
--BEFORE CODE 27.10.2014
--Измение колонки stavka таблицы CREDIT_STAVKI_SUM
UPDATE [dbo].[CREDIT_STAVKI_SUM] SET [STAVKA] =((0)) WHERE [STAVKA] IS NULL
ALTER TABLE [dbo].[CREDIT_STAVKI_SUM] ALTER COLUMN [STAVKA] numeric(7, 4) NOT NULL 
GO

GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REC_CARD_OPTIONS', 'Настройки "Заявка на получение наличности"', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_REC_CARD_OPTIONS', NAME = 'Настройки "Заявка на получение наличности"', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_REC_CARD_OPTIONS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPT_TYP_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REC_CARD_OPT_TYP_LINK', 'Ссылка на операцию', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_REC_CARD_OPT_TYP_LINK', NAME = 'Ссылка на операцию', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_REC_CARD_OPT_TYP_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_TYP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REC_CARD_TYP_NAME', 'Наим тип. опер.', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_REC_CARD_TYP_NAME', NAME = 'Наим тип. опер.', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_REC_CARD_TYP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_TYP_LINK_V')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REC_CARD_TYP_LINK_V', 'Ссылка на операцию внебюджет', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_REC_CARD_TYP_LINK_V', NAME = 'Ссылка на операцию внебюджет', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_REC_CARD_TYP_LINK_V'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_TYP_NAME_V')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REC_CARD_TYP_NAME_V', 'Наим тип. опер.(внеб)', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_REC_CARD_TYP_NAME_V', NAME = 'Наим тип. опер.(внеб)', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_REC_CARD_TYP_NAME_V'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_DELIM_SUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REC_CARD_DELIM_SUMMA', 'Разделитель суммы', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_REC_CARD_DELIM_SUMMA', NAME = 'Разделитель суммы', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_REC_CARD_DELIM_SUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_DELIM_KBK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REC_CARD_DELIM_KBK', 'Разделитель КБК', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_REC_CARD_DELIM_KBK', NAME = 'Разделитель КБК', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_REC_CARD_DELIM_KBK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS_KODBP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REC_CARD_OPTIONS_KODBP', 'Выводить код по сводному реестру', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_REC_CARD_OPTIONS_KODBP', NAME = 'Выводить код по сводному реестру', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_REC_CARD_OPTIONS_KODBP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS_DATE_POD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REC_CARD_OPTIONS_DATE_POD', 'Выводить дату подписи при печати', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_REC_CARD_OPTIONS_DATE_POD', NAME = 'Выводить дату подписи при печати', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_REC_CARD_OPTIONS_DATE_POD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_POST_GL_BUH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REC_CARD_POST_GL_BUH', 'Выгружать должность гл. бухгалтера', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_REC_CARD_POST_GL_BUH', NAME = 'Выгружать должность гл. бухгалтера', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_REC_CARD_POST_GL_BUH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_POST_RUK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REC_CARD_POST_RUK', 'Выгружать должность руководителя', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_REC_CARD_POST_RUK', NAME = 'Выгружать должность руководителя', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_REC_CARD_POST_RUK'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS', 'TITLE', 'Настройки "Заявка на получение наличных денег"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS', 'SAVE_OBJECT_METHOD', 'X_SAVE_DOCUMENT_OPTIONS()'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''DOCUMENTS_RECEPTION_CARD_OPTIONS'')'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_OPTIONS(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS', 'OPTIONS_OBJECT_CODE', 'DOC_REC_CARD_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPT_TYP_LINK', 'TITLE', 'Ссылка на операцию'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPT_TYP_LINK', 'CONTROLSOURCE', 'm.cAlias + ".TYP_LINK"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPT_TYP_LINK', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPT_TYP_LINK', 'SHORT_CODE_OBJ', 'TYP_LINK'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPT_TYP_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TYP_LINK"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPT_TYP_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME', 'TITLE', 'Типовая операция'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TYP_LINK", "TYP_NAME", "DOCUMENTS_RECEPTION_CASH")'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME', 'REFERENCE_TO_DICT', 'DOC_REC_CARD_OPT_TYP_LINK'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(120)'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME', 'SHORT_CODE_OBJ', 'TYP_NAME'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TYP_NAME"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME', 'CONTROL_NAME_EDIT', 'Asel_spr1'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_LINK_V', 'TITLE', 'Ссылка на операцию внебюджет'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_LINK_V', 'CONTROLSOURCE', 'm.cAlias + ".TYP_LINK_V"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_LINK_V', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_LINK_V', 'SHORT_CODE_OBJ', 'TYP_LINK_V'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_LINK_V', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TYP_LINK_V"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_LINK_V', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME_V', 'TITLE', 'Типовая операция(внеб)'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME_V', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TYP_LINK_V", "TYP_NAME_V", "DOC_RECEPTION_CARD")'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME_V', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME_V', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME_V', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME_V', 'REFERENCE_TO_DICT', 'DOC_REC_CARD_TYP_LINK_V'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME_V', 'TYPE_FIELD_DICT', 'VARCHAR(120)'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME_V', 'SHORT_CODE_OBJ', 'TYP_NAME_V'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME_V', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TYP_NAME_V"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME_V', 'CONTROL_NAME_EDIT', 'Asel_spr2'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_TYP_NAME_V', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_SUMMA', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_SUMMA', 'CONTROLSOURCE', 'm.cALIAS+".DELIM"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_SUMMA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_SUMMA', 'CONTROL_TYPE', ''
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_SUMMA', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_SUMMA', 'TYPE_FIELD_DICT', 'VarChar(1)'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_SUMMA', 'SHORT_CODE_OBJ', 'DELIM'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_SUMMA', 'CONTROLSOURCE_EDIT', 'm.cALIAS+".DELIM"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_SUMMA', 'CONTROL_NAME_EDIT', 'Delim_summa'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_KBK', 'TITLE', 'Разделитель КБК'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_KBK', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_KBK', 'CONTROLSOURCE', 'm.cALIAS+".DELIMKBK"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_KBK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_KBK', 'CONTROL_TYPE', ''
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_KBK', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_KBK', 'TYPE_FIELD_DICT', 'VarChar(1)'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_KBK', 'SHORT_CODE_OBJ', 'DELIMKBK'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_KBK', 'CONTROLSOURCE_EDIT', 'm.cALIAS+".DELIMKBK"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_DELIM_KBK', 'CONTROL_NAME_EDIT', 'DelimKBK'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_KODBP', 'TITLE', 'Выводить код по сводному реестру'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_KODBP', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_KODBP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_KODBP', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_KODBP', 'TYPE_FIELD_DICT', 'BIT'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_KODBP', 'SHORT_CODE_OBJ', 'KODBP'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_KODBP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".KODBP"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_KODBP', 'CONTROL_NAME_EDIT', 'aChkKodBP'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_DATE_POD', 'TITLE', 'Выводить дату подписи при печати'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_DATE_POD', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_DATE_POD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_DATE_POD', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_DATE_POD', 'TYPE_FIELD_DICT', 'BIT'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_DATE_POD', 'SHORT_CODE_OBJ', 'DATE_POD'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_DATE_POD', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE_POD"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_DATE_POD', 'CONTROL_NAME_EDIT', 'aChkDatePod'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_GL_BUH', 'TITLE', 'Выгружать должность гл. бухгалтера'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_GL_BUH', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_GL_BUH', 'CONTROLSOURCE', 'm.cALIAS+ ".POST_GL"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_GL_BUH', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_GL_BUH', 'CONTROL_TYPE', ''
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_GL_BUH', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_GL_BUH', 'TYPE_FIELD_DICT', 'BIT'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_GL_BUH', 'SHORT_CODE_OBJ', 'POST_GL'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_GL_BUH', 'CONTROLSOURCE_EDIT', 'm.cALIAS+ ".POST_GL"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_GL_BUH', 'CONTROL_NAME_EDIT', 'aChkPostGl'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_RUK', 'TITLE', 'Выгружать должность руководителя'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_RUK', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_RUK', 'CONTROLSOURCE', 'm.cALIAS+ ".POST_RUK"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_RUK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_RUK', 'CONTROL_TYPE', ''
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_RUK', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_RUK', 'TYPE_FIELD_DICT', 'BIT'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_RUK', 'SHORT_CODE_OBJ', 'POST_RUK'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_RUK', 'CONTROLSOURCE_EDIT', 'm.cALIAS+ ".POST_RUK"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_POST_RUK', 'CONTROL_NAME_EDIT', 'aChkPostRuk'
GO
EXECUTE X_FORM_VIEW_OPTIONS 'DOC_REC_CARD_OPTIONS'
GO

GO

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


IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[DF_G_PROV_GUID]'))
ALTER TABLE [dbo].[G_PROV] 
ADD CONSTRAINT [DF_G_PROV_GUID] DEFAULT (NEWID()) FOR [GUID]
GO


UPDATE p SET [GUID] = NEWID()
FROM dbo.[G_PROV] p WHERE [GUID] IS NULL
GO



GO
--Измение колонки ACC_ESN таблицы SAL_SFIN
ALTER TABLE [dbo].[SAL_SFIN] ALTER COLUMN [ACC_ESN] varchar(10) NULL 
GO


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


IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[DF_SAL_SFIN_USED_SRC]'))
ALTER TABLE [dbo].[SAL_SFIN] 
ADD CONSTRAINT [DF_SAL_SFIN_USED_SRC] DEFAULT ((1)) FOR [USED]
GO


UPDATE S SET [USED] = 1
FROM dbo.SAL_SFIN  s WHERE USED IS NULL
GO


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

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

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

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

GO
--Таблица SZV_K_PACHKA
IF not exists(select * from sysobjects where id = object_id('[dbo].[SZV_K_PACHKA]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[SZV_K_PACHKA] (
	[link] int NOT NULL IDENTITY(1,1) ,
	[numer] numeric(5, 0) NOT NULL ,
	[date] datetime NOT NULL ,
	[type_sved] tinyint NOT NULL ,
	[link_dep] int NOT NULL ,
	[proverka] tinyint NOT NULL ,
	[LINK_ISHOD] int NULL )
GO

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

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

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

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

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

GO

--Таблица SZV_K_svedenia
IF not exists(select * from sysobjects where id = object_id('[dbo].[SZV_K_svedenia]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[SZV_K_svedenia] (
	[link] int NOT NULL IDENTITY(1,1) ,
	[link_up] int NOT NULL ,
	[pachka] int NOT NULL ,
	[orders] int NOT NULL ,
	[link_pers] int NOT NULL ,
	[dper_vn_m] int NOT NULL ,
	[dper_vn_d] int NOT NULL ,
	[dper_oz_m] int NOT NULL ,
	[dper_oz_d] int NOT NULL ,
	[terr_usl] varchar(10) NOT NULL ,
	[terr_koef] numeric(18, 2) NOT NULL ,
	[all_stazh_y] int NOT NULL ,
	[all_stazh_m] int NOT NULL ,
	[all_stazh_d] int NOT NULL ,
	[DATE_BEG] datetime NULL ,
	[DATE_END] datetime NULL )
GO

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

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

--Индексы

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SZV_K_0_SZV_K]'))
ALTER TABLE [dbo].[SZV_K_svedenia] 
ADD CONSTRAINT [FK_SZV_K_0_SZV_K] FOREIGN KEY ([link_up]) REFERENCES [dbo].[SZV_K_PACHKA] ([link])
 ON DELETE CASCADE
 ON UPDATE CASCADE
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SZV_K_0_PERSON]'))
ALTER TABLE [dbo].[SZV_K_svedenia] 
ADD CONSTRAINT [FK_SZV_K_0_PERSON] FOREIGN KEY ([link_pers]) REFERENCES [dbo].[PERSON] ([LINK])
 ON DELETE CASCADE
 ON UPDATE CASCADE
GO

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

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

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

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

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

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

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

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

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

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

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

GO
CREATE TRIGGER [dbo].[SZV_K_SVEDENIA_SA_DELETE] ON dbo.SZV_K_svedenia 
FOR DELETE
AS

update SZV_K_pachka set proverka = 0
where
	link in (select link_up from DELETED)




GO


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

GO
CREATE TRIGGER [dbo].[SZV_K_SVEDENIA_SA_INSUPD] ON dbo.SZV_K_svedenia 
FOR INSERT, UPDATE
AS

update SZV_K_pachka set proverka = 0
where
	link in (select link_up from INSERTED)



GO


GO

--Таблица SZV_K_sved_WORK_DEP
IF not exists(select * from sysobjects where id = object_id('[dbo].[SZV_K_sved_WORK_DEP]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[SZV_K_sved_WORK_DEP] (
	[link] int NOT NULL IDENTITY(1,1) ,
	[link_up] int NOT NULL ,
	[orders] int NOT NULL ,
	[vid_work] varchar(10) NULL ,
	[NAME_DEP] varchar(254) NOT NULL ,
	[INN] varchar(12) NOT NULL ,
	[KPP] varchar(9) NOT NULL ,
	[OKPO] varchar(20) NOT NULL )
GO

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

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

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SZV_K_sved_WORK_DEP_SZV_K_svedenia]'))
ALTER TABLE [dbo].[SZV_K_sved_WORK_DEP] 
ADD CONSTRAINT [FK_SZV_K_sved_WORK_DEP_SZV_K_svedenia] FOREIGN KEY ([link_up]) REFERENCES [dbo].[SZV_K_svedenia] ([link])
 ON DELETE CASCADE
 ON UPDATE CASCADE
GO


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

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

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

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

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


--Триггеры

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

GO
CREATE TRIGGER [dbo].[SZV_K_sved_WORK_DEP_SA_DELETE] ON dbo.SZV_K_sved_WORK_DEP 
FOR DELETE
AS

update SZV_K_pachka set proverka = 0
where
	link in	(select S. link_up from dbo.SZV_K_SVEDENIA S 
							   INNER JOIN DELETED I on S.link = I.link_up)



GO


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

GO
CREATE TRIGGER [dbo].[SZV_K_sved_WORK_DEP_SA_INSUPD] ON dbo.SZV_K_sved_WORK_DEP
FOR INSERT, UPDATE
AS

update SZV_K_pachka set proverka = 0
where
	link in (select S. link_up from dbo.SZV_K_SVEDENIA S 
							   INNER JOIN DELETED I on S.link = I.link_up)


GO




GO

--Таблица SZV_K_stazh
IF not exists(select * from sysobjects where id = object_id('[dbo].[SZV_K_stazh]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[SZV_K_stazh] (
	[link] int NOT NULL IDENTITY(1,1) ,
	[link_up] int NOT NULL ,
	[orders] int NOT NULL ,
	[date1] datetime NOT NULL ,
	[date2] datetime NOT NULL ,
	[ter_usl] varchar(10) NULL ,
	[ter_koef] numeric(18, 2) NULL ,
	[osob_usl] varchar(10) NULL ,
	[osob_k1] varchar(20) NULL ,
	[osob_k2] varchar(20) NULL ,
	[osob_k3] varchar(20) NULL ,
	[is_osnov] varchar(10) NULL ,
	[is_dop] varchar(20) NULL ,
	[is_dop_m] tinyint NULL ,
	[is_dop_d] tinyint NULL ,
	[ud_osnov] varchar(10) NULL ,
	[ud_dop_m] int NULL ,
	[ud_dop_d] int NULL ,
	[ud_dop_k] numeric(18, 2) NULL ,
	[POST] varchar(254) NULL )
GO

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

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

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SZV_K_stazh_SZV_K_sved_WORK_DEP]'))
ALTER TABLE [dbo].[SZV_K_stazh] 
ADD CONSTRAINT [FK_SZV_K_stazh_SZV_K_sved_WORK_DEP] FOREIGN KEY ([link_up]) REFERENCES [dbo].[SZV_K_sved_WORK_DEP] ([link])
 ON DELETE CASCADE
 ON UPDATE CASCADE
GO

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

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

GO
CREATE TRIGGER [dbo].[SZV_K_stazh_SA_DELETE] ON [dbo].[SZV_K_stazh] 
FOR DELETE
AS

update SZV_K_pachka set proverka = 0
where
	link in
	(select link_up from dbo.SZV_K_SVEDENIA  
					where link in 
					      (select s.link_up from dbo.SZV_K_sved_WORK_DEP s 
										  INNER JOIN DELETED I on S.link = I.link_up
					      )
	)


GO


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

GO
CREATE TRIGGER [dbo].[SZV_K_stazh_SA_INSUPD] ON [dbo].[SZV_K_stazh] 
FOR INSERT, UPDATE
AS

update SZV_K_pachka set proverka = 0
WHERE
	link in
	(select link_up from dbo.SZV_K_SVEDENIA  
					where link in 
					      (select s.link_up from dbo.SZV_K_sved_WORK_DEP s 
										INNER JOIN INSERTED I on S.link = I.link_up
					      )
	)



GO




GO

--Таблица SZV_K_stazh_DOP
IF not exists(select * from sysobjects where id = object_id('[dbo].[SZV_K_stazh_DOP]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[SZV_K_stazh_DOP] (
	[link] int NOT NULL IDENTITY(1,1) ,
	[link_up] int NOT NULL ,
	[orders] int NOT NULL ,
	[date1] datetime NOT NULL ,
	[date2] datetime NOT NULL ,
	[ter_usl] varchar(10) NULL ,
	[ter_koef] numeric(18, 2) NULL ,
	[osob_usl] varchar(10) NULL ,
	[osob_k1] varchar(20) NULL ,
	[osob_k2] varchar(20) NULL ,
	[osob_k3] varchar(20) NULL ,
	[is_osnov] varchar(10) NULL ,
	[is_dop] varchar(20) NULL ,
	[is_dop_m] tinyint NULL ,
	[is_dop_d] tinyint NULL ,
	[ud_osnov] varchar(10) NULL ,
	[ud_dop_m] int NULL ,
	[ud_dop_d] int NULL ,
	[ud_dop_k] numeric(18, 2) NULL ,
	[POST] varchar(254) NULL )
GO

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

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

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SZV_K_stazh_DOP_SZV_K_stazh]'))
ALTER TABLE [dbo].[SZV_K_stazh_DOP] 
ADD CONSTRAINT [FK_SZV_K_stazh_DOP_SZV_K_stazh] FOREIGN KEY ([link_up]) REFERENCES [dbo].[SZV_K_stazh] ([link])
 ON DELETE CASCADE
 ON UPDATE CASCADE
GO

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

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

GO
CREATE TRIGGER [dbo].[SZV_K_stazh_DOP_SA_DELETE] ON [dbo].[SZV_K_stazh_DOP] 
FOR DELETE
AS



update SZV_K_pachka set proverka = 0
where
	link in
	(select link_up from dbo.SZV_K_SVEDENIA  
					where link in 
					      (select link_up from dbo.SZV_K_sved_WORK_DEP 
										  WHERE link IN
													(  select s.link_up from dbo.SZV_K_stazh s 
																		INNER JOIN DELETED I on S.link = I.link_up
													)
					      )
	)




GO


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

GO
CREATE TRIGGER [dbo].[SZV_K_stazh_DOP_SA_INSUPD] ON [dbo].[SZV_K_stazh_DOP] 
FOR INSERT, UPDATE
AS

update SZV_K_pachka set proverka = 0
where
	link in
	(select link_up from dbo.SZV_K_SVEDENIA  
					where link in 
					      (select link_up from dbo.SZV_K_sved_WORK_DEP 
										  WHERE link IN
													(  select s.link_up from dbo.SZV4_stazh s 
																	INNER JOIN INSERTED I on S.link = I.link_up
													)
					      )
	)





GO








GO
IF NOT EXISTS(SELECT * FROM S_BANK_FORMAT_BASE WHERE ltrim(rtrim(CODE)) = 'INN')
BEGIN 
	INSERT INTO S_BANK_FORMAT_BASE (CODE, NAME , FTYPE, FVALUE, DATATYPE )
	SELECT 'INN',
			'ИНН сотрудника', 
			1,
			'',
			'C'
END 

GO


IF NOT EXISTS(SELECT * FROM S_BANK_FORMAT_BASE WHERE ltrim(rtrim(CODE)) = 'DEP_ACC_M')
BEGIN 
	INSERT INTO S_BANK_FORMAT_BASE (CODE, NAME , FTYPE, FVALUE, DATATYPE )
	SELECT 'DEP_ACC_M',
			'Счет списания', 
			1,
			'',
			'C'
END			
GO

IF NOT EXISTS(SELECT * FROM S_BANK_FORMAT_BASE WHERE ltrim(rtrim(CODE)) = 'KASS_PHONE')
BEGIN 
	INSERT INTO S_BANK_FORMAT_BASE (CODE, NAME , FTYPE, FVALUE, DATATYPE )
	SELECT 'KASS_PHONE',
			'Телефон кассира', 
			1,
			'',
			'C'
END			
GO

IF NOT EXISTS(SELECT * FROM S_BANK_FORMAT_BASE WHERE ltrim(rtrim(CODE)) = 'NOTE')
BEGIN 
	INSERT INTO S_BANK_FORMAT_BASE (CODE, NAME , FTYPE, FVALUE, DATATYPE )
	SELECT 'NOTE',
			'Комментарий', 
			1,
			'',
			'C'
END			
GO

IF NOT EXISTS(SELECT * FROM S_BANK_FORMAT_BASE WHERE ltrim(rtrim(CODE)) = 'EXCH_DATE')
BEGIN 
	INSERT INTO S_BANK_FORMAT_BASE (CODE, NAME , FTYPE, FVALUE, DATATYPE )
	SELECT 'EXCH_DATE',
			'Дата файла', 
			1,
			'',
			'D'
END			
GO

IF NOT EXISTS(SELECT * FROM S_BANK_FORMAT_BASE WHERE ltrim(rtrim(CODE)) = 'MON')
BEGIN 
	INSERT INTO S_BANK_FORMAT_BASE (CODE, NAME , FTYPE, FVALUE, DATATYPE )
	SELECT 'MON',
			'Месяц по ведомости', 
			1,
			'',
			'N'
END			
GO

IF NOT EXISTS(SELECT * FROM S_BANK_FORMAT_BASE WHERE ltrim(rtrim(CODE)) = 'NEW_STR1')
BEGIN 
	INSERT INTO S_BANK_FORMAT_BASE (CODE, NAME , FTYPE, FVALUE, DATATYPE )
	
	SELECT 'NEW_STR1',
			'Переход на новую строку1', 
			2,
			'CHR(13)+CHR(10)',
			'C'
END			
GO



GO
--Измение колонки DOP таблицы S_BANK_FORMAT_TABLE
IF COLUMNPROPERTY(object_id('[dbo].[S_BANK_FORMAT_TABLE]'), 'DOP', 'AllowsNull') IS null
	ALTER TABLE [dbo].[S_BANK_FORMAT_TABLE] ADD [DOP] tinyint NULL 
GO
GO

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

GO
CREATE FUNCTION dbo.SA_GET_DEP_ACC(@LINK_DEP INT, @LINK_ACC INT = NULL, @LINK_SALSFIN INT = NULL, @DEP_ACC INT = NULL)
RETURNS INT
AS
BEGIN

SET @DEP_ACC = 
	(
	SELECT TOP 1 LINK 
	FROM
		(
		--СЧЕТ УЖЕ ИЗВЕСТЕН, ПРОВЕРИТЬ ЧТОБЫ БЫЛ ОТ СВОЕЙ ОРГАНИЗАЦИИ
		SELECT ORD = 0, DA.LINK
		FROM dbo.DEPARTMENT_ACCOUNTS DA
		WHERE DA.LINK = @DEP_ACC AND DA.LINK_UP = @LINK_DEP
		
		--СЧЕТ ЗАДАН В ЗАРПЛАТСКОМ ИСТОЧНИКЕ ФИН
		UNION ALL
		SELECT ORD = 1, DA.LINK
		FROM dbo.SAL_SFIN SF INNER JOIN dbo.DEPARTMENT_ACCOUNTS DA ON DA.LINK = SF.LINK_LACC
		WHERE SF.LINK = @LINK_SALSFIN AND DA.LINK_UP = @LINK_DEP
		
		--РАСЧЕТНЫЙ С ПРИОРИТЕТОМ СЧЕТА ПО УМОЛЧАНИЮ
		UNION ALL
		SELECT ORD = 2, DA.LINK
		FROM
			dbo.DEPARTMENTS D
			INNER JOIN dbo.DEPARTMENT_ACCOUNTS DA ON D.LINK = DA.LINK_UP AND D.MAIN_LINK = DA.LINK
			INNER JOIN dbo.S_ACCOUNTS SA ON SA.LINK = @LINK_ACC
		WHERE
			D.LINK = @LINK_DEP
			AND DA.[TYPE] = 1
			AND SA.CODE LIKE '%.21'
		---
		UNION ALL
		SELECT ORD = 3, DA.LINK
		FROM
			dbo.DEPARTMENT_ACCOUNTS DA
			INNER JOIN dbo.S_ACCOUNTS SA ON SA.LINK = @LINK_ACC
		WHERE
			DA.LINK_UP = @LINK_DEP 
			AND DA.[TYPE] = 1
			AND SA.CODE LIKE '%.21'
			
		--ЛИЦЕВОЙ С ПРИОРИТЕТОМ СЧЕТА ПО УМОЛЧАНИЮ
		UNION ALL
		SELECT ORD = 4, DA.LINK
		FROM
			dbo.DEPARTMENTS D
			INNER JOIN dbo.DEPARTMENT_ACCOUNTS DA ON D.LINK = DA.LINK_UP AND D.MAIN_LINK = DA.LINK
			INNER JOIN dbo.S_ACCOUNTS SA ON SA.LINK = @LINK_ACC
		WHERE
			D.LINK = @LINK_DEP
			AND DA.[TYPE] = 2
			AND SA.cSource = '1'
		---	
		UNION ALL
		SELECT ORD = 5, DA.LINK
		FROM
			dbo.DEPARTMENT_ACCOUNTS DA
			INNER JOIN dbo.S_ACCOUNTS SA ON SA.LINK = @LINK_ACC
		WHERE
			DA.LINK_UP = @LINK_DEP
			AND DA.[TYPE] = 2
			AND SA.cSource = '1'
						
		--ВНЕБЮДЖЕТНЫЙ С ПРИОРИТЕТОМ СЧЕТА ПО УМОЛЧАНИЮ
		UNION ALL
		SELECT ORD = 6, DA.LINK
		FROM
			dbo.DEPARTMENTS D
			INNER JOIN dbo.DEPARTMENT_ACCOUNTS DA ON D.LINK = DA.LINK_UP AND D.MAIN_LINK = DA.LINK
		WHERE
			D.LINK = @LINK_DEP
			AND DA.[TYPE] = 4
		--	
		UNION ALL
		SELECT ORD = 7, DA.LINK
		FROM
			dbo.DEPARTMENT_ACCOUNTS DA
		WHERE
			DA.LINK_UP = @LINK_DEP
			AND DA.[TYPE] = 4
			
		--ПРОЧИЕ С ПРИОРИТЕТОМ СЧЕТА ПО УМОЛЧАНИЮ
		UNION ALL
		SELECT ORD = 8, DA.LINK
		FROM
			dbo.DEPARTMENTS D
			INNER JOIN dbo.DEPARTMENT_ACCOUNTS DA ON D.LINK = DA.LINK_UP AND D.MAIN_LINK = DA.LINK
		WHERE
			D.LINK = @LINK_DEP
			AND DA.[TYPE] = 2
		--	
		UNION ALL
		SELECT ORD = 9, DA.LINK
		FROM
			dbo.DEPARTMENT_ACCOUNTS DA
		WHERE
			DA.LINK_UP = @LINK_DEP
			AND DA.[TYPE] = 2							
		) T
	ORDER BY ORD
	)	

RETURN @DEP_ACC

END

GO

GRANT EXECUTE ON dbo.[SA_GET_DEP_ACC] TO PUBLIC

GO

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

GO

CREATE  FUNCTION dbo.xd_get_cj_info(@varKSparLink int)
RETURNS VARCHAR(254)
AS
BEGIN

RETURN
	LEFT((SELECT TOP 1 
		'Строка журнала операций по з/п: ' + 
		+ ' ФИО: ' +  RTRIM(ISNULL(LEFT(COALESCE(LTRIM(ISNULL(P1.FM,P2.FM)) + ' ' + LTRIM(ISNULL(P1.IM,P2.IM)) + ' ' + LTRIM(ISNULL(P1.OT,P2.OT)),'Не заполнено'),100),'нет данных')) 
		+ ' Операция: ' +  RTRIM(P.NAME) 	
		 + ' Месяц: '+ LTRIM(RTRIM(STR(MONTH(JC.PERIOD_BEGIN))))
		 + ' Год: '+ LTRIM(RTRIM(STR(YEAR(JC.PERIOD_BEGIN))))
	FROM 
		dbo.CALCULATE_JURNAL JC
		INNER JOIN dbo.PAYS P ON JC.LINK_PAYS = P.LINK
		LEFT JOIN dbo.EMPL E ON E.LINK = JC.LINK_EMPL
		LEFT JOIN dbo.PERSON P1 ON P1.LINK = E.PERS_LINK
		LEFT JOIN dbo.PERSON P2 ON P2.LINK = JC.PERS_LINK
	WHERE
		JC.LINK = @varKSparLink
	),254)	

END
GO

GRANT EXECUTE ON dbo.[xd_get_cj_info] TO PUBLIC

GO

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

GO

CREATE VIEW [dbo].SA_SZV_K_PACHKA
as
SELECT
	P.link,
	CODE = 
	(case TYPE_SVED when 2 then 'Корректирующие'+ SPACE(1) when 3 then 'Отменяющие'+ SPACE(1) else 'Исходные' end)
	+ 'cведения' 
	+ 	SPACE(1) +  'от' + SPACE(1) + CONVERT(VARCHAR(10),date,104), 
	numer, 
	[date], 
	[type_sved], n_type_sved = (case type_sved when 1 then 'исходные' when 2 then 'корректирующие' when 3 then 'отменяющие' else '' end),
	link_dep,
	proverka,
	nproverka = (case when proverka = 0 then 'Не выполнена' else 'Выполнена' end),
	P.LINK_ISHOD
	--------------------------------------------------------------------------			
FROM 
	dbo.SZV_K_PACHKA P 
group by 
		P.link, numer, [date],[type_SVED], link_dep, proverka,P.LINK_ISHOD



GO


GRANT SELECT ON dbo.[SA_SZV_K_PACHKA] TO PUBLIC

GO




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

GO



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


GO


GRANT SELECT ON dbo.[SA_SZV4_SPR_SPR] TO PUBLIC

GO




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

GO
CREATE VIEW [dbo].SA_SZV_K_sved_WORK_DEP
as

SELECT 
	link = S.link_up,
	link1 = S.link, 
	S.orders,
	S.NAME_DEP,
	S.INN,S.KPP,S.OKPO, 
	VID_WORK = LTRIM(RTRIM(V.CODE)),
	VID_WORK_N = LTRIM(RTRIM(V.NAME))
FROM 
	dbo.SZV_K_sved_WORK_DEP S
	inner join dbo.SZV4_SPR v on v.SPR_CODE = 'VID_WORK' AND  v.code = S.vid_work


GO


GRANT SELECT ON dbo.[SA_SZV_K_sved_WORK_DEP] TO PUBLIC

GO




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

GO

CREATE  VIEW [dbo].S_BANK_FORMAT_TABLE_VIEW
AS
	SELECT 
		T.LINK, 
		T.LINK_PART,
		T.CODE,
		T.LINK_FLD,
		B.CODE AS CODE_FLD,
		B.NAME AS NAME_FLD,
		T.ORDERS,
		T.IsFixed,
		T.MaxLen,
		T.Decimals,
		T.PadType,
		T.RightBorder,
		T.PaddingChar,
		T.CODE_DBF,
		T.TYPE_DBF,
		T.CONST_VALUE,
		T.FUNC,
		T.DOP,
		B.FTYPE,
		B.FVALUE,
		B.DATATYPE
FROM 
	dbo.S_BANK_FORMAT_TABLE T 
	INNER JOIN S_BANK_FORMAT_BASE B ON T.LINK_FLD = B.LINK


GO


GRANT SELECT ON dbo.[S_BANK_FORMAT_TABLE_VIEW] TO PUBLIC

GO


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

GO

CREATE  VIEW [dbo].SA_SZV_K_STAZH
as

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

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

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

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

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

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

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

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



GO


GRANT SELECT ON dbo.[SA_SZV_K_STAZH] TO PUBLIC

GO




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

GO

CREATE  VIEW [dbo].SA_SZV_K_STAZH_DOP
as

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

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

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

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

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

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

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

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



GO


GRANT SELECT ON dbo.[SA_SZV_K_STAZH_DOP] TO PUBLIC

GO



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

GO
CREATE VIEW [dbo].SA_PU_REPORTS
AS

SELECT ORD = 1, YB = 1994, YE = 2009, [NAME] = 'СЗВ-4-1 (Индивидуальные сведения)', REP_CODE = 'SZV4_PER_SZV41#forma = 1#Нет данных для этой формы'
UNION
SELECT ORD = 2, YB = 1994, YE = 2009, [NAME] = 'СЗВ-4-2 (Списочная форма)', REP_CODE = 'SZV4_PER_SZV42#forma = 2#Нет данных для этой формы'
UNION
SELECT ORD = 3, YB = 1994, YE = 2009, [NAME] = 'АДВ-6-1 (Опись документов)', REP_CODE = 'SZV4_PER_ADV61'
UNION
SELECT ORD = 4, YB = 1994, YE = 2009, [NAME] = 'АДВ-11 (Ведомость уплаты страховых взносов)', REP_CODE = 'SZV4_PER_ADV11'
UNION
SELECT ORD = 5, YB = 1994, YE = 2009, [NAME] = 'Все формы', REP_CODE = 'SZV4_PER_SZV41#forma = 1,SZV4_PER_SZV42#forma = 2,SZV4_PER_ADV61,SZV4_PER_ADV11'

UNION
SELECT ORD = 1, YB = 2010, YE = 2012, [NAME] = 'СЗВ-6-1 (Индивидуальные сведения)', REP_CODE = 'SZV4_PER_SZV61#forma = 1#Нет данных для этой формы'
UNION
SELECT ORD = 2, YB = 2010, YE = 2012, [NAME] = 'СЗВ-6-2 (Списочная форма)', REP_CODE = 'SZV4_PER_SZV62#forma = 2#Нет данных для этой формы'
UNION
SELECT ORD = 3, YB = 2010, YE = 2012, [NAME] = 'АДВ-6-3 (Опись документов)', REP_CODE = 'SZV4_PER_ADV63'
UNION
SELECT ORD = 4, YB = 2010, YE = 2014, [NAME] = 'АДВ-6-2 (Опись сведений)', REP_CODE = 'SZV4_PER_ADV62'
UNION
SELECT ORD = 5, YB = 2010, YE = 2012, [NAME] = 'Все формы', REP_CODE = 'SZV4_PER_SZV61#forma = 1,SZV4_PER_SZV62#forma = 2,SZV4_PER_ADV63,SZV4_PER_ADV62'
UNION
SELECT ORD = 6, YB = 2010, YE = 2013, [NAME] = 'СПВ-1 (Для выходящих на пенсию)', REP_CODE = 'SZV4_PER_SPV1#EVAL(THISFORM.ALIAS + ".TYPE")=2#Только для типа сведений "Назначение пенсии"!'
UNION
SELECT ORD = 6, YB = 2014, YE = 2999, [NAME] = 'СПВ-2 (Для выходящих на пенсию)', REP_CODE = 'SZV4_PER_SPV2#EVAL(THISFORM.ALIAS + ".TYPE")=2#Только для типа сведений "Назначение пенсии"!'
UNION
SELECT ORD = 7, YB = 2010, YE = 2013, [NAME] = 'Все формы (Для выходящих на пенсию)', REP_CODE = 'SZV4_PER_SPV1#EVAL(THISFORM.ALIAS + ".TYPE")=2,SZV4_PER_ADV63#EVAL(THISFORM.ALIAS + ".TYPE")=2,SZV4_PER_ADV62#EVAL(THISFORM.ALIAS + ".TYPE")=2'
UNION
SELECT ORD = 7, YB = 2014, YE = 2999, [NAME] = 'Все формы (Для выходящих на пенсию)', REP_CODE = 'SZV4_PER_SPV2#EVAL(THISFORM.ALIAS + ".TYPE")=2,SZV4_PER_ADV62#EVAL(THISFORM.ALIAS + ".TYPE")=2'


UNION
SELECT ORD = 1, YB = 2013, YE = 2014, [NAME] = 'СЗВ-6-4 (Сведения о сумме выплат и страховом стаже застрахованного лица)', REP_CODE = 'SZV4_PRINT_SZV64# #Нет данных для этой формы'
UNION
SELECT ORD = 3, YB = 2013, YE = 2014, [NAME] = 'АДВ-6-5 (Опись документов)', REP_CODE = 'SZV4_PRINT_ADV65'
UNION
SELECT ORD = 5, YB = 2013, YE = 2014, [NAME] = 'Все формы', REP_CODE = 'SZV4_PRINT_SZV64,SZV4_PRINT_ADV65,SZV4_PER_ADV62'


GO


GRANT SELECT ON dbo.[SA_PU_REPORTS] TO PUBLIC

GO



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

GO

CREATE VIEW dbo.SA_SZV4_EXPORT_FORMATS_14
AS
	 	SELECT FNAME = 'Формат 7.00 (с 01.01.2010 г.)', PROC_NAME = 'SZV4_EXPORT_PFR_700_14', PRG_SKRIPT = '', DIR = 'PF'

GO


GRANT SELECT ON dbo.[SA_SZV4_EXPORT_FORMATS_14] TO PUBLIC

GO




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

GO

CREATE VIEW dbo.SS_SZVK_EXPORT_FORMATS
AS
	SELECT FNAME = 'Формат 7.00 (с 01.01.2007 г.)', PROC_NAME = 'SS_SZVK_EXPORT_700', 
		PRG_SKRIPT = /*'IF NVL(X_GET_NASTR("SA_SZV4_OPT2 "),1) = 1
				MESSAGEBOX("АДВ-11 должны быть без копеек! Задайте способ округления в настройках!",48,"Предупреждение")
				endif'*/ '',
		DIR = 'PF'


GO


GRANT SELECT ON dbo.[SS_SZVK_EXPORT_FORMATS] TO PUBLIC

GO



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

GO
CREATE VIEW dbo.DIS_ORDER
AS
WITH 
	CH AS (

	SELECT 
		ORDERS = 1, LINK_DIS = LINK_UP, LINK = LINK_UP, LINK_SELF = LINK_UP
	FROM 
		[dbo].[SDOC_DIS] A

	UNION ALL

	--являются продолжениями
	SELECT ORDERS = ORDERS + 1, CH.LINK_DIS, D.LINK_UP, D.REF_DOC
	FROM 
		(SELECT LINK_UP AS LINK FROM [dbo].[SDOC_DIS]) AS C1 --Список больничных
		INNER JOIN [dbo].[SDOC_DIS] D ON C1.LINK = D.LINK_UP
		INNER JOIN CH ON CH.LINK_SELF = D.LINK_UP
) 
	SELECT ORDERS, CHILD = LINK_DIS, PARENT = LINK_SELF FROM CH WHERE LINK_SELF IS NOT NULL

GO


GRANT SELECT ON dbo.[DIS_ORDER] TO PUBLIC

GO

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

GO
CREATE VIEW [dbo].DIS_FIRST
AS
WITH CH AS (
	SELECT 
		LINK = LINK_UP, FIRST_LINK = LINK_UP
	FROM 
		[dbo].[SDOC_DIS]
	WHERE
		REF_DOC IS NULL

	UNION ALL

	--какой источник менялся на последний
	SELECT LINK = B.LINK_UP, CH.FIRST_LINK
	FROM
		CH
		INNER JOIN [dbo].[SDOC_DIS] B ON B.REF_DOC = CH.LINK

) SELECT LINK, FIRST_LINK FROM CH

GO

GRANT SELECT ON dbo.[DIS_FIRST] TO PUBLIC

GO

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

GO
CREATE VIEW [dbo].DIS_LAST
AS
WITH CH AS (
	--не являются продолжениями
	SELECT 
		LINK = LINK_UP, LAST_LINK = LINK_UP
	FROM 
		[dbo].[SDOC_DIS] A
	WHERE
		NOT EXISTS (SELECT * FROM [dbo].[SDOC_DIS] B WHERE A.LINK_UP = B.REF_DOC)

	UNION ALL

	--являются продолжениями
	SELECT LINK = С.LINK_UP, CH.LAST_LINK
	FROM
		CH
		INNER JOIN [dbo].[SDOC_DIS] B ON B.LINK_UP = CH.LINK
		INNER JOIN [dbo].[SDOC_DIS] С ON С.LINK_UP = B.REF_DOC

) SELECT LINK, LAST_LINK FROM CH 

GO

GRANT SELECT ON dbo.[DIS_LAST] TO PUBLIC

GO

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

GO
CREATE VIEW [dbo].SA_SZV_K_REPORTS
AS


SELECT ORD = 1, YB = 2000, YE = 2999, [NAME] = 'СЗВ-K (Сведения о трудовом стаже застрахованного лица)', REP_CODE = 'SZVK_PRINT# #Нет данных для этой формы'


GO


GRANT SELECT ON dbo.[SA_SZV_K_REPORTS] TO PUBLIC

GO


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

GO
CREATE TRIGGER dbo.SAL_SFIN_DELETE ON SAL_SFIN
FOR DELETE 
AS
  IF @@ROWCOUNT>0
	BEGIN
		UPDATE dbo.SAL_SFIN SET [LINK_CH_SFIN]=null WHERE EXISTS (SELECT * FROM DELETED D WHERE D.[LINK] = [LINK_CH_SFIN]) 
	END

GO

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

GO
CREATE FUNCTION dbo.SAL_SFIN_CHANGES (@DATE DATETIME = NULL)
/*для каждого источника определяем на что он в итоге поменялся к заданной дате*/
RETURNS TABLE

RETURN
WITH CH AS (
	SELECT 
		LINK, NEW_LINK = LINK 
	FROM 
		dbo.SAL_SFIN F
		INNER JOIN (SELECT DBO.SALARYCALCPERIOD() AS [DATE]) AS CP ON 1=1
	WHERE
		(LINK_CH_SFIN IS NULL OR LINK_CH_SFIN IS NOT NULL AND DATE_CHANGE > ISNULL(@DATE,CP.[DATE]) )

	UNION ALL
	--какой источник менялся на последний
	SELECT F.LINK, NEW_LINK = CH.NEW_LINK
	FROM
		CH
		INNER JOIN dbo.SAL_SFIN F ON F.LINK_CH_SFIN = CH.LINK
		INNER JOIN (SELECT DBO.SALARYCALCPERIOD() AS [DATE]) AS CP ON 1=1
	WHERE
		(F.DATE_CHANGE IS NOT NULL AND F.DATE_CHANGE <= ISNULL(@DATE,CP.[DATE]) OR F.DATE_CHANGE IS NULL)
		
) SELECT LINK, NEW_LINK FROM CH

GO


GRANT SELECT ON dbo.[SAL_SFIN_CHANGES] TO PUBLIC

GO

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

GO

CREATE       FUNCTION dbo.sa_SZVK_EmplExpirTable (
	@pers_link int = -1,
	@Date datetime = '20011231',
	@link_szvk INT ,
	@BUFF_ID VARCHAR(20) = NULL
)  


RETURNS @R TABLE (pers_link int, expir_link int, expir_code varchar(10),dop_st tinyint, years INT, months INT, days INT)
AS  
BEGIN 


	DECLARE @result int, @nyears int, @nmonths int, @ndays int, @ndate datetime, @tdate datetime, @cstr varchar(7000), @fname varchar(20)
	DECLARE @T TABLE (pers_link int, expir_link int, expir_code varchar(10) , dop_st tinyint, date_begin datetime, date_end datetime, koeff numeric(4,1), years numeric(5,2), months numeric(5,2), days numeric(5,2), lastday int)
	DECLARE @R_TEMP TABLE (pers_link int, expir_link int, expir_code varchar(10), dop_st tinyint, years numeric(5,2), months numeric(5,2), days numeric(8,2))
	DECLARE @DIS_DATE TABLE (pers_link int, date datetime)

	insert into @DIS_DATE (pers_link, date)
	SELECT link_PERS, date2 
	FROM dbo.szv_k_stazh st 
	INNER JOIN SZV_K_sved_WORK_DEP wd ON wd.link = st.link_up
	INNER JOIN SZV_K_svedenia sv ON sv.link = wd.link_up
	WHERE 
	sv.link_up = @link_szvk
	AND 
		(
			(@pers_link = -1 
			AND 
			(	@BUFF_ID IS NULL
				OR 
				@BUFF_ID IS NOT NULL AND sv.LINK_PERS IN (SELECT LINK FROM DBO.BUFFER WITH (NOLOCK) WHERE ID = @BUFF_ID)
			))
			OR
			(@pers_link > 0 AND sv.LINK_PERS = @pers_link)
		)
	and date2<@date


	SELECT @tdate = WORKDATE FROM USER_INFO

	--IF @mode=1
	INSERT @T
	SELECT o.link_pers, 
			link = case when o.dop_st = 0 THEN 1 
						END ,
			code = case WHEN o.dop_st = 0 THEN 'ST'
						END , 
			o.dop_st,
			date_begin = o.date1 , 
			date_end = case when o.date2<@Date then o.date2 else @Date end,
			o.ter_koef, 0, 0, 0, 0
			FROM (	/*СТАЖ ОБЩИЙ*/
					SELECT Sv.link_PERS, st.date1 , st.date2 , st.ter_usl , st.ter_koef, st.osob_usl, st.ud_osnov , dop_st = 0
					FROM dbo.szv_k_stazh st 
					left JOIN SZV_K_sved_WORK_DEP wd ON wd.link = st.link_up
					left JOIN SZV_K_svedenia sv ON sv.link = wd.link_up
					WHERE 
					sv.link_up = @link_szvk
					and st.date1 <= @Date
					AND 
						(
							(@pers_link = -1 
							AND 
							(	@BUFF_ID IS NULL
								OR 
								@BUFF_ID IS NOT NULL AND sv.LINK_PERS IN (SELECT LINK FROM DBO.BUFFER WITH (NOLOCK) WHERE ID = @BUFF_ID)
							))
							OR
							(@pers_link > 0 AND sv.LINK_PERS = @pers_link)
						)
					) o
	UNION ALL
	SELECT o.link_pers, 
			link = case WHEN o.dop_st = 0 AND ltrim(rtrim(o.ter_usl)) <> '' THEN 2
						WHEN o.dop_st = 0 AND ltrim(rtrim(o.osob_usl)) <> '' THEN 3 
						WHEN o.dop_st = 0 AND ltrim(rtrim(o.ud_osnov)) <> '' THEN 4
						WHEN o.dop_st = 1 AND ltrim(rtrim(o.ter_usl)) <> '' THEN 2
						WHEN o.dop_st = 1 AND ltrim(rtrim(o.osob_usl)) <> '' THEN 3 
						WHEN o.dop_st = 1 AND ltrim(rtrim(o.ud_osnov)) <> '' THEN 4
						END ,
			code = case WHEN ltrim(rtrim(o.ter_usl)) <> '' THEN 'TER_USL'
						WHEN ltrim(rtrim(o.osob_usl)) <> '' THEN 'OS_USL'
						WHEN ltrim(rtrim(o.ud_osnov)) <> '' THEN 'UD_USL'
						END , 
			o.dop_st,
			date_begin = o.date1 , 
			date_end = case when o.date2<@Date then o.date2 else @Date end,
			o.ter_koef, 0, 0, 0, 0
			FROM (	/*СТАЖ ПО ТЕРРИТОРИАЛЬНЫМ УСЛОВИЯМ ТРУДА*/
					SELECT Sv.link_PERS, st.date1 , st.date2 , st.ter_usl, st.ter_koef, osob_usl = '', ud_osnov = '', dop_st = 0
					FROM dbo.szv_k_stazh st 
					left JOIN SZV_K_sved_WORK_DEP wd ON wd.link = st.link_up
					left JOIN SZV_K_svedenia sv ON sv.link = wd.link_up
					WHERE
					isnull(st.ter_usl, '') <> '' 
					and sv.link_up = @link_szvk
					and st.date1 <= @Date
					AND 
						(
							(@pers_link = -1 
							AND 
							(	@BUFF_ID IS NULL
								OR 
								@BUFF_ID IS NOT NULL AND sv.LINK_PERS IN (SELECT LINK FROM DBO.BUFFER WITH (NOLOCK) WHERE ID = @BUFF_ID)
							))
							OR
							(@pers_link > 0 AND sv.LINK_PERS = @pers_link)
						)	
				UNION ALL 
					/*СТАЖ ПО ОСОБЫМ УСЛОВИЯМ ТРУДА*/
					SELECT Sv.link_PERS, st.date1 , st.date2 , ter_usl = '', st.ter_koef, st.osob_usl, ud_osnov = '', dop_st = 0
					FROM dbo.szv_k_stazh st 
					left JOIN SZV_K_sved_WORK_DEP wd ON wd.link = st.link_up
					left JOIN SZV_K_svedenia sv ON sv.link = wd.link_up
					WHERE
					isnull(st.osob_usl, '') <> '' 
					and sv.link_up = @link_szvk
					and st.date1 <= @Date
					AND 
						(
							(@pers_link = -1 
							AND 
							(	@BUFF_ID IS NULL
								OR 
								@BUFF_ID IS NOT NULL AND sv.LINK_PERS IN (SELECT LINK FROM DBO.BUFFER WITH (NOLOCK) WHERE ID = @BUFF_ID)
							))
							OR
							(@pers_link > 0 AND sv.LINK_PERS = @pers_link)
						)					
				UNION ALL 
					/*СТАЖ ПО ВЫСЛУГЕ ЛЕТ*/
					SELECT Sv.link_PERS, st.date1 , st.date2 , ter_usl = '', st.ter_koef, osob_usl = '', ST.ud_osnov , dop_st = 0
					FROM dbo.szv_k_stazh st 
					left JOIN SZV_K_sved_WORK_DEP wd ON wd.link = st.link_up
					left JOIN SZV_K_svedenia sv ON sv.link = wd.link_up
					WHERE
					isnull(ST.ud_osnov, '') <> '' 
					and sv.link_up = @link_szvk
					and st.date1 <= @Date
					AND 
						(
							(@pers_link = -1 
							AND 
							(	@BUFF_ID IS NULL
								OR 
								@BUFF_ID IS NOT NULL AND sv.LINK_PERS IN (SELECT LINK FROM DBO.BUFFER WITH (NOLOCK) WHERE ID = @BUFF_ID)
							))
							OR
							(@pers_link > 0 AND sv.LINK_PERS = @pers_link)
						)
				/*ДОП ЗАПИСИ ПО СТАЖУ (ЕСЛИ ЕСТЬ ОСОБЫЕ УСЛОВИЯ ТРУДА В ОСНОВНЫХ ЗАПИСЯХ)*/		
				UNION all
						/*ДОП СТАЖ ПО ТЕРРИТОРИАЛЬНЫМ УСЛОВИЯМ*/
					SELECT Sv.link_PERS, st.date1 , st.date2 , std.ter_usl, std.ter_koef, osob_usl = '', ud_osnov = '', dop_st = 1
					FROM dbo.szv_k_stazh_dop std
					inner join dbo.szv_k_stazh st ON st.link = std.link_up
					left JOIN SZV_K_sved_WORK_DEP wd ON wd.link = st.link_up
					left JOIN SZV_K_svedenia sv ON sv.link = wd.link_up
					WHERE
					ISNULL(std.ter_usl,'') <> ''
					AND sv.link_up = @link_szvk
					and std.date1 <= @Date
					AND 
						(
							(@pers_link = -1 
							AND 
							(	@BUFF_ID IS NULL
								OR 
								@BUFF_ID IS NOT NULL AND sv.LINK_PERS IN (SELECT LINK FROM DBO.BUFFER WITH (NOLOCK) WHERE ID = @BUFF_ID)
							))
							OR
							(@pers_link > 0 AND sv.LINK_PERS = @pers_link)
						)
				UNION all
						/*ДОП СТАЖ ПО ОСОБЫМ УСЛОВИЯМ*/
					SELECT Sv.link_PERS, st.date1 , st.date2 , ter_usl  = '', std.ter_koef, std.osob_usl, ud_osnov = '', dop_st = 1
					FROM dbo.szv_k_stazh_dop std
					inner join dbo.szv_k_stazh st ON st.link = std.link_up
					left JOIN SZV_K_sved_WORK_DEP wd ON wd.link = st.link_up
					left JOIN SZV_K_svedenia sv ON sv.link = wd.link_up
					WHERE
					ISNULL(std.osob_usl,'') <> ''
					AND sv.link_up = @link_szvk
					and std.date1 <= @Date
					AND 
						(
							(@pers_link = -1 
							AND 
							(	@BUFF_ID IS NULL
								OR 
								@BUFF_ID IS NOT NULL AND sv.LINK_PERS IN (SELECT LINK FROM DBO.BUFFER WITH (NOLOCK) WHERE ID = @BUFF_ID)
							))
							OR
							(@pers_link > 0 AND sv.LINK_PERS = @pers_link)
						)			
				UNION all
						/*ДОП СТАЖ ПО ВЫСЛУГЕ ЛЕТ*/
					SELECT Sv.link_PERS, st.date1 , st.date2 , ter_usl = '', std.ter_koef, osob_usl = '', std.ud_osnov , dop_st = 1
					FROM dbo.szv_k_stazh_dop std
					inner join dbo.szv_k_stazh st ON st.link = std.link_up
					left JOIN SZV_K_sved_WORK_DEP wd ON wd.link = st.link_up
					left JOIN SZV_K_svedenia sv ON sv.link = wd.link_up
					WHERE
					ISNULL(std.ud_osnov,'') <> ''
					AND sv.link_up = @link_szvk
					and std.date1 <= @Date
					AND 
						(
							(@pers_link = -1 
							AND 
							(	@BUFF_ID IS NULL
								OR 
								@BUFF_ID IS NOT NULL AND sv.LINK_PERS IN (SELECT LINK FROM DBO.BUFFER WITH (NOLOCK) WHERE ID = @BUFF_ID)
							))
							OR
							(@pers_link > 0 AND sv.LINK_PERS = @pers_link)
						)				
			) o

	UPDATE @T SET 
		years = year(date_end+1) - year(date_begin),
		months = month(date_end+1) - month(date_begin),
		days = day(date_end+1) - day(date_begin),
		lastday = 30/*datepart(day, dbo.DateBeginOfMonth(date_end+1) - 1)*/


	UPDATE @T SET years = convert(int, years), months = months + (years-convert(int, years)) * 12
	UPDATE @T SET months = convert(int, months), days = days + (months-convert(int, months)) * lastday
	UPDATE @T SET months = months - 1, days = days + lastday WHERE days<0
	UPDATE @T SET years = years - 1, months = months + 12 WHERE months<0

	INSERT @R_TEMP
	SELECT pers_link, expir_link, expir_code,DOP_ST, isnull(sum(years/**koeff*/), 0), isnull(sum(months/**koeff*/), 0), isnull(sum(days/**koeff*/), 0)
	FROM @T GROUP BY pers_link, expir_link, expir_code,DOP_ST

	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 INTO @R
	SELECT * FROM @R_TEMP



	RETURN			
				
END




GO


GRANT SELECT ON dbo.[sa_SZVK_EmplExpirTable] TO PUBLIC

GO


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

GO

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

CREATE   FUNCTION dbo.KU_EMPL_PLACING_FN(@dDATE datetime = null)
RETURNS @RESULT TABLE
		( [LINK] INT,
		[PERS_LINK]	INT,
		[DEP_LINK] INT,
		[DEP_NAME] VARCHAR(254),
		[TAB] VARCHAR(10),
		[FM] VARCHAR(100),
		[IM] VARCHAR(100),
		[OT] VARCHAR(100),
		[FIO] VARCHAR(100),
		[NAME_EMPL] VARCHAR(100),
		[SUBDIV_HEAD] INT,
		[SUBDIV_LINK] INT,
		[SUBDIV_CODE] VARCHAR(5),
		[SUBDIV_NAME] VARCHAR(254),
		[POST_LINK] INT,
		[POST_CODE] VARCHAR(10),
		[POST_NAME] VARCHAR(254),
		[STAFF_HEAD] INT,
		[STAFF_LINK] INT,
		[NUM_STAKE] NUMERIC(3,2),
		[STATUS] INT,
		[STATUS_NAME] VARCHAR(60),
		[NOTWORK] tinyint,
		[DATE_BEGIN] DATETIME,
		[DATE_MOV] DATETIME,
		[OKLAD] NUMERIC(10,2),
		[GRAPH_LINK] INT,
		[GRAPH_NAME] VARCHAR(60),
		[DATE_SACK]	DATETIME,
		[ITEM_MOVE_LINK] INT,
		[VIS] BIT,
		[LINK_KBK] INT,
		[CODE_KBK] VARCHAR(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  dbo.EMPL_CHIN ch1 inner join dbo.DICTIONARY_CHIN dh ON  ch1.chin_link = dh.link
WHERE  ch1.[DATE] = 
				(SELECT TOP 1 C.DATE 
				 FROM dbo.EMPL_CHIN C 
				 WHERE C.EMPL_LINK = ch1.EMPL_LINK AND C.DATE <= @dDATE 
				 ORDER BY DATE DESC)	

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

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

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

-- Заполнение результирующей таблицы --------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------
INSERT INTO @RESULT([LINK],
		[PERS_LINK],		[DEP_LINK],		[DEP_NAME],
		[TAB],		[FM],	[IM],	[OT],	[FIO],
		[NAME_EMPL],		[SUBDIV_HEAD],	[SUBDIV_LINK],
		[SUBDIV_CODE],		[SUBDIV_NAME],	[POST_LINK],
		[POST_CODE],		[POST_NAME],	[STAFF_HEAD],
		[STAFF_LINK],		[NUM_STAKE],	[STATUS],
		[STATUS_NAME],		[NOTWORK],		[DATE_BEGIN], [DATE_MOV],
		[OKLAD],			[GRAPH_LINK],	[GRAPH_NAME],
		[DATE_SACK],		[ITEM_MOVE_LINK],		[VIS],
		[LINK_KBK], 		[CODE_KBK], 	[NAME_KBK],
		[RAZR],				[SYST_PAY],		[POST_GROUP], [KATEG],
		[CHIN],				[CHIN_DATE],	[EMAIL],
		[PHONE_WORK],		[PHONE_MOB],	[INN],
		[SNILS],			[SACK],			[SACK_PER])
SELECT	distinct
	T.*,
	CASE
		WHEN datediff(day,T.DATE_SACK, @dDATE) > 0  THEN 1
		ELSE 0
	END AS SACK,
	CASE
		WHEN YEAR(T.DATE_SACK) = YEAR(@dDATE)
		     AND MONTH(T.DATE_SACK) = MONTH(@dDATE) THEN 1
		ELSE 0
	END AS SACK_PER
FROM	(
	SELECT 
		[LINK] 			= 	E.LINK, 
		[PERS_LINK]		= 	P.LINK, 
		[DEP_LINK]		= 	E.DEP_LINK,
		[DEP_NAME]		=	DEP.NAME,
		[TAB]			= 	E.TAB,
		[FM]			= 	P.FM,
		[IM]			= 	P.IM, 
		[OT]			=	P.OT,
		[FIO]			=	LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(FM)) + ' ' + LTRIM(RTRIM(IM)) + ' ' + LTRIM(RTRIM(OT)),'Не заполнено'))),100),
		[NAME_EMPL]		= 	LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(FM)) + ' ' + LEFT(LTRIM(RTRIM(IM)),1) + '.' + LEFT(LTRIM(RTRIM(OT)),1) + '.', 'Не заполнено'))),30),
		[SUBDIV_HEAD]	=	DS.link_up,
		[SUBDIV_LINK]	=	DS.LINK,
		[SUBDIV_CODE]	=	DS.CODE,
		[SUBDIV_NAME]	=	DS.NAME,
		[POST_LINK]		=	DP.LINK,
		[POST_CODE]		=	DP.CODE,
		[POST_NAME]		=	DP.NAME,
		[STAFF_HEAD]	=	PE.STAFF_HEAD,
		[STAFF_LINK]	= 	PE.STAFF_LINK,
		[NUM_STAKE]		=	PE.NUM_STAKE,
		[STATUS]		=	PE.[STATUS],
		[STATUS_NAME]	=	CASE WHEN PE.[STATUS] = 1 THEN 'Основной' WHEN PE.[STATUS] = 2 THEN 'Совместитель' WHEN PE.[STATUS] = 3 THEN 'Внешний совместитель' END,
		[NOTWORK]		=	E.NOTWORK,
		[DATE_BEGIN]	=	IM.DATE_BEGIN,
		[DATE_MOV]		=	PE.DATE_BEG,
		[OKLAD]			=	PE.oklad,
		[GRAPH_LINK]	= 	G.LINK,
		[GRAPH_NAME]	=	G.NAME,
		[DATE_SACK]		=	IDF.DIS_DATE,
		[ITEM_MOVE_LINK] =	PE.MOVE_LINK,
		[VIS]			=	CONVERT(bit, 0),
		LINK_KBK		=	KBK.LINK,
		CODE_KBK		=	KBK.CODE,
		NAME_KBK		=	KBK.NAME,
		RAZR			=	COALESCE(IM.ETS_RAZR,0),
		[SYST_PAY]		=	E.SYST_PAY,		
		[POST_GROUP]	=	GR.NAME,
		[KATEG]			=	KAT.NAME,
		[CHIN]			=	CE.CHIN_NAME,
		[CHIN_DATE]		=	CE.CHIN_DATE,		
		[EMAIL]			=	PME.[EMAIL] ,
		[PHONE_WORK]	=	PME.[PHONE_WORK],
		[PHONE_MOB]		=	PME.[PHONE_MOB],
		[INN]			=	P.INN,
		[SNILS]			=	P.INSUR_NUM
	FROM			dbo.EMPL		E
		INNER JOIN	dbo.PERSON 			P	 ON e.pers_link=p.link
		LEFT JOIN	dbo.GRAPH			G	 ON e.graph_link=g.link
		LEFT JOIN	@POST_EMPL		PE	 ON E.LINK = PE.EMPL_LINK
		LEFT JOIN	dbo.SAL_SFIN		KBK	 ON KBK.LINK = PE.LINK_KBK		
		LEFT JOIN	dbo.SUBDIV			DS	 ON PE.subdiv_link = DS.LINK
		LEFT JOIN	dbo.POST			DP	 ON PE.post_link = DP.LINK
		LEFT JOIN	dbo.ITEM_MOVE		IM	 ON IM.ACTIVE = 1 AND IM.NEW_FACE = 1 AND IM.EMPL_LINK = E.LINK
		LEFT JOIN	dbo.DEPARTMENTS		DEP	 ON E.DEP_LINK = DEP.LINK
		LEFT JOIN	dbo.ITEM_MOVE	SE	 ON E.LINK = SE.EMPL_LINK AND @dDATE between SE.date_begin and SE.date_end and SE.active=1
		LEFT JOIN	@ITEM_DIS_FACE	IDF	 ON E.LINK = IDF.EMPL_LINK
		LEFT JOIN	@CHIN_EMPL		CE	 ON E.LINK = CE.EMPL_LINK
		LEFT JOIN   @PHONE_MAIL_EMPL PME ON E.LINK = PME.EMPL_LINK
		LEFT JOIN	dbo.STAFF ST ON ST.LINK = PE.STAFF_LINK
		LEFT JOIN	dbo.GR_GOS GR ON GR.LINK = ST.GR_GOS_LINK
		LEFT JOIN   DBO.KAT_GOS KAT ON KAT.LINK = ST.KAT_GOS_LINK
		--LEFT JOIN	dbo.KATEG KAT ON KAT.LINK = ST.KAT_LINK

	) T

RETURN
END

GO


GRANT SELECT ON dbo.[KU_EMPL_PLACING_FN] TO PUBLIC

GO

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

GO

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

GO


GRANT SELECT ON dbo.[SALARY_SRC_FIN] TO PUBLIC

GO

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

GO

CREATE VIEW [dbo].[DIS]  AS 
SELECT 
	S.LINK,
	S.NUMBER,
	S.DATE,
	S.COMMENTARY,
	[FLAG_JC] = COALESCE(R.ref_doc,0)/COALESCE(R.ref_doc,1),
	S.LINK_DEP,
	dep.NAME as name_dep,
	[TAB_NUMER] = E.TAB,
	[NAME_EMPL] =  dbo.sd_GetEmplName(E.LINK),
	[REF_EMPL]  = SD.LINK_EMPL,
	[DAYS] 	   = SD.days,
	[HOURS]	   = SD.HOURS,
	SD.DATE1,
	SD.DATE2,
	[NEPR_YEAR] = SD.NEPR_YEARS,
	[NEPR_MONTH] = SD.NEPR_MONTH,
	[NEPR_DAY] = SD.NEPR_DAY,
	[CODE_TYP_ARHE] = N.CODE,
	[NAME_TYP_ARHE] = N.NAME,
	[REF_TYP_ARHE] 	= N.LINK,
	[NUM_DOC] 		= S2.NUMBER,
	[REF_DOC] 		= SD.REF_DOC,
	N.DEKRET,
	LINK_PAYS = COALESCE(LINK_PAYS,0),
	CODE_PAYS = COALESCE(P.CODE,''),
	NAME_PAYS = COALESCE(P.[NAME],''),
	KIDS_FLAG = COALESCE(N.KIDS,0),
	REF_PERS_KID = SD.REF_PERS_KID,
	[PERS_KID] = LEFT(ISNULL(FIO,''),150),
	FAMILY_NAME = LEFT(ISNULL(FAMILY_NAME,''),20),
	BIRTHDATE = ISNULL(CONVERT(VARCHAR(10),BIRTHDATE,104),''),
	E.PERS_LINK,
	N.INSTRUCT,
	SD.MDEP_NAME,
	SD.MDEP_ADDR,
	LAST_DIS = (CASE WHEN L.LINK IS NULL THEN 0 ELSE 1 END)
FROM 
	dbo.SDOC S 
	INNER JOIN dbo.SDOC_DIS SD ON  S.LINK = SD.LINK_UP
	INNER JOIN dbo.NETRUD N ON SD.TYPE = N.LINK
	INNER JOIN dbo.EMPL E  ON (SD.LINK_EMPL = E.LINK) 
	inner JOIN dbo.DEPARTMENTS dep on dep.link = s.LINK_DEP
	LEFT JOIN (SELECT DISTINCT DL.LINK FROM dbo.DIS_LAST DL WHERE DL.LINK = DL.LAST_LINK) L ON L.LINK = SD.LINK_UP
	LEFT JOIN dbo.SDOC S2 ON SD.REF_DOC = S2.LINK
	LEFT JOIN dbo.PAYS P ON P.LINK = N.LINK_PAYS
	LEFT JOIN dbo.KU_PERS_FAMILY F ON F.LINK = SD.REF_PERS_KID
	LEFT JOIN ( 
			select distinct sd.ref_doc  from dbo.SDOC S INNER JOIN dbo.sdoc_adis SD ON S.LINK = SD.LINK_UP
		) R ON R.ref_doc = s.link


GO


GRANT SELECT ON dbo.[DIS] TO PUBLIC

GO


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

GO

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

CREATE  FUNCTION dbo.sa_SZVK_GetEmplExpir (
	@pers_link int,
	@link_szvk INT,
	@TimeUnit varchar(10) = 'YEAR',
	@expir_code varchar(10) = null,
	@date datetime = '20011231'
	
)  
RETURNS int
AS  
BEGIN 
	DECLARE @years int, @months int, @days int

	SELECT @years = years, @months = months, @days = days
	FROM dbo.sa_SZVK_EmplExpirTable (@pers_link,@Date,@link_szvk,DEFAULT)
	WHERE expir_code=RTRIM(ltrim(@expir_code))

	RETURN case LTRIM(RTRIM(@TimeUnit)) when 'YEAR' then @years when 'MONTH' then @months when 'DAY' then @days else null end
END


GO


GRANT EXECUTE ON dbo.[sa_SZVK_GetEmplExpir] TO PUBLIC

GO



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

GO
CREATE VIEW [dbo].SA_SZV_K_SVEDENIA
as

SELECT 
	link = S.link_up,
	link1 = S.link,
	LINK_FACE = S.link_pers, 
	S.pachka,
	S.orders,
	P.FM, P.IM, P.OT, PF_NUM = P.INSUR_NUM, P.BIRTHDATE,
	FIO = LTRIM(RTRIM(P.FM)) + ' ' + LEFT(LTRIM(RTRIM(P.IM)),1) + '.' + LEFT(LTRIM(RTRIM(P.OT)),1) + '.',
	FIO2 = LTRIM(RTRIM(P.FM)) + ' ' + LTRIM(RTRIM(P.IM)) + ' ' + LTRIM(RTRIM(P.OT)),
	ADDRESS = LEFT(ISNULL(dbo.GetAddressByKladr(P.ADR_REAL_LINK), ''), 254) + 
	CASE WHEN LEN(ISNULL(P.HOUSE_REAL, '')) = 0 THEN '' ELSE ', д. ' + LTRIM(RTRIM(P.HOUSE_REAL)) END 
	+ CASE WHEN LEN(ISNULL(P.CORP_REAL, '')) = 0 THEN '' ELSE ', корп. ' + LTRIM(RTRIM(P.CORP_REAL)) END 
	+ CASE WHEN LEN(ISNULL(P.FLAT_REAL, '')) = 0 THEN '' ELSE ', кв. ' + LTRIM(RTRIM(P.FLAT_REAL)) END ,
	ADDRESS2 = dbo.GET_ADDRESS9PARTS(S.link_pers, 0),
	dper_vn_m,
	dper_vn_d,
	dper_oz_m,
	dper_oz_d,
	--Территориальные условия
	ter_usl = S.terr_usl,
	n_ter_usl = COALESCE(SPR1.[name],''), 
	ter_koef = S.terr_koef,
	f_ter_usl = COALESCE(S.[terr_usl],'') 
			+ (case when COALESCE(S.[terr_usl],'')  <> '' and coalesce(s.terr_koef,0) <> 0 then ',' + convert(varchar(20),coalesce(s.terr_koef,0)) else '' end),
	s.all_stazh_y,
	s.all_stazh_m,
	s.all_stazh_d
	
	
FROM 
	dbo.SZV_K_PACHKA D
	INNER JOIN dbo.SZV_K_SVEDENIA S ON S.LINK_UP = D.LINK
	INNER JOIN PERSON P on P.LINK = S.link_pers
	left join dbo.szv4_spr spr1 on spr1.spr_code = 'TERR_USL' and spr1.code = S.terr_usl



GO


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

CREATE  FUNCTION dbo.BK_GetKOLinkByAO (@intLINK_AO INT)  
RETURNS INT
AS  
BEGIN 
	DECLARE @intLINK_KO	INT

	SELECT TOP 1 @intLINK_KO = LINK
	FROM dbo.XK_GetTable_Doc_FOREIGN (@intLINK_AO) F
	WHERE REF_CODE IN ('BV_DOC_AO_KO_LINK_PKO', 'BV_DOC_AO_KO_LINK_RKO')

	RETURN @intLINK_KO
END


GO


GRANT EXECUTE ON dbo.[BK_GetKOLinkByAO] 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

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

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

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

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

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

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

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

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

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

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

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

RETURN 

END




GO


GRANT SELECT ON dbo.[sa_dict_wh_pays_empl] TO PUBLIC

GO


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


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

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

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

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


GRANT SELECT ON dbo.[BV_DOC_AVANSE_REP] TO PUBLIC

GO

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

/*
© Кейсистемс (Keysystems), 2005
*/
--- Функция вычисляет объекты для налога на имущества ---
CREATE         FUNCTION dbo.CalcNalogBalanceOS (@dDate DATETIME = NULL, @intDepLink INT = NULL)
-- Если @intDepLink = NULL то расчет без учета DEP_LINK, т.е. для всех организаций
RETURNS @varKSOUT_TABLE TABLE
	(	DEP_LINK	INT,
		[ACCOUNT] [INT],
		[GRP_CODE] [CHAR] (8) NOT NULL,
		[INV]	[INT] NOT NULL,
		[OST_SUM] [NUMERIC] (20,2) NULL,
		[BALANS] [NUMERIC] (20,2) NULL,
		[AMORT] [NUMERIC] (20,2) NULL,
		[NO_NALOG] BIT NOT NULL,
		[DATE_BEGIN] DATETIME NULL
	)
AS
BEGIN
	DECLARE
		@AMORT_FULL NUMERIC (28,2),
		@DATE_BEGIN	DATETIME,
		@intNOT_USE_NASTR	INT,
		@intACCOUNT	INT,
		@dDATE_REST	DATETIME

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

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

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

	---	Изменения в НК в 2013 ---
	DECLARE @TAB_INPUT_INV TABLE
		(INV	INT,
		DEP_LINK	INT
		)

	IF YEAR (@dDate) >= 2013
		INSERT INTO @TAB_INPUT_INV
		SELECT
			T1.INV,
			T1.DEP_LINK
		FROM dbo.BK_GetTableOperINV
			(DEFAULT,
			'20130101',
			@dDATE,
			2,
			@intDepLink) T1
		INNER JOIN dbo.INVENTORY INV ON (INV.LINK = T1.INV)	
		INNER JOIN dbo.NOMENCLATURE NOMEN ON (NOMEN.LINK = INV.NOMENCLATURE)	
		INNER JOIN dbo.GROUP_INV GRA ON (GRA.LINK = NOMEN.GROUP_INV
			AND GRA.CODE LIKE '101[2-3]%')	
		GROUP BY
			T1.INV,
			T1.DEP_LINK

	SET @dDATE_REST	= @dDate

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

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

	INSERT INTO @T_BALANS 
		(
		DEP_LINK,
		ACCOUNT,
		INV,
		BALANS,
		QTY
		)
	SELECT
		T1.DEP_LINK,
		T1.ACCOUNT,
		ISNULL (T1.INV, 0),
		SUM (T1.D_SUMMA),
		SUM (T1.D_QUANTITY)
	FROM dbo.ARestTableByDate (@dDATE_REST, @intACCOUNT) T1
	WHERE 
		NOT EXISTS (SELECT * FROM @TAB_INPUT_INV TTT WHERE TTT.INV = T1.INV)
	GROUP BY
		T1.DEP_LINK,
		T1.ACCOUNT,
		ISNULL (T1.INV, 0)

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

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

	INSERT INTO @T_AMORT 
		(
		DEP_LINK,
		ACCOUNT,
		INV,
		SUMMA
		)
	SELECT
		T1.DEP_LINK,
		T1.ACCOUNT,
		ISNULL (T1.INV, 0),
		SUM (T1.K_SUMMA)
	FROM dbo.ARestTableByDate (@dDATE_REST, @intACCOUNT) T1
	WHERE 
		NOT EXISTS (SELECT * FROM @TAB_INPUT_INV TTT WHERE TTT.INV = T1.INV)
	GROUP BY
		T1.DEP_LINK,
		T1.ACCOUNT,
		ISNULL (T1.INV, 0)

	--- !!!Результат!!! ---
	INSERT @varKSOUT_TABLE
		(DEP_LINK,
		ACCOUNT,
		INV,
		BALANS,
		GRP_CODE,
		NO_NALOG,
		DATE_BEGIN,
		AMORT,
		OST_SUM
		)
	SELECT
		T1.DEP_LINK,
		T1.ACCOUNT,
		ISNULL (T1.INV, 0),
		T1.BALANS,
		GRI.CODE,
		ISNULL(ASS.NO_TAX, 0),
		ASS.DATE_BEGIN,
		ISNULL (T2.SUMMA, 0),
		T1.BALANS - ISNULL (T2.SUMMA, 0)
	FROM @T_BALANS T1
	INNER JOIN dbo.INVENTORY INV ON (INV.LINK = T1.INV)	
	INNER JOIN dbo.NOMENCLATURE NOMEN ON (NOMEN.LINK = INV.NOMENCLATURE)	
	INNER JOIN dbo.GROUP_INV GRI ON (GRI.LINK = NOMEN.GROUP_INV)	
	LEFT JOIN dbo.ASSETS ASS ON (ASS.LINK_UP = INV.LINK)
	LEFT MERGE JOIN @T_AMORT T2 ON (T2.INV = T1.INV)
	WHERE
		(@intNOT_USE_NASTR = 0
			AND ASS.DATE_BEGIN <= @dDate
			AND (T1.BALANS <> 0
				AND (T1.QTY = 0 AND T1.BALANS > @AMORT_FULL
					OR T1.QTY <> 0
						AND ABS (T1.BALANS) > ABS (T1.QTY) * @AMORT_FULL
					))
			OR @intNOT_USE_NASTR = 1)




	RETURN
END
GO


GRANT SELECT ON dbo.[CalcNalogBalanceOS] TO PUBLIC
GO



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

GO
CREATE FUNCTION dbo.sa_ssch_empls_n(
	@BDate datetime,
	@EDate	datetime,
	@DEP_LINK int = NULL,
	@sex tinyint = 0, -- 0 все, 1 - только мужчины, 2 - только женщины
	@status tinyint = 1, --0 - основные и внешние совместители, 1- только основные, 3 - только внешние совместители
	@invalid tinyint = 0, -- 0 все, 1 только инвалиды, 2 - только на работе с вредными факторами
	@BUFFER_SUBDIV VARCHAR(20) = NULL --Код буффера, для отбора подразделений	
	)
/*определение среднесписочной численности*/
RETURNS numeric(18,2)
AS  
BEGIN 
	DECLARE @Res numeric(18,2) 

	SET @DEP_LINK = COALESCE(@DEP_LINK,(SELECT TOP 1 DEP_LINK FROM dbo.USER_DEP))
	
	DECLARE @INV TABLE (DATE DATETIME, PERS_LINK INT)

	IF @invalid = 0 
		Set @Res = --Все
		Coalesce(Round((
			SELECT (SUM(SSCH)/COUNT(SSCH))
			FROM
				(
					Select SSCH = sum(cnt_empl) / DAY(dbo.DATEENDOFMONTH(dbo.ConvertDMY2Date(1,M,Y)))
					from
					(	
						Select  cnt_empl = sum( CONVERT(NUMERIC(18,2),sssch) ), Y = YEAR(DATE_N), M = MONTH(DATE_N)
						FROM 
							dbo.empl e
							inner join dbo.person p on p.link = e.pers_link					
							inner join (select * from dbo.ku_EmplsInPeriod0(@BDate,@EDate, @DEP_LINK, 0, 0) group by date, empl_link,status, sch,ssch,comment) s on  e.link = s.empl_link                                  
							INNER JOIN dbo.SA_EMPLS_INFO_PERIOD(@BDate,@EDate, DEFAULT, @DEP_LINK) EI ON S.EMPL_LINK = EI.EMPL_LINK AND S.[DATE] BETWEEN EI.PERIOD_BEG AND EI.PERIOD_END
							inner   JOIN (
										select f.link_empl, f.date_N, sSSCH = (case when sum(f.FACT_NAGR) >= 1 THEN 1 
																					when sum(f.FACT_NAGR) < 1 AND sum(f.FACT_NAGR) <> 0 THEN 0.5 ELSE 0 END )  
										from 
											(SELECT SW.link_empl , SW.fio, SW.link_les, SW.link_paral,SW.NORM_WEEK_HOURS , SW.fact_week_hours,DATE_N = D.[DATE], SW.date_begin , SW.date_end, FACT_NAGR = convert(numeric(15,2),isnull((SW.fact_week_hours/SW.NORM_WEEK_HOURS),0))  
											from  STO_W_HOURS_TABLE SW
											inner join dbo.days_ex(@BDate,@EDate) D on D.[DATE] between SW.DATE_BEGIN AND ISNULL(SW.DATE_END,D.[DATE])
											WHERE  @EDate between SW.date_begin and SW.date_end  
												or @BDate between SW.date_begin and SW.date_end ) f 
										GROUP BY f.link_empl, f.date_n
										
										
										) FN on fn.link_empl = e.link and s.date = fn.date_N
							where
							(@sex = 0 or (@sex <> 0 and sex = @sex))
							and
							((@status = 0 and S.[status] <> 2) or (@status in (1,3) and S.[status] = @status))
							and
							e.dep_link = @DEP_LINK
							AND
							(
								@BUFFER_SUBDIV IS NULL
								OR 
								@BUFFER_SUBDIV IS NOT NULL AND EI.SUBDIV_LINK IN (SELECT B.LINK FROM dbo.BUFFER B WHERE B.ID = @BUFFER_SUBDIV)
							)
						group by
							 FN.date_N
					) as A
					GROUP BY Y, M
				) AS B
		),2),0)

	IF @invalid = 1 
		Set @Res = --считаем только инвалидов 
		Coalesce(Round((
			SELECT (SUM(SSCH)/COUNT(SSCH))
			FROM
				(
					Select SSCH = sum(cnt_empl) / DAY(dbo.DATEENDOFMONTH(dbo.ConvertDMY2Date(1,M,Y)))
					from
					(	
						Select cnt_empl = sum( CONVERT(NUMERIC(18,2),sssch) ), Y = YEAR(DATE_N), M = MONTH(DATE_N)
						FROM 
							dbo.pers_invalid I
							inner join dbo.person p on I.pers_link = P.link
							inner join dbo.empl e on p.link = e.pers_link
							inner join dbo.ku_EmplsInPeriod0(@BDate,@EDate, @DEP_LINK, 0, 0) s on e.link = s.empl_link and s.[date] between I.DATE_BEGIN AND ISNULL(I.DATE_END,@EDate)
							INNER JOIN dbo.SA_EMPLS_INFO_PERIOD(@BDate,@EDate, DEFAULT, @DEP_LINK) EI ON S.EMPL_LINK = EI.EMPL_LINK AND S.DATE BETWEEN EI.PERIOD_BEG AND EI.PERIOD_END
							inner JOIN (
										select f.link_empl, f.date_N, sSSCH = (case when sum(f.FACT_NAGR) >= 1 THEN 1 
																					when sum(f.FACT_NAGR) < 1 AND sum(f.FACT_NAGR) <> 0 THEN 0.5 ELSE 0 END )  
										from 
											(SELECT SW.link_empl , SW.fio, SW.link_les, SW.link_paral,SW.NORM_WEEK_HOURS , SW.fact_week_hours,DATE_N = D.[DATE], SW.date_begin , SW.date_end, FACT_NAGR = convert(numeric(15,2),isnull((SW.fact_week_hours/SW.NORM_WEEK_HOURS),0))  
											from  STO_W_HOURS_TABLE SW
											inner join dbo.days_ex(@BDate,@EDate) D on D.[DATE] between SW.DATE_BEGIN AND ISNULL(SW.DATE_END,D.[DATE])
											WHERE  @EDate between SW.date_begin and SW.date_end  
												or @BDate between SW.date_begin and SW.date_end ) f 
										GROUP BY f.link_empl, f.date_n
										
										
										) FN on fn.link_empl = e.link and s.date = fn.date_N
						where
							(@sex = 0 or (@sex <> 0 and sex = @sex))
							and
							((@status = 0 and S.[status] <> 2) or (@status in (1,3) and S.[status] = @status))
							and
							e.dep_link = @DEP_LINK
							and
							I.DATE_BEGIN <= @EDate
							and isnull(I.DATE_END, @EDate) >= @BDate
							AND
							(
								@BUFFER_SUBDIV IS NULL
								OR 
								@BUFFER_SUBDIV IS NOT NULL AND EI.SUBDIV_LINK IN (SELECT B.LINK FROM dbo.BUFFER B WHERE B.ID = @BUFFER_SUBDIV)
							)					
						group by
							FN.date_N
					) as A
					GROUP BY Y, M
				) AS B			
		),2),0)

	IF @invalid = 2 -- сотрудники с вредными факторами
	BEGIN
		DECLARE @FAKTOR TABLE (LINK INT)

		INSERT INTO @FAKTOR (LINK)
		SELECT DISTINCT EMPL_LINK
		FROM 
			dbo.STAFF_HEAD H
			INNER JOIN dbo.STAFF S ON S.LINK_UP = H.LINK
			INNER JOIN dbo.sa_item_move im ON H.LINK = IM.STAFF_LINK
		where
			H.DEP_LINK = @DEP_LINK
			AND
			(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)
			AND
			im.DATE_BEGIN <= @EDate and im.DATE_END3 >= @BDate
			and 
			S.DATE_BEGIN <= @EDate and S.DATE_END >= @BDate
	
		Set @Res = --только на работе с вредными факторами
		Coalesce(Round((
			SELECT (SUM(SSCH)/COUNT(SSCH))
			FROM
				(
					Select SSCH = sum(cnt_empl) / DAY(dbo.DATEENDOFMONTH(dbo.ConvertDMY2Date(1,M,Y)))
					from
					(	
						Select cnt_empl = sum( CONVERT(NUMERIC(18,2),sssch) ), Y = YEAR(DATE_N), M = MONTH(DATE_N)
						FROM 
							@FAKTOR F 	
							inner join dbo.empl e on F.LINK = e.LINK
							INNER JOIN dbo.PERSON P ON P.LINK = E.PERS_LINK
							inner join dbo.ku_EmplsInPeriod0(@BDate,@EDate, @DEP_LINK, 0, 0) s on e.link = s.empl_link
							INNER JOIN dbo.SA_EMPLS_INFO_PERIOD(@BDate,@EDate, DEFAULT, @DEP_LINK) EI ON S.EMPL_LINK = EI.EMPL_LINK AND S.DATE BETWEEN EI.PERIOD_BEG AND EI.PERIOD_END
							inner JOIN (
										select f.link_empl, f.date_N, sSSCH = (case when sum(f.FACT_NAGR) >= 1 THEN 1 
																					when sum(f.FACT_NAGR) < 1 AND sum(f.FACT_NAGR) <> 0 THEN 0.5 ELSE 0 END )  
										from 
											(SELECT SW.link_empl , SW.fio, SW.link_les, SW.link_paral,SW.NORM_WEEK_HOURS , SW.fact_week_hours,DATE_N = D.[DATE], SW.date_begin , SW.date_end, FACT_NAGR = convert(numeric(15,2),isnull((SW.fact_week_hours/SW.NORM_WEEK_HOURS),0))  
											from  STO_W_HOURS_TABLE SW
											inner join dbo.days_ex(@BDate,@EDate) D on D.[DATE] between SW.DATE_BEGIN AND ISNULL(SW.DATE_END,D.[DATE])
											WHERE  @EDate between SW.date_begin and SW.date_end  
												or @BDate between SW.date_begin and SW.date_end ) f 
										GROUP BY f.link_empl, f.date_n
										
										
										) FN on fn.link_empl = e.link and s.date = fn.date_N
						where
							(@sex = 0 or (@sex <> 0 and sex = @sex))
							and
							((@status = 0 and S.[status] <> 2) or (@status in (1,3) and S.[status] = @status))
							and
							e.dep_link = @DEP_LINK
							AND
							(
								@BUFFER_SUBDIV IS NULL
								OR 
								@BUFFER_SUBDIV IS NOT NULL AND EI.SUBDIV_LINK IN (SELECT B.LINK FROM dbo.BUFFER B WHERE B.ID = @BUFFER_SUBDIV)
							)					
						group by
							FN.date_N
					) as A
					GROUP BY Y, M
				) AS B			
		),2),0)
	END					

	RETURN @Res
END





GO


GRANT EXECUTE ON dbo.[sa_ssch_empls_n] TO PUBLIC

GO



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

GO
CREATE FUNCTION dbo.sa_ssch_empls_nzp_N_ALL(
	@BDate datetime,
	@EDate	datetime,
	@DEP_LINK int ,
	@BUFFER_SUBDIV VARCHAR(20) = NULL --Код буффера, для отбора подразделений	
	)
	
/*определение среднесписочной численности*/
RETURNS TABLE

RETURN
	
	--- считаем для всех
		SELECT [SSCH] = Coalesce((SUM(SSCH)/COUNT(SSCH)),0),cat_nzp_link , code , SPHERE_LINK , [status], NAME_CAT , staff_head 
		FROM
			(
				Select SSCH = sum(cnt_empl) / DAY(dbo.DATEENDOFMONTH(dbo.ConvertDMY2Date(1,M,Y))) , [status], NAME_CAT , staff_head , cat_nzp_link , code , SPHERE_LINK
				from
				(	
					Select cnt_empl = case when  sum( CONVERT(NUMERIC(18,2),isnull(fn.sssch,0.00)) ) =0.00 then sum( CONVERT(NUMERIC(18,2),isnull(ssch,0.00)) ) else sum( CONVERT(NUMERIC(18,2),isnull(fn.sssch,0.00)) ) end , 
							Y = YEAR(DATE), M = MONTH(DATE) , S.[status], pc.NAME_CAT , se.staff_head , st.cat_nzp_link , pc.code , st.SPHERE_LINK
					FROM 
						dbo.empl e
						inner join SD_EMPL se on se.link = e.link
						left join staff st on st.link_up = se.staff_head and  st.link = se.staff_link 
						left join PERS_CATEGORY_BY_SPHERE pc on pc.link = st.cat_nzp_link 				
						inner join dbo.person p on p.link = e.pers_link	
						inner join (select * from dbo.ku_EmplsInPeriod0(@BDate,@EDate, @DEP_LINK, 0, 0) group by date, empl_link,status, sch,ssch,comment) s on  e.link = s.empl_link                                  
						INNER JOIN dbo.SA_EMPLS_INFO_PERIOD(@BDate,@EDate, DEFAULT, @DEP_LINK) EI ON S.EMPL_LINK = EI.EMPL_LINK AND S.[DATE] BETWEEN EI.PERIOD_BEG AND EI.PERIOD_END
						LEFT   JOIN (
										select f.link_empl, f.date_N, sSSCH = (case when sum(f.FACT_NAGR) >= 1 THEN 1 
																					when sum(f.FACT_NAGR) < 1 AND sum(f.FACT_NAGR) <> 0 THEN sum(f.FACT_NAGR) ELSE 0 END )  
										from 
											(SELECT SW.link_empl , SW.fio, SW.link_les, SW.link_paral,SW.NORM_WEEK_HOURS , SW.fact_week_hours,DATE_N = D.[DATE], SW.date_begin , SW.date_end, FACT_NAGR = convert(numeric(15,2),isnull((SW.fact_week_hours/SW.NORM_WEEK_HOURS),0))  
											from  STO_W_HOURS_TABLE SW
											inner join dbo.days_ex(@BDate,@EDate) D on D.[DATE] between SW.DATE_BEGIN AND ISNULL(SW.DATE_END,D.[DATE])
											WHERE  @EDate between SW.date_begin and SW.date_end  
												or @BDate between SW.date_begin and SW.date_end ) f 
										GROUP BY f.link_empl, f.date_n
										
										
										) FN on fn.link_empl = e.link and s.date = fn.date_N
					
					where
						e.dep_link = @DEP_LINK
						AND
						(
							@BUFFER_SUBDIV IS NULL
							OR 
							@BUFFER_SUBDIV IS NOT NULL AND EI.SUBDIV_LINK IN (SELECT B.LINK FROM dbo.BUFFER B WHERE B.ID = @BUFFER_SUBDIV)
						)
					group by
						s.date, S.[status], pc.NAME_CAT , se.staff_head , st.cat_nzp_link , pc.code , st.SPHERE_LINK
						
				) as A 
  			
				GROUP BY Y, M, [status], NAME_CAT , staff_head , cat_nzp_link , code , SPHERE_LINK	
				
			) AS B GROUP  by [status] , cat_nzp_link, NAME_CAT , code , SPHERE_LINK, staff_head 
	



GO


GRANT SELECT ON dbo.[sa_ssch_empls_nzp_N_ALL] TO PUBLIC

GO



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

GO

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

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

SET NOCOUNT  ON

CREATE TABLE #DOC(LINK INT)

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

CREATE TABLE #SPV_ONLY(DOC_LINK INT , SPV_ONLY TINYINT )	
insert into #SPV_ONLY(DOC_LINK, SPV_ONLY)
select 
	doc_link = d.link,
	SPV_ONLY = (SELECT TOP 1 [type] FROM dbo.SA_SZV4_PACHKA WHERE link = d.Link)
from #DOC d


--Опись на пачку
CREATE TABLE #ADV65 (
	LINK_PU int,
	[YEAR] NUMERIC(4),
	[NGROUP] NUMERIC(5),
	[DOCCOUNT] int,
	PERS_CNT int,
	[cGRP] varchar(5),
	[OPT1] tinyint,
	[OPT2] tinyint,
	[OPT3] tinyint,
	[OPT4] tinyint,
	[INC_M1] numeric(18,2),
	[INC_M2] numeric(18,2),
	[INC_M3] numeric(18,2),
	[B_BEF_M1] numeric(18,2),
	[B_BEF_M2] numeric(18,2),
	[B_BEF_M3] numeric(18,2),
	[B_AFT_M1] numeric(18,2),
	[B_AFT_M2] numeric(18,2),
	[B_AFT_M3] numeric(18,2),
	[INSUR] numeric(18,2),
	[INSUR1] numeric(18,2),
	[GAIN] numeric(18,2),
	[GAIN1] numeric(18,2),
	sd_str numeric(18,2),
	sud_str numeric(18,2),
	sd_nak numeric(18,2),
	sud_nak numeric(18,2),
	REG_NOM_PF varchar(20),
	[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,
	T_DOG TINYINT,
	DATE_CRT datetime,
	DATE_DOC datetime,
	SZV TINYINT , NPP  int identity (1,1))	


---
CREATE TABLE #SPV2 (
	LINK_PU int,
	[YEAR] int,
	INN VARCHAR(12),
	KPP VARCHAR(9),
	OKPO VARCHAR(40),
	CODE VARCHAR(20),
	[PER] TINYINT,
	[PER10] TINYINT,
	[YEAR_EDT] int,
	[PER_EDT] 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),
	[INC_T1_M1] numeric(18,2),
	[INC_T1_M2] numeric(18,2),
	[INC_T1_M3] numeric(18,2),
	[INC_T2_M1] numeric(18,2),
	[INC_T2_M2] numeric(18,2),
	[INC_T2_M3] 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), 
	REG_NOM_PF varchar(20),
	DEP_NAME varchar(254),
	DATE_CRT datetime,
	DATE_DOC datetime,
	DD INT, MM varchar(10), YY INT,
	NPP  int)


CREATE TABLE #PERS_INFO2 (
	LINK_PU int,
	[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),
	[INC_T1_M1] numeric(18,2),
	[INC_T1_M2] numeric(18,2),
	[INC_T1_M3] numeric(18,2),
	[INC_T2_M1] numeric(18,2),
	[INC_T2_M2] numeric(18,2),
	[INC_T2_M3] 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),
	T_DOG tinyint,
	REG_NOM_PF varchar(20),
	PFNUMBER varchar(20), 
	DEP_NAME varchar(254),
	DATE_CRT datetime,
	DATE_DOC datetime )


-- Курсор для выбранных из буфера документов перс учета
DECLARE @CURS1 CURSOR, @link_DOC int, @link_doc_old INT 

set @link_doc_old = 0

SET @CURS1 = CURSOR FORWARD_ONLY

FOR SELECT LINK FROM #DOC order by link 


OPEN @CURS1
FETCH NEXT FROM @CURS1 INTO @LINK_DOC

WHILE @@FETCH_STATUS = 0	

BEGIN
		
			if @link_doc_old = 0
			begin
				set @link_doc_old = @LINK_DOC 
			end
			--Опись на пачку
			INSERT INTO #ADV65 (YEAR,NGROUP,DOCCOUNT,PERS_CNT,cGRP,OPT1,OPT2,OPT3,OPT4,
								INC_M1,INC_M2,INC_M3,B_BEF_M1,B_BEF_M2,B_BEF_M3,B_AFT_M1,B_AFT_M2,B_AFT_M3,
								INSUR,INSUR1,GAIN,GAIN1,sd_str,sud_str,sd_nak,sud_nak,REG_NOM_PF,DEP_NAME,OKPO,INN,KPP,CODE,PER,PER10,
								TYPE,PER_EDT,YEAR_EDT,T_DOG,DATE_CRT,DATE_DOC,SZV)
			exec dbo.SZV4_PRINT_ADV65 @LINK_DOC 

			UPDATE #ADV65 SET link_pu = @LINK_DOC FROM #ADV65 WHERE LINK_PU IS NULL 
					--*-* Проставляем номер в пачке
			/*if @link_doc_old <> @LINK_DOC
			begin
				UPDATE #ADV65 SET NGROUP = NGROUP + 1  FROM #ADV65 WHERE LINK_PU = @LINK_DOC
				UPDATE #ADV65 SET cGRP = REPLACE(str((cGRP + 1),5),' ','0')  FROM #ADV65 WHERE LINK_PU = @LINK_DOC
			end*/
		
			--Вдруг ПФР номер не указан
			UPDATE #ADV65 SET PFNUMBER =  case when LEN(RTRIM(LTRIM(COALESCE(REG_NOM_PF,'')))) < 14 AND link_pu = @LINK_DOC then REPLACE(SPACE(14),'              ','000-000-000000') 
													else  RTRIM(LTRIM(COALESCE(REG_NOM_PF,''))) end 			
			
			--- заполение #SPV2

			IF ( SELECT top 1 SPV_ONLY FROM #SPV_ONLY WHERE DOC_LINK = @LINK_DOC) = 2
			BEGIN
				INSERT INTO #SPV2(YEAR,INN,KPP,OKPO,CODE,PER,PER10,YEAR_EDT,PER_EDT,TYPE,ID,NGROUP,PF_NUM,FIO,FM,IM,OT,ADDRESS,
								  ADDRESS2,INSUR,INSUR1,GAIN,GAIN1,INC_T1_M1,INC_T1_M2,INC_T1_M3,INC_T2_M1,INC_T2_M2,INC_T2_M3,
								  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,REG_NOM_PF,DEP_NAME,DATE_CRT,DATE_DOC,DD,MM,YY)
				exec dbo.SZV4_PRINT_SPV2 @LINK_DOC
				
				UPDATE #SPV2 SET link_pu = @LINK_DOC FROM #SPV2 WHERE LINK_PU IS NULL 
				UPDATE #SPV2 set ID_EX = 1 FROM #SPV2 WHERE link_pu = @LINK_DOC and ID_EX is null
			---- пересоберем номера пачек 
					declare @CURS_NUM CURSOR , @NUM_PACH_MIN int, @NUM_PACH1 int, @LINK_PU1 int, @T_DOG1 tinyint , @NGROUP1 int ,  @cGRP1 varchar(5),  @CODE1 varchar(5),  @TYPE1 TINYINT, @NPP int 
					select @NUM_PACH_MIN  =  min(NGROUP) from  #ADV65 

					set @NUM_PACH1 = @NUM_PACH_MIN
					SET @CURS_NUM = CURSOR FORWARD_ONLY
					FOR SELECT link_pu, T_DOG , NGROUP,   cGRP, CODE,  [TYPE], NPP  FROM #ADV65 order by NPP


					OPEN @CURS_NUM
					FETCH NEXT FROM @CURS_NUM INTO @LINK_PU1,@T_DOG1,@NGROUP1, @cGRP1, @CODE1 , @TYPE1, @NPP

					WHILE @@FETCH_STATUS = 0	

					BEGIN
								
								update S SET  S.NPP = @NPP
									from #SPV2 S  where S.link_pu =@LINK_PU1 and S.NGROUP = @NGROUP1 and LTRIM(RTRIM(S.CODE)) = LTRIM(RTRIM(@CODE1)) AND S.[TYPE] = @TYPE1
								
								if @NUM_PACH1 <> @NUM_PACH_MIN
								BEGIN
									update #ADV65 set NGROUP = @NUM_PACH1 ,
												  cGRP = REPLACE(str((@NUM_PACH1),5),' ','0')
									from #ADV65  where link_pu =@LINK_PU1 and T_DOG = @T_DOG1 and NGROUP = @NGROUP1 and cGRP = @cGRP1 and CODE = @CODE1 and NPP = @NPP
								
									UPDATE S SET NGROUP = (SELECT NGROUP from #ADV65  where link_pu =@LINK_PU1 and T_DOG = @T_DOG1 and CODE = @CODE1 and NPP = @NPP AND [TYPE] =@TYPE1)  
									  FROM #SPV2 S WHERE link_pu =@LINK_PU1  and CODE = @CODE1 and NPP = @NPP AND [TYPE] =@TYPE1
								
								END
								
								SET @NUM_PACH1 = @NUM_PACH1+1 

						FETCH NEXT FROM @CURS_NUM INTO @LINK_PU1,@T_DOG1,@NGROUP1, @cGRP1, @CODE1, @TYPE1, @NPP
					END

					CLOSE @CURS_NUM
					DEALLOCATE @CURS_NUM	


						--*-* Проставляем номер в пачке
				/*if @link_doc_old <> @LINK_DOC
				begin
					UPDATE #SPV2 SET NGROUP = NGROUP + 1  FROM #SPV2 WHERE LINK_PU = @LINK_DOC
				end
				*/		
				update #SPV2 set FM = UPPER(FM), IM = UPPER(IM), OT = UPPER(OT), ADDRESS2 = UPPER(ADDRESS2) WHERE link_pu = @LINK_DOC 
			

				-- заполение #PERS_INFO2 

				INSERT INTO #PERS_INFO2(LINK_PU,[YEAR], INN, KPP, OKPO, CODE, [PER], [PER10], [PER_EDT], [YEAR_EDT], [TYPE],
										[ID], [NGROUP], [PF_NUM], [FIO], [FM], [IM], [OT], [ADDRESS], [ADDRESS2],
										[INSUR], [INSUR1], [GAIN], [GAIN1],INC_T1_M1,INC_T1_M2,INC_T1_M3,INC_T2_M1,INC_T2_M2,INC_T2_M3,
										[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	LINK_PU,[YEAR], INN, KPP, OKPO, CODE, [PER], [PER10], [PER_EDT], [YEAR_EDT], [TYPE],
						[ID], [NGROUP], [PF_NUM], [FIO], [FM], [IM], [OT], [ADDRESS], [ADDRESS2],
						[INSUR], [INSUR1], [GAIN], [GAIN1],INC_T1_M1,INC_T1_M2,INC_T1_M3,INC_T2_M1,INC_T2_M2,INC_T2_M3, 
						[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,
						REG_NOM_PF, DEP_NAME, DATE_CRT, DATE_DOC
				FROM #SPV2
			
			
			END	
			

			set @link_doc_old = @link_doc

	FETCH NEXT FROM @CURS1 INTO @LINK_DOC
END

CLOSE @CURS1
DEALLOCATE @CURS1			

DECLARE @NN INT, @PN INT, @ON INT
SELECT @NN = 0, @PN = 0, @ON = 0


SELECT *
INTO #PERS_INFO 
FROM #PERS_INFO2 ORDER BY link_pu,T_DOG , NGROUP, [ID]


DECLARE @PI_NGROUP INT, @PI_ID INT, @PI_link_pu int, @PI_T_DOG tinyint  
DECLARE @Cur_PI CURSOR
SET @Cur_PI = CURSOR FORWARD_ONLY

FOR select link_pu, NGROUP,T_DOG, [ID]  from #PERS_INFO order by link_pu,T_DOG, NGROUP, [ID]

OPEN @Cur_PI
FETCH NEXT FROM @Cur_PI INTO @PI_link_pu, @PI_NGROUP,@PI_T_DOG, @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 link_pu = @PI_link_pu and  NGROUP = @PI_NGROUP and  T_DOG = @PI_T_DOG  AND ID = @PI_ID

		SET @ON = @NN				

	END

	FETCH NEXT FROM @Cur_PI INTO @PI_link_pu, @PI_NGROUP,@PI_T_DOG, @PI_ID
END

CLOSE @Cur_PI
DEALLOCATE @Cur_PI

--select * from #ADV65
--select * from #SZV62
--select * from #SZV61
--select * from #PERS_INFO
--select * from #SPV2
--select * from #PERS_INFO2


--Строка заголовка
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, @LINK_PU INT, @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),
	@INC_T1_M1 VARCHAR(20),@INC_T1_M2 VARCHAR(20),@INC_T1_M3 VARCHAR(20),@INC_T2_M1 VARCHAR(20),@INC_T2_M2 VARCHAR(20),@INC_T2_M3 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 = (SELECT TOP 1 LINK FROM #DOC )


--select 	
--	/*LINK_PU,*/
--	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 #ADV65 order by /*LINK_PU,*/ NGROUP


SET @Cur1 = CURSOR FORWARD_ONLY
FOR 
select 	
	LINK_PU,
	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 #ADV65 order by LINK_PU,NGROUP, T_DOG
/*ВХОДЯЩАЯ ОПИСЬ AДВ63 практически то же самое что и опись АДВ61 */
OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @LINK_PU,@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(2) + '</ВХОДЯЩАЯ_ОПИСЬ>'

		--Экспорт СПВ-2
		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) + '<ТипСведений>'+ @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 @PER WHEN 1 THEN '3' WHEN 2 THEN '6' WHEN 3 THEN '9' ELSE '0' END + '</Квартал>'+ CHAR(10)
		+ 	 SPACE(4) + '<Год>' + @YEAR + '</Год>' + CHAR(10)
		+ 	 SPACE(4) + '<Название>' + 
										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	
									+ '</Название>' + CHAR(10)
		+ 	SPACE(3) + '</ОтчетныйПериод>' + CHAR(10)
		+	CASE WHEN @PER_EDT <> '0' THEN
		 	SPACE(3) +  '<КорректируемыйОтчетныйПериод>' + CHAR(10)
		+ 	 SPACE(4) + '<Квартал>' + CASE @PER_EDT WHEN 1 THEN '3' WHEN 2 THEN '6' WHEN 3 THEN '9' ELSE '0' END + '</Квартал>'+ CHAR(10)
		+ 	 SPACE(4) + '<Год>' + @YEAR_EDT + '</Год>' + CHAR(10)
		+ 	 SPACE(4) + '<Название>' + 
										CASE @PER_EDT 
											WHEN '1' THEN 'С 01.01.'+@YEAR_EDT+' ПО 31.03.'+@YEAR_EDT
											WHEN '2' THEN 'С 01.04.'+@YEAR_EDT+' ПО 30.06.'+@YEAR_EDT
											WHEN '3' THEN 'С 01.07.'+@YEAR_EDT+' ПО 30.09.'+@YEAR_EDT
											WHEN '4' THEN 'С 01.10.'+@YEAR_EDT+' ПО 31.12.'+@YEAR_EDT
											ELSE ''
										END 
									+ '</Название>' + CHAR(10)
		+ 	SPACE(3) + '</КорректируемыйОтчетныйПериод>' + 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)
		
		+ 	SPACE(3) + '<ДатаЗаполнения>' + @DATE_DOC + '</ДатаЗаполнения>' + CHAR(10)
		+ 	CASE WHEN @TYPDOC = 'СПВ-1' THEN SPACE(3) + '<ДатаСоставленияНа>' + @DATE_DOC + '</ДатаСоставленияНа>' ELSE '' END
		,
		--В этом промежутки блоки со стажем
		---------------------------------------------------
		SPACE(1) + '</СВЕДЕНИЯ_О_СТРАХОВОМ_СТАЖЕ_ЗЛ_ДЛЯ_УСТАНОВЛЕНИЯ_ПЕНСИИ>'
		from #PERS_INFO where LINK_PU = @LINK_PU and NGROUP = @NGROUP and ID_EX = 1
		Group by LINK_PU, id , ID_EX,PF_NUM,FM,IM,OT
		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 LINK_PU = @LINK_PU and  NGROUP = @NGROUP and ID_EX >= 1) --AND @SZV = 1 AND @TYPDOC = 'СПВ-1'
					BEGIN
						INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
						Select @lcFNAME,
						CASE WHEN @TYPE <> 'ОТМЕНЯЮЩАЯ' THEN			
							+	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) + '<ПозицияСписка>' + UPPER(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) + '</СтажевыйПериод>'
						ELSE '' END
						from #PERS_INFO where LINK_PU = @LINK_PU and NGROUP = @NGROUP AND [ID] = @PERS_ID
						Group by LINK_PU, id , ID_EX,PF_NUM,FM,IM,OT, DATE_BEGIN,DATE_END,ter_usl,osob_usl,EX_CODE,is_dop,P_CODE,ter_koef,osob_spis,f_is_dop, 
									is_dop_m, is_dop_d,f_ud_dop, ud_dop_m,ud_dop_d,f_ud_dop,ud_dop_m,ud_dop_k
						ORDER BY [ID]

					END
						
					
					
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
					Select @lcFNAME,
							SPACE(4) + '<ПризнакНачисленияВзносовОПС>' + CASE WHEN ISNULL(INSUR,0) <> 0 THEN 'ДА' ELSE 'НЕТ' END  + '</ПризнакНачисленияВзносовОПС>' + CHAR(10)
							+ SPACE(4) + '<ПризнакНачисленияВзносовПоДопТарифу>' + CASE WHEN (SUM(ISNULL(INC_T1_M1,0))+SUM(ISNULL(INC_T1_M2,0))+ SUM(ISNULL(INC_T1_M3,0)) +SUM(ISNULL(INC_T2_M1,0)) + SUM(ISNULL(INC_T2_M2,0))+ SUM(ISNULL(INC_T2_M3,0))) <> 0 then 'ДА' else 'НЕТ' end + '</ПризнакНачисленияВзносовПоДопТарифу>'
					from #PERS_INFO where LINK_PU = @LINK_PU and NGROUP = @NGROUP AND [ID] = @PERS_ID
					GROUP BY LINK_PU, NGROUP , [ID] , INSUR
					ORDER BY [ID]
					
	
					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  @LINK_PU, @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


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_14] TO PUBLIC

GO




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

GO

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

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

SET NOCOUNT  ON

CREATE TABLE #DOC(LINK INT)

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

CREATE TABLE #SPV_ONLY(DOC_LINK INT , SPV_ONLY TINYINT )	
insert into #SPV_ONLY(DOC_LINK, SPV_ONLY)
select 
	doc_link = d.link,
	SPV_ONLY = (SELECT TOP 1 [type] FROM dbo.SA_SZV4_PACHKA WHERE link = d.Link)
from #DOC d


--Опись на пачку
-- Опись по документам АДВ-6-5	
CREATE TABLE #ADV65 (
	LINK_PU int,
	[YEAR] NUMERIC(4),
	[NGROUP] NUMERIC(5),
	[DOCCOUNT] int,
	PERS_CNT int,
	[cGRP] varchar(5),
	[OPT1] tinyint,
	[OPT2] tinyint,
	[OPT3] tinyint,
	[OPT4] tinyint,
	[INC_M1] numeric(18,2),
	[INC_M2] numeric(18,2),
	[INC_M3] numeric(18,2),
	[B_BEF_M1] numeric(18,2),
	[B_BEF_M2] numeric(18,2),
	[B_BEF_M3] numeric(18,2),
	[B_AFT_M1] numeric(18,2),
	[B_AFT_M2] numeric(18,2),
	[B_AFT_M3] numeric(18,2),
	[INSUR] numeric(18,2),
	[INSUR1] numeric(18,2),
	[GAIN] numeric(18,2),
	[GAIN1] numeric(18,2),
	sd_str numeric(18,2),
	sud_str numeric(18,2),
	sd_nak numeric(18,2),
	sud_nak numeric(18,2),
	REG_NOM_PF varchar(20),
	[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,
	T_DOG TINYINT,
	DATE_CRT datetime,
	DATE_DOC datetime,
	SZV TINYINT , NPP  int identity (1,1))	

--- 
	CREATE TABLE #SZV64(
	LINK_PU int,
	[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),
	[T_DOG] tinyint, 
	[FIO] VARCHAR(254),
	[FM] VARCHAR(100),
	[IM] VARCHAR(100),
	[OT] VARCHAR(100),
	[ADDRESS] VARCHAR(254),
	[ADDRESS2] VARCHAR(254),
	[INC_M1] numeric(18,2),
	[INC_M2] numeric(18,2),
	[INC_M3] numeric(18,2),
	[B_BEF_M1] numeric(18,2),
	[B_BEF_M2] numeric(18,2),
	[B_BEF_M3] numeric(18,2),
	[B_AFT_M1] numeric(18,2),
	[B_AFT_M2] numeric(18,2),
	[B_AFT_M3] numeric(18,2),
	[INC_T1M1] numeric(18,2),
	[INC_T2M1] numeric(18,2),
	[INC_T1M2] numeric(18,2),
	[INC_T2M2] numeric(18,2),
	[INC_T1M3] numeric(18,2),
	[INC_T2M3] numeric(18,2),
	[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),
	REG_NOM_PF varchar(20),
	--PFNUMBER varchar(20), 
	DEP_NAME varchar(254),
	DATE_CRT datetime,
	DATE_DOC datetime )	
	
	
---
CREATE TABLE #SPV1 (
	LINK_PU int,
	[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), 
	REG_NOM_PF varchar(20),
	DEP_NAME varchar(254),
	DATE_CRT datetime,
	DATE_DOC datetime,
	DD INT, MM varchar(10), YY INT
	 )


CREATE TABLE #PERS_INFO2 (
	LINK_PU int,
	[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),
	INC_M1 numeric(18,2),
	B_BEF_M1 numeric(18,2),
	B_AFT_M1 numeric(18,2),
	INC_M2   numeric(18,2),
	B_BEF_M2 numeric(18,2),
	B_AFT_M2 numeric(18,2),
	INC_M3	 numeric(18,2),
	B_BEF_M3 numeric(18,2),
	B_AFT_M3 numeric(18,2),
	INC_T1M1 numeric(18,2),
	INC_T2M1 numeric(18,2),
	INC_T1M2 numeric(18,2),
	INC_T2M2 numeric(18,2),
	INC_T1M3 numeric(18,2), 
	INC_T2M3 numeric(18,2),
	[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),
	T_DOG tinyint,
	REG_NOM_PF varchar(20),
	PFNUMBER varchar(20), 
	DEP_NAME varchar(254),
	DATE_CRT datetime,
	DATE_DOC datetime )



-- Курсор для выбранных из буфера документов перс учета
DECLARE @CURS1 CURSOR, @link_DOC int, @link_doc_old int, @NG int, @NGPP1 int, @Typ int
set @NGPP1 = 1
set @NG = 0 
set @Typ = 0
set @link_doc_old = 0
SET @CURS1 = CURSOR FORWARD_ONLY

FOR SELECT LINK FROM #DOC order by link 


OPEN @CURS1
FETCH NEXT FROM @CURS1 INTO @LINK_DOC

WHILE @@FETCH_STATUS = 0	

BEGIN

			if @link_doc_old = 0
			begin
				set @link_doc_old = @LINK_DOC 
			end
			--Опись на пачку
			--Опись на документы
			INSERT INTO #ADV65  (YEAR,NGROUP,DOCCOUNT,PERS_CNT,cGRP,OPT1,OPT2,OPT3,OPT4,
								INC_M1,INC_M2,INC_M3,B_BEF_M1,B_BEF_M2,B_BEF_M3,B_AFT_M1,B_AFT_M2,B_AFT_M3,
								INSUR,INSUR1,GAIN,GAIN1,sd_str,sud_str,sd_nak,sud_nak,REG_NOM_PF,DEP_NAME,OKPO,INN,KPP,CODE,PER,PER10,
								TYPE,PER_EDT,YEAR_EDT,T_DOG,DATE_CRT,DATE_DOC,SZV)
			exec dbo.SZV4_PRINT_ADV65 @LINK_DOC 

			UPDATE #ADV65 SET link_pu = @LINK_DOC FROM #ADV65 WHERE LINK_PU IS NULL 
					--*-* Проставляем номер в пачке
			if @link_doc_old <> @LINK_DOC
			begin
				
				UPDATE #ADV65 SET NGROUP = NGROUP + 1  FROM #ADV65 WHERE LINK_PU = @LINK_DOC
				UPDATE #ADV65 SET cGRP = REPLACE(str((cGRP + 1),5),' ','0')  FROM #ADV65 WHERE LINK_PU = @LINK_DOC
			end
	
			--Вдруг ПФР номер не указан
			UPDATE #ADV65 SET PFNUMBER = case when LEN(RTRIM(LTRIM(COALESCE(REG_NOM_PF,'')))) < 14 AND link_pu = @LINK_DOC	then REPLACE(SPACE(14),'              ','000-000-000000') 
													else RTRIM(LTRIM(COALESCE(REG_NOM_PF,''))) end 		
			
			
			---- пересоберем номера пачек 
					declare @CURS_NUM CURSOR , @NUM_PACH_MIN int, @NUM_PACH1 int, @LINK_PU1 int, @T_DOG1 tinyint , @NGROUP1 int ,  @cGRP1 varchar(5),  @CODE1 varchar(5) , @NPP int 
					select @NUM_PACH_MIN  =  min(NGROUP) from  #ADV65 

					set @NUM_PACH1 = @NUM_PACH_MIN
					SET @CURS_NUM = CURSOR FORWARD_ONLY

					FOR SELECT link_pu, T_DOG , NGROUP,   cGRP, CODE, NPP  FROM #ADV65 order by NPP


					OPEN @CURS_NUM
					FETCH NEXT FROM @CURS_NUM INTO @LINK_PU1,@T_DOG1,@NGROUP1, @cGRP1, @CODE1 , @NPP

					WHILE @@FETCH_STATUS = 0	

					BEGIN

								if @NUM_PACH1 <> @NUM_PACH_MIN
								BEGIN
									update #ADV65 set NGROUP = @NUM_PACH1 ,
												  cGRP = REPLACE(str((@NUM_PACH1),5),' ','0')
									from #ADV65  where link_pu =@LINK_PU1 and T_DOG = @T_DOG1 and NGROUP = @NGROUP1 and cGRP = @cGRP1 and CODE = @CODE1 and NPP = @NPP
								END
								
								SET @NUM_PACH1 = @NUM_PACH1+1 

						FETCH NEXT FROM @CURS_NUM INTO @LINK_PU1,@T_DOG1,@NGROUP1, @cGRP1, @CODE1 , @NPP
					END

					CLOSE @CURS_NUM
					DEALLOCATE @CURS_NUM	
			
		
			--- заполнение #SZV61
			IF ( SELECT top 1 SPV_ONLY FROM #SPV_ONLY WHERE DOC_LINK = @LINK_DOC) = 1
			BEGIN

				--- СЗВ6-4
				INSERT INTO #SZV64(	[YEAR],INN,KPP,OKPO,CODE,[PER],[PER10],[TYPE],[PER_EDT],[YEAR_EDT],[ID],[NGROUP],[PF_NUM],[T_DOG],[FIO],[FM],[IM],[OT],
									[ADDRESS],[ADDRESS2],INC_M1,B_BEF_M1,B_AFT_M1,INC_M2,B_BEF_M2,B_AFT_M2,INC_M3,B_BEF_M3,B_AFT_M3,INC_T1M1,INC_T2M1,INC_T1M2,INC_T2M2,INC_T1M3,INC_T2M3,
									[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,REG_NOM_PF,DEP_NAME,DATE_CRT,DATE_DOC)
									
				exec dbo.SZV4_PRINT_SZV64 @LINK_DOC 
				UPDATE #SZV64 SET link_pu = @LINK_DOC FROM #SZV64 WHERE LINK_PU IS NULL 
				set @Typ = (select distinct [TYPE] from #SZV64  where link_pu = @link_doc_old)
				--select @NG = (select max([NGROUP]) from #SZV64  where NGROUP is not null)
				
				
						--*-* Проставляем номер в пачке
				if @link_doc_old <> @LINK_DOC
				begin
				
					select @NG = (select max([NGROUP]) from #SZV64  where NGROUP is not null)
					UPDATE #SZV64 SET NGROUP = @NG + 1  FROM #SZV64 WHERE LINK_PU = @LINK_DOC /*and  [TYPE] > @Typ*/

				end
			
				update #SZV64 set FM = UPPER(FM), IM = UPPER(IM), OT = UPPER(OT), ADDRESS2 = UPPER(ADDRESS2), f_is_dop = UPPER(f_is_dop) FROM #SZV64 WHERE link_pu = @LINK_DOC
				UPDATE #SZV64 set ID_EX = 1 FROM #SZV64 WHERE link_pu = @LINK_DOC and ID_EX is null
					---- пересоберем номера пачек 
					select @NUM_PACH1  =  max(NGROUP) from  #SZV64  where T_DOG = 1 

					--update #SZV64 set NGROUP = @NUM_PACH1 + 1 from #SZV64  where T_DOG <> 1 
			
						
						DECLARE @NN1 INT, @PN1 INT, @ON1 INT
						SELECT @NN1 = 0, @PN1 = 0, @ON1 = 0
						DECLARE @PI_NGROUP1 INT, @PI_ID1 INT, @PI_link_pu1 int , @PI_T_DOG1 tinyint  
						DECLARE @Cur_PI1 CURSOR
						SET @Cur_PI1 = CURSOR FORWARD_ONLY

						FOR select link_pu, NGROUP,T_DOG, [ID]  from #SZV64 order by link_pu,T_DOG, NGROUP, [ID] 

						OPEN @Cur_PI1
						FETCH NEXT FROM @Cur_PI1 INTO @PI_link_pu1, @PI_NGROUP1, @PI_T_DOG1, @PI_ID1
						WHILE (@@fetch_status <> -1)
						BEGIN
							IF (@@fetch_status <> -2)
							BEGIN

								SET @NN1 = (CASE WHEN @PI_NGROUP1 <> @PN1 THEN 1 ELSE (CASE WHEN @ON1 <> @PI_ID1 THEN @NN1 + 1 ELSE @NN1 END) END)
								SET @PN1 = (CASE WHEN @PI_NGROUP1 <> @PN1 THEN @PI_NGROUP1 ELSE @PN1 END)

								UPDATE A
								SET 
									ID = @NN1
								FROM #SZV64 A 
								WHERE link_pu = @PI_link_pu1 and  NGROUP = @PI_NGROUP1 and  T_DOG = @PI_T_DOG1 AND ID = @PI_ID1 

								SET @ON1 = @NN1				

							END

							FETCH NEXT FROM @Cur_PI1 INTO @PI_link_pu1, @PI_NGROUP1, @PI_T_DOG1, @PI_ID1
						END

						CLOSE @Cur_PI1
						DEALLOCATE @Cur_PI1
						
			END
			

			--- заполнение #PERS_INFO2
			INSERT INTO #PERS_INFO2 (LINK_PU,[YEAR],INN,KPP,OKPO,CODE,[PER],[PER10],[TYPE],[PER_EDT],[YEAR_EDT],
									[ID],[NGROUP],[PF_NUM], T_DOG,[FIO],[FM],[IM],[OT],[ADDRESS],[ADDRESS2],
									INC_M1,INC_M2,INC_M3,B_BEF_M1,B_BEF_M2,B_BEF_M3,B_AFT_M1,B_AFT_M2,B_AFT_M3,INC_T1M1,INC_T2M1,INC_T1M2,INC_T2M2,INC_T1M3,INC_T2M3,
									[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 * FROM #SZV64	WHERE link_pu = @LINK_DOC	 order by NGROUP , ID , ID_EX



			--- заполение #SPV1

			IF ( SELECT top 1 SPV_ONLY FROM #SPV_ONLY WHERE DOC_LINK = @LINK_DOC) = 2
			BEGIN
				INSERT INTO #SPV1(YEAR,INN,KPP,OKPO,CODE,PER,PER10,TYPE,ID,NGROUP,PFNUMBER,FIO,FM,IM,OT,ADDRESS,
								  ADDRESS2,INSUR,INSUR1,GAIN,GAIN1,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,REG_NOM_PF,DEP_NAME,DATE_CRT,DATE_DOC,DD,MM,YY)
				exec dbo.SZV4_PRINT_SPV1 @LINK_DOC
				
						
				UPDATE #SPV1 SET link_pu = @LINK_DOC FROM #SPV1 WHERE LINK_PU IS NULL 
		
						--*-* Проставляем номер в пачке
				if @link_doc_old <> @LINK_DOC
				begin
					UPDATE #SPV1 SET NGROUP = NGROUP + 1  FROM #SPV1 WHERE LINK_PU = @LINK_DOC
				end
						
				update #SPV1 set FM = UPPER(FM), IM = UPPER(IM), OT = UPPER(OT), ADDRESS2 = UPPER(ADDRESS2) WHERE link_pu = @LINK_DOC 
				-- заполение #PERS_INFO2 
				INSERT INTO #PERS_INFO2(LINK_PU,[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	LINK_PU,[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,
						REG_NOM_PF, DEP_NAME, DATE_CRT, DATE_DOC
				FROM #SPV1
			END	

			set @link_doc_old = @link_doc


	FETCH NEXT FROM @CURS1 INTO @LINK_DOC
END

CLOSE @CURS1
DEALLOCATE @CURS1			

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

DECLARE @NN INT, @PN INT, @ON INT
SELECT @NN = 0, @PN = 0, @ON = 0

SELECT *
INTO #PERS_INFO 
FROM #PERS_INFO2 ORDER BY link_pu,T_DOG , NGROUP,   [ID] 

DECLARE @PI_NGROUP INT, @PI_ID INT, @PI_link_pu int , @PI_T_DOG tinyint  
DECLARE @Cur_PI CURSOR
SET @Cur_PI = CURSOR FORWARD_ONLY

FOR select link_pu, NGROUP,T_DOG, [ID]  from #PERS_INFO order by link_pu,T_DOG, NGROUP, [ID] 

OPEN @Cur_PI
FETCH NEXT FROM @Cur_PI INTO @PI_link_pu, @PI_NGROUP, @PI_T_DOG, @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 link_pu = @PI_link_pu and  NGROUP = @PI_NGROUP and  T_DOG = @PI_T_DOG AND ID = @PI_ID 

		SET @ON = @NN				

	END

	FETCH NEXT FROM @Cur_PI INTO @PI_link_pu, @PI_NGROUP, @PI_T_DOG, @PI_ID
END

CLOSE @Cur_PI
DEALLOCATE @Cur_PI

--select * from #ADV65
--select * from #SZV62
--select * from #SZV64
--select * from #PERS_INFO
--select * from #SPV1
--select * from #PERS_INFO2

--Строка заголовка
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, @LINK_PU INT, @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),
	@sd_str VARCHAR(20),@sud_str VARCHAR(20),@sd_nak VARCHAR(20),@sud_nak 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),  @T_DOG tinyint, @T_DOG_N varchar (20),
	@INC_M1 numeric(18,2),@INC_M2 numeric(18,2),@INC_M3 numeric(18,2),@B_BEF_M1 numeric(18,2),@B_BEF_M2 numeric(18,2),@B_BEF_M3 numeric(18,2),
	@B_AFT_M1 numeric(18,2),@B_AFT_M2 numeric(18,2),@B_AFT_M3 numeric(18,2),
	@INC_T1M1 VARCHAR(20),@INC_T2M1 VARCHAR(20),@INC_T1M2 VARCHAR(20),@INC_T2M2 VARCHAR(20),@INC_T1M3 VARCHAR(20),@INC_T2M3 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 = (SELECT TOP 1 LINK FROM #DOC )

SET @Cur1 = CURSOR FORWARD_ONLY
FOR 
select 	
	LINK_PU,
	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 [TYPE] <> 1 AND  CONVERT(VARCHAR(4),[YEAR_EDT]) < '2013' THEN ( case when SZV = 1 then 'СЗВ-6-1' ELSE 'СЗВ-6-2' END ) ELSE 'СЗВ-6-4' 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),
	INC_M1,
	INC_M2,
	INC_M3,
	B_BEF_M1,
	B_BEF_M2,
	B_BEF_M3,
	B_AFT_M1,
	B_AFT_M2,
	B_AFT_M3,
	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))),
	sd_str = RTRIM(LTRIM(STR(COALESCE(sd_str,0),15,2))), 
	sud_str = RTRIM(LTRIM(STR(COALESCE(sud_str,0),15,2))),
	sd_nak = RTRIM(LTRIM(STR(COALESCE(sd_nak,0),15,2))),
	sud_nak = RTRIM(LTRIM(STR(COALESCE(sud_nak,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,
	[T_DOG],
	T_DOG_N = CASE WHEN T_DOG = 1 then  'ТРУДОВОЙ' else 'ГРАЖДАНСКО-ПРАВОВОЙ' end
from #ADV65 order by  LINK_PU,NGROUP, T_DOG 

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @LINK_PU,@NGROUP, @lcFNAME, @INN, @KPP, @DEP_NAME, @PFNUMBER, @PACHNUM, @DOCCOUNT, @TYPDOC, @PERSCNT, @DATE_CRT, @DATE_DOC, @YEAR,
	@SZV, @TYP_SVED, @VID_KOR, @INC_M1 ,@INC_M2,@INC_M3,@B_BEF_M1,@B_BEF_M2,@B_BEF_M3,	@B_AFT_M1,@B_AFT_M2,@B_AFT_M3,
	@INSUR, @INSUR1, @GAIN, @GAIN1,@sd_str,@sud_str,@sd_nak,@sud_nak, @PER, @TYPE, @PER_EDT, @YEAR_EDT, @PER_EDT_NAME, @TYPE, @KATEG, @PER_NAME,@T_DOG,@T_DOG_N 

WHILE (@@fetch_status <> -1)
BEGIN
	
	IF (@@fetch_status <> -2)
	BEGIN	
			
			IF @TYPE <> 'ОТМЕНЯЮЩАЯ'  --ЕСЛИ Сведения отменяющие , заполняем иначе --
			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) + CASE WHEN @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' THEN '<ВХОДЯЩАЯ_ОПИСЬ_ПО_СТРАХОВЫМ_ВЗНОСАМ>'  ELSE '<ВХОДЯЩАЯ_ОПИСЬ_ПО_СУММАМ_ВЫПЛАТ_И_ПО_СТРАХОВЫМ_ВЗНОСАМ>' END 
					   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) + CASE WHEN @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013'   THEN '<ТипДокумента>СВЕДЕНИЯ_О_СТРАХОВЫХ_ВЗНОСАХ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ</ТипДокумента>' ELSE  '<ТипДокумента>СВЕДЕНИЯ_О_СУММЕ_ВЫПЛАТ_О_СТРАХОВЫХ_ВЗНОСАХ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ</ТипДокумента>'  END 
						   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) 
																				 WHEN @YEAR >= '2014' THEN (CASE @PER WHEN '1' THEN '3' WHEN '2' THEN '6' WHEN '3' THEN '9' ELSE '0' 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
											WHEN @YEAR >= '2014' THEN
												CASE @PER 
													WHEN '1' THEN 'С 01.01.'+@YEAR+' ПО 31.03.'+@YEAR
													WHEN '2' THEN 'С 01.01.'+@YEAR+' ПО 30.06.'+@YEAR
													WHEN '3' THEN 'С 01.01.'+@YEAR+' ПО 30.09.'+@YEAR
													WHEN '4' THEN 'С 01.01.'+@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_EDT+' ПО 30.06.'+@YEAR_EDT
													WHEN '4' THEN 'С 01.07.'+@YEAR_EDT+' ПО 31.12.'+@YEAR_EDT
													ELSE ''
												END
											ELSE
												CASE @PER_EDT 
													WHEN '1' THEN 'С 01.01.'+@YEAR_EDT+' ПО 31.03.'+@YEAR_EDT
													WHEN '2' THEN 'С 01.04.'+@YEAR_EDT+' ПО 30.06.'+@YEAR_EDT
													WHEN '3' THEN 'С 01.07.'+@YEAR_EDT+' ПО 30.09.'+@YEAR_EDT
													WHEN '4' THEN 'С 01.10.'+@YEAR_EDT+' ПО 31.12.'+@YEAR_EDT
													ELSE ''
												END									
										END	+ '</Название>' WHERE @PER_EDT <> '0'
					   UNION ALL SELECT @lcFNAME, SPACE(3) + '</КорректируемыйОтчетныйПериод>' WHERE @PER_EDT <> '0'
					   	UNION ALL SELECT @lcFNAME, SPACE(3) + CASE WHEN @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013'  THEN '' ELSE  '<ТипДоговора>'+@T_DOG_N+'</ТипДоговора>' END
					   UNION ALL SELECT @lcFNAME, SPACE(3) + CASE WHEN @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' THEN '' ELSE '<СуммаВыплатИвознагражденийВпользуЗЛ>' END 
						UNION ALL SELECT @lcFNAME, SPACE(4) + CASE WHEN @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013'  THEN '' ELSE '<ТипСтроки>ИТОГ</ТипСтроки>' END
						--UNION ALL SELECT @lcFNAME, SPACE(4) + '<Месяц>'+@M1+'</Месяц>'
						UNION ALL SELECT @lcFNAME, SPACE(4) + CASE WHEN @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013'  THEN '' ELSE '<СуммаВыплатВсего>'+RTRIM(LTRIM(STR((COALESCE(@INC_M1,0) + COALESCE(@INC_M2,0)+ COALESCE(@INC_M3,0)),15,2)))+'</СуммаВыплатВсего>' END 
						UNION ALL SELECT @lcFNAME, SPACE(4) + CASE WHEN @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' THEN '' ELSE '<СуммаВыплатНачисленыСтраховыеВзносыНеПревышающие>'+RTRIM(LTRIM(STR((COALESCE(@B_BEF_M1,0) + COALESCE(@B_BEF_M2,0)+ COALESCE(@B_BEF_M3,0)),15,2)))+'</СуммаВыплатНачисленыСтраховыеВзносыНеПревышающие>' END 
						UNION ALL SELECT @lcFNAME, SPACE(4) + CASE WHEN @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' THEN '' ELSE '<СуммаВыплатНачисленыСтраховыеВзносыПревышающие>'+RTRIM(LTRIM(STR((COALESCE(@B_AFT_M1,0) + COALESCE(@B_AFT_M2,0)+ COALESCE(@B_AFT_M3,0)),15,2)))+'</СуммаВыплатНачисленыСтраховыеВзносыПревышающие>' END 
					   UNION ALL SELECT @lcFNAME, SPACE(3) + CASE WHEN @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' THEN '' ELSE '</СуммаВыплатИвознагражденийВпользуЗЛ>' END 
				
						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) + CASE WHEN @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' THEN '</ВХОДЯЩАЯ_ОПИСЬ_ПО_СТРАХОВЫМ_ВЗНОСАМ>' ELSE '</ВХОДЯЩАЯ_ОПИСЬ_ПО_СУММАМ_ВЫПЛАТ_И_ПО_СТРАХОВЫМ_ВЗНОСАМ>'  END 
			 END
			 ELSE  --Отменяющие сведения заполняются иначе-
			 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) + CASE WHEN @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' THEN '<ВХОДЯЩАЯ_ОПИСЬ_ПО_СТРАХОВЫМ_ВЗНОСАМ>' ELSE  '<ВХОДЯЩАЯ_ОПИСЬ_ПО_СУММАМ_ВЫПЛАТ_И_ПО_СТРАХОВЫМ_ВЗНОСАМ>' END 
						   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) + CASE WHEN @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013'  THEN '<ТипДокумента>СВЕДЕНИЯ_О_СТРАХОВЫХ_ВЗНОСАХ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ</ТипДокумента>' ELSE '<ТипДокумента>СВЕДЕНИЯ_О_СУММЕ_ВЫПЛАТ_О_СТРАХОВЫХ_ВЗНОСАХ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ</ТипДокумента>'  END 
							   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) 
																					 WHEN @YEAR >= '2014' THEN (CASE @PER WHEN '1' THEN '3' WHEN '2' THEN '6' WHEN '3' THEN '9' ELSE '0' 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
												WHEN @YEAR >= '2014' THEN
													CASE @PER 
														WHEN '1' THEN 'С 01.01.'+@YEAR+' ПО 31.03.'+@YEAR
														WHEN '2' THEN 'С 01.01.'+@YEAR+' ПО 30.06.'+@YEAR
														WHEN '3' THEN 'С 01.01.'+@YEAR+' ПО 30.09.'+@YEAR
														WHEN '4' THEN 'С 01.01.'+@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_EDT+' ПО 30.06.'+@YEAR_EDT
														WHEN '4' THEN 'С 01.07.'+@YEAR_EDT+' ПО 31.12.'+@YEAR_EDT
														ELSE ''
													END
												ELSE
													CASE @PER_EDT 
														WHEN '1' THEN 'С 01.01.'+@YEAR_EDT+' ПО 31.03.'+@YEAR_EDT
														WHEN '2' THEN 'С 01.04.'+@YEAR_EDT+' ПО 30.06.'+@YEAR_EDT
														WHEN '3' THEN 'С 01.07.'+@YEAR_EDT+' ПО 30.09.'+@YEAR_EDT
														WHEN '4' THEN 'С 01.10.'+@YEAR_EDT+' ПО 31.12.'+@YEAR_EDT
														ELSE ''
													END									
											END	+ '</Название>' WHERE @PER_EDT <> '0'
						   UNION ALL SELECT @lcFNAME, SPACE(3) + '</КорректируемыйОтчетныйПериод>' WHERE @PER_EDT <> '0'
						   UNION ALL SELECT @lcFNAME, SPACE(3) + CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013'  THEN '' ELSE '<ТипДоговора>'+@T_DOG_N+'</ТипДоговора>'  END	
						  UNION ALL SELECT @lcFNAME, SPACE(2) + CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' THEN '</ВХОДЯЩАЯ_ОПИСЬ_ПО_СТРАХОВЫМ_ВЗНОСАМ>' ELSE '</ВХОДЯЩАЯ_ОПИСЬ_ПО_СУММАМ_ВЫПЛАТ_И_ПО_СТРАХОВЫМ_ВЗНОСАМ>'  END
					  
			END
		--Экспорт СЗВ-6-4		

		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) + CASE WHEN @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' then '<СВЕДЕНИЯ_О_СТРАХОВЫХ_ВЗНОСАХ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ>' else '<СВЕДЕНИЯ_О_СУММЕ_ВЫПЛАТ_О_СТРАХОВЫХ_ВЗНОСАХ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ>'  end + CHAR(10) 
		+	SPACE(3) + '<НомерВпачке>' + RTRIM(LTRIM(STR(ID+1))) + '</НомерВпачке>' + CHAR(10)
		+ 	SPACE(3) + CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013'  then '<ВидФормы>'+@TYPDOC+'</ВидФормы>' ELSE '' END + 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) 
											WHEN @YEAR >= '2014' THEN (CASE @PER WHEN '1' THEN '3' WHEN '2' THEN '6' WHEN '3' THEN '9' ELSE '0' 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
									  WHEN @YEAR >= '2014' THEN
											CASE @PER 
												WHEN '1' THEN 'С 01.01.'+@YEAR+' ПО 31.03.'+@YEAR
												WHEN '2' THEN 'С 01.01.'+@YEAR+' ПО 30.06.'+@YEAR
												WHEN '3' THEN 'С 01.01.'+@YEAR+' ПО 30.09.'+@YEAR
												WHEN '4' THEN 'С 01.01.'+@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_EDT+' ПО 30.06.'+@YEAR_EDT
											WHEN '4' THEN 'С 01.07.'+@YEAR_EDT+' ПО 31.12.'+@YEAR_EDT
											ELSE ''
										END
									ELSE
										CASE @PER_EDT 
											WHEN '1' THEN 'С 01.01.'+@YEAR_EDT+' ПО 31.03.'+@YEAR_EDT
											WHEN '2' THEN 'С 01.04.'+@YEAR_EDT+' ПО 30.06.'+@YEAR_EDT
											WHEN '3' THEN 'С 01.07.'+@YEAR_EDT+' ПО 30.09.'+@YEAR_EDT
											WHEN '4' THEN 'С 01.10.'+@YEAR_EDT+' ПО 31.12.'+@YEAR_EDT
											ELSE ''
										END 
								END	+ '</Название>' + CHAR(10)
		+ 	SPACE(3) + '</КорректируемыйОтчетныйПериод>' + CHAR(10)								
		+ 	SPACE(3) + CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' then '' ELSE '<РегистрационныйНомерКорректируемогоПериода>'+ @PFNUMBER +'</РегистрационныйНомерКорректируемогоПериода>' END + 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 @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013'  then '' else +   SPACE(3) + '<ТипДоговора>'+@T_DOG_N+'</ТипДоговора>' + CHAR(10) end	
		+ CASE WHEN @TYPE <> 'ОТМЕНЯЮЩАЯ' THEN
		+ CASE WHEN @TYPDOC <> 'СПВ-1' THEN 
		+ CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013'  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 
				+ 	SPACE(3) + '<СуммаВыплатИвознагражденийВпользуЗЛ>' + CHAR(10)
				+ 	  SPACE(4) + '<ТипСтроки>МЕСЦ</ТипСтроки>' + CHAR(10)
				+	  SPACE(4) + '<Месяц>' + case when @PER_EDT = 0 then 
												( CASE @PER 
													WHEN '1' THEN '1'
													WHEN '2' THEN '4'
													WHEN '3' THEN '7'
													WHEN '4' THEN '10'
												   ELSE ''
												   END	)
												else (
														CASE  @PER_EDT 		
														WHEN '1' THEN '1'
														WHEN '2' THEN '4'
														WHEN '3' THEN '7'
														WHEN '4' THEN '10'
														ELSE ''
														END) 
											   end	+'</Месяц>' + CHAR(10)

				+ 	  SPACE(4) + '<СуммаВыплатВсего>'+RTRIM(LTRIM(STR(COALESCE(INC_M1,0),15,2)))+'</СуммаВыплатВсего>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносыНеПревышающие>'+RTRIM(LTRIM(STR(COALESCE(B_BEF_M1,0),15,2)))+'</СуммаВыплатНачисленыСтраховыеВзносыНеПревышающие>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносыПревышающие>'+RTRIM(LTRIM(STR(COALESCE(B_AFT_M1,0),15,2)))+'</СуммаВыплатНачисленыСтраховыеВзносыПревышающие>' + CHAR(10)
				+ 	SPACE(3) + '</СуммаВыплатИвознагражденийВпользуЗЛ>' + CHAR(10)
				+ 	SPACE(3) + '<СуммаВыплатИвознагражденийВпользуЗЛ>' + CHAR(10)
				+ 	  SPACE(4) + '<ТипСтроки>МЕСЦ</ТипСтроки>' + CHAR(10)
				+	  SPACE(4) + '<Месяц>' + case when @PER_EDT = 0 then 
												( CASE @PER 
													WHEN '1' THEN '2'
													WHEN '2' THEN '5'
													WHEN '3' THEN '8'
													WHEN '4' THEN '11'
												   ELSE ''
												   END	)
												else (
														CASE  @PER_EDT 		
														WHEN '1' THEN '2'
														WHEN '2' THEN '5'
														WHEN '3' THEN '8'
														WHEN '4' THEN '11'
														ELSE ''
														END) 
											   end	+'</Месяц>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатВсего>'+RTRIM(LTRIM(STR(COALESCE(INC_M2,0),15,2)))+'</СуммаВыплатВсего>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносыНеПревышающие>'+RTRIM(LTRIM(STR(COALESCE(B_BEF_M2,0),15,2)))+'</СуммаВыплатНачисленыСтраховыеВзносыНеПревышающие>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносыПревышающие>'+RTRIM(LTRIM(STR(COALESCE(B_AFT_M2,0),15,2)))+'</СуммаВыплатНачисленыСтраховыеВзносыПревышающие>' + CHAR(10)
				+ 	SPACE(3) + '</СуммаВыплатИвознагражденийВпользуЗЛ>' + CHAR(10)
				+ 	SPACE(3) + '<СуммаВыплатИвознагражденийВпользуЗЛ>' + CHAR(10)
				+ 	  SPACE(4) + '<ТипСтроки>МЕСЦ</ТипСтроки>' + CHAR(10)
				+	  SPACE(4) + '<Месяц>' + case when @PER_EDT = 0 then 
												( CASE @PER 
													WHEN '1' THEN '3'
													WHEN '2' THEN '6'
													WHEN '3' THEN '9'
													WHEN '4' THEN '12'
												   ELSE ''
												   END	)
												else (
														CASE  @PER_EDT 		
														WHEN '1' THEN '3'
														WHEN '2' THEN '6'
														WHEN '3' THEN '9'
														WHEN '4' THEN '12'
														ELSE ''
														END) 
											   end	+'</Месяц>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатВсего>'+RTRIM(LTRIM(STR(COALESCE(INC_M3,0),15,2)))+'</СуммаВыплатВсего>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносыНеПревышающие>'+RTRIM(LTRIM(STR(COALESCE(B_BEF_M3,0),15,2)))+'</СуммаВыплатНачисленыСтраховыеВзносыНеПревышающие>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносыПревышающие>'+RTRIM(LTRIM(STR(COALESCE(B_AFT_M3,0),15,2)))+'</СуммаВыплатНачисленыСтраховыеВзносыПревышающие>' + CHAR(10)
				+ 	SPACE(3) + '</СуммаВыплатИвознагражденийВпользуЗЛ>' + CHAR(10)
				+ 	SPACE(3) + '<СуммаВыплатИвознагражденийВпользуЗЛ>' + CHAR(10)
				+ 	  SPACE(4) + '<ТипСтроки>ИТОГ</ТипСтроки>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатВсего>'+RTRIM(LTRIM(STR((COALESCE(INC_M1,0) + COALESCE(INC_M2,0)+ COALESCE(INC_M3,0)),15,2)))+'</СуммаВыплатВсего>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносыНеПревышающие>'+RTRIM(LTRIM(STR((COALESCE(B_BEF_M1,0) + COALESCE(B_BEF_M2,0)+ COALESCE(B_BEF_M3,0)),15,2)))+'</СуммаВыплатНачисленыСтраховыеВзносыНеПревышающие>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатНачисленыСтраховыеВзносыПревышающие>'+RTRIM(LTRIM(STR((COALESCE(B_AFT_M1,0) + COALESCE(B_AFT_M2,0)+ COALESCE(B_AFT_M3,0)),15,2)))+'</СуммаВыплатНачисленыСтраховыеВзносыПревышающие>' + CHAR(10)
				+ 	SPACE(3) + '</СуммаВыплатИвознагражденийВпользуЗЛ>' + CHAR(10)								
				
				+ 	SPACE(3) + '<СуммаВыплатИвознагражденийПоДопТарифу>' + CHAR(10)
				+ 	  SPACE(4) + '<ТипСтроки>МЕСЦ</ТипСтроки>' + CHAR(10)
				+	  SPACE(4) + '<Месяц>' + case when @PER_EDT = 0 then 
												( CASE @PER 
													WHEN '1' THEN '1'
													WHEN '2' THEN '4'
													WHEN '3' THEN '7'
													WHEN '4' THEN '10'
												   ELSE ''
												   END	)
												else (
														CASE  @PER_EDT 		
														WHEN '1' THEN '1'
														WHEN '2' THEN '4'
														WHEN '3' THEN '7'
														WHEN '4' THEN '10'
														ELSE ''
														END) 
											   end	+'</Месяц>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатПоДопТарифу27-1>'+RTRIM(LTRIM(STR(COALESCE(INC_T1M1,0),15,2)))+'</СуммаВыплатПоДопТарифу27-1>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатПоДопТарифу27-2-18>'+RTRIM(LTRIM(STR(COALESCE(INC_T2M1,0),15,2)))+'</СуммаВыплатПоДопТарифу27-2-18>' + CHAR(10)
				+ 	SPACE(3) + '</СуммаВыплатИвознагражденийПоДопТарифу>' + CHAR(10)
				+ 	SPACE(3) + '<СуммаВыплатИвознагражденийПоДопТарифу>' + CHAR(10)
				+ 	  SPACE(4) + '<ТипСтроки>МЕСЦ</ТипСтроки>' + CHAR(10)
				+	  SPACE(4) + '<Месяц>' + case when @PER_EDT = 0 then 
												( CASE @PER 
													WHEN '1' THEN '2'
													WHEN '2' THEN '5'
													WHEN '3' THEN '8'
													WHEN '4' THEN '11'
												   ELSE ''
												   END	)
												else (
														CASE  @PER_EDT 		
														WHEN '1' THEN '2'
														WHEN '2' THEN '5'
														WHEN '3' THEN '8'
														WHEN '4' THEN '11'
														ELSE ''
														END) 
											   end	+'</Месяц>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатПоДопТарифу27-1>'+RTRIM(LTRIM(STR(COALESCE(INC_T1M2,0),15,2)))+'</СуммаВыплатПоДопТарифу27-1>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатПоДопТарифу27-2-18>'+RTRIM(LTRIM(STR(COALESCE(INC_T2M2,0),15,2)))+'</СуммаВыплатПоДопТарифу27-2-18>' + CHAR(10)
				+ 	SPACE(3) + '</СуммаВыплатИвознагражденийПоДопТарифу>' + CHAR(10)
				+ 	SPACE(3) + '<СуммаВыплатИвознагражденийПоДопТарифу>' + CHAR(10)
				+ 	  SPACE(4) + '<ТипСтроки>МЕСЦ</ТипСтроки>' + CHAR(10)
				+	  SPACE(4) + '<Месяц>' + case when @PER_EDT = 0 then 
												( CASE @PER 
													WHEN '1' THEN '3'
													WHEN '2' THEN '6'
													WHEN '3' THEN '9'
													WHEN '4' THEN '12'
												   ELSE ''
												   END	)
												else (
														CASE  @PER_EDT 		
														WHEN '1' THEN '3'
														WHEN '2' THEN '6'
														WHEN '3' THEN '9'
														WHEN '4' THEN '12'
														ELSE ''
														END) 
											   end	+'</Месяц>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатПоДопТарифу27-1>'+RTRIM(LTRIM(STR(COALESCE(INC_T1M3,0),15,2)))+'</СуммаВыплатПоДопТарифу27-1>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатПоДопТарифу27-2-18>'+RTRIM(LTRIM(STR(COALESCE(INC_T2M3,0),15,2)))+'</СуммаВыплатПоДопТарифу27-2-18>' + CHAR(10)
				+ 	SPACE(3) + '</СуммаВыплатИвознагражденийПоДопТарифу>' + CHAR(10)
				+ 	SPACE(3) + '<СуммаВыплатИвознагражденийПоДопТарифу>' + CHAR(10)
				+ 	  SPACE(4) + '<ТипСтроки>ИТОГ</ТипСтроки>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатПоДопТарифу27-1>'+RTRIM(LTRIM(STR((COALESCE(INC_T1M1,0) + COALESCE(INC_T1M2,0)+ COALESCE(INC_T1M3,0)),15,2)))+'</СуммаВыплатПоДопТарифу27-1>' + CHAR(10)
				+ 	  SPACE(4) + '<СуммаВыплатПоДопТарифу27-2-18>'+RTRIM(LTRIM(STR((COALESCE(INC_T2M1,0) + COALESCE(INC_T2M2,0)+ COALESCE(INC_T2M3,0)),15,2)))+'</СуммаВыплатПоДопТарифу27-2-18>' + CHAR(10)
				+ 	SPACE(3) + '</СуммаВыплатИвознагражденийПоДопТарифу>' + CHAR(10)				
				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)
				
			ELSE ''
			END	
		ELSE ''
		END
		+ CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' then	SPACE(3) + '<ДатаЗаполнения>' + @DATE_DOC + '</ДатаЗаполнения>' + CHAR(10) ELSE ''  END	
		+ CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013'  then + CASE WHEN @TYPDOC = 'СПВ-1' THEN	SPACE(3) + '<ДатаСоставленияНа>' + @DATE_DOC + '</ДатаСоставленияНа>' + CHAR(10)  ELSE ''  END ELSE '' END

		,
		--В этом промежутке блоки со стажем
		---------------------------------------------------
		 CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013'  then '' else 	SPACE(3) + '<ДатаЗаполнения>' + @DATE_DOC + '</ДатаЗаполнения>' + CHAR(10) end
		+ CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013'  then + CASE WHEN @TYPDOC = 'СПВ-1' THEN	SPACE(3) + '<ДатаСоставленияНа>' + @DATE_DOC + '</ДатаСоставленияНа>' + CHAR(10)  ELSE ''  END ELSE '' END

		+ CASE WHEN   @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013'  then SPACE(1) + '</СВЕДЕНИЯ_О_СТРАХОВЫХ_ВЗНОСАХ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ>' else  SPACE(1) + '</СВЕДЕНИЯ_О_СУММЕ_ВЫПЛАТ_О_СТРАХОВЫХ_ВЗНОСАХ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ>' END
		from #PERS_INFO where LINK_PU = @LINK_PU  and T_DOG = @T_DOG and 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 LINK_PU = @LINK_PU  and T_DOG = @T_DOG and NGROUP = @NGROUP and ID_EX >= 1 and DATE_BEGIN is not null) --AND @SZV = 1 AND @TYPDOC = 'СПВ-1'
					BEGIN
						INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
						Select @lcFNAME,
						CASE WHEN @TYPE <> 'ОТМЕНЯЮЩАЯ' THEN	
						/*CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' 	THEN	''
						ELSE*/	

							+	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(ter_usl,''))) not in ('Ч31','Ч33','Ч34','Ч35','Ч36') then
													(CASE WHEN RTRIM(LTRIM(COALESCE(STR(ter_koef,4,2),''))) <> '0.00' then SPACE(8) + '<Коэффициент>' + RTRIM(LTRIM(COALESCE(STR(ter_koef,4,2),''))) + '</Коэффициент>' + CHAR(10) else '' end)
													else '' end
							+ 					SPACE(7) + '</ТерриториальныеУсловия>' + CHAR(10)
												ELSE '' END
							+ 					CASE WHEN RTRIM(LTRIM(COALESCE(osob_usl,''))) <> '' THEN
												SPACE(7) + '<ОсобыеУсловияТруда>' + CHAR(10)
							+						SPACE(8) + '<ОснованиеОУТ>' + RTRIM(LTRIM(COALESCE(osob_usl,''))) + '</ОснованиеОУТ>' + CHAR(10)
							+						SPACE(8) + '<ПозицияСписка>' + UPPER(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(is_dop,''))) <> '' and RTRIM(LTRIM(COALESCE(is_dop,''))) <> 'НЕОПЛ'  THEN
								+ 					(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE,''))) <> '' THEN
													SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
								+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE,''))) + '</ОснованиеВЛ>' + CHAR(10)
								+						CASE WHEN COALESCE(f_ud_dop,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop,'') LIKE '%МИН.%' THEN
														SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
								+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_m,0),3))) + '</Часы>' + CHAR(10)
								+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_d,0),3))) + '</Минуты>' + CHAR(10)
								+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
														ELSE '' END
								+						CASE WHEN COALESCE(f_ud_dop,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop,'') LIKE '%ДН.%' THEN
														SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
								+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
								+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_m,0),3))) + '</ВсеМесяцы>' + CHAR(10)
								+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_d,0),3))) + '</ВсеДни>' + CHAR(10)
								+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
														ELSE '' END
								+						CASE WHEN COALESCE(ud_dop_k,0) <> 0 THEN
															SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_k,0),4,2))) + '</ДоляСтавки>' + CHAR(10)
														ELSE '' END
								+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
													ELSE '' END)
													WHEN RTRIM(LTRIM(COALESCE(is_dop,''))) = '' THEN
													(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE,''))) <> '' THEN
													SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
								+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE,''))) + '</ОснованиеВЛ>' + CHAR(10)
								+						CASE WHEN COALESCE(f_ud_dop,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop,'') LIKE '%МИН.%' THEN
														SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
								+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_m,0),3))) + '</Часы>' + CHAR(10)
								+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_d,0),3))) + '</Минуты>' + CHAR(10)
								+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
														ELSE '' END
								+						CASE WHEN COALESCE(f_ud_dop,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop,'') LIKE '%ДН.%' THEN
														SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
								+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
								+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_m,0),3))) + '</ВсеМесяцы>' + CHAR(10)
								+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_d,0),3))) + '</ВсеДни>' + CHAR(10)
								+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
														ELSE '' END
								+						CASE WHEN COALESCE(ud_dop_k,0) <> 0 THEN
															SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_k,0),4,2))) + '</ДоляСтавки>' + CHAR(10)
														ELSE '' END
								+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
													ELSE '' END)
												ELSE '' END
							+			SPACE(5) + '</ОсобенностиУчета>' + CHAR(10)
							+		SPACE(4) + '</ЛьготныйСтаж>' + CHAR(10)
										ELSE '' END
							+	SPACE(3) + '</СтажевыйПериод>'
						
						/*END*/
						ELSE '' END
						from #PERS_INFO where LINK_PU = @LINK_PU and NGROUP = @NGROUP AND [ID] = @PERS_ID  and T_DOG = @T_DOG 
						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  @LINK_PU,@NGROUP, @lcFNAME, @INN, @KPP, @DEP_NAME, @PFNUMBER, @PACHNUM, @DOCCOUNT, @TYPDOC, @PERSCNT, @DATE_CRT, @DATE_DOC, @YEAR,
	@SZV, @TYP_SVED, @VID_KOR, @INC_M1 ,@INC_M2,@INC_M3,@B_BEF_M1,@B_BEF_M2,@B_BEF_M3,	@B_AFT_M1,@B_AFT_M2,@B_AFT_M3,
	@INSUR, @INSUR1, @GAIN, @GAIN1,@sd_str,@sud_str,@sd_nak,@sud_nak, @PER, @TYPE, @PER_EDT, @YEAR_EDT, @PER_EDT_NAME, @TYPE, @KATEG, @PER_NAME,@T_DOG,@T_DOG_N 
END

CLOSE @Cur1
DEALLOCATE @Cur1


/*для выгрузки из перс учета , выгрузка ОПИСИ Адв62 с 2014 закрыта */
/*
CREATE TABLE #ADV62A (
	LINK_PU INT,
	[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
)

CREATE TABLE #ADV62B1 (
	LINK_PU INT,
	[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 
)

CREATE TABLE #ADV62C1 (
	LINK_PU INT,
	[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),
	sd_str numeric(18,2),
	sud_str numeric(18,2),
	sd_nak numeric(18,2),
	sud_nak numeric(18,2),
	[PERS_CNT] INT,
	[FNAME] VARCHAR(256),
	[IT_ROUND] TINYINT 
)

--select * from #DOC

DECLARE @CURS2 CURSOR, @link_DOC2 int, @link_DOC2_old int , @NG1 int, @NGPP int, @Typ1 int , @cGRP2 varchar (5)

SET @NGPP = 1
set @NG1 = 0 
set @Typ1 = 0
set @cGRP2 = ''
set @LINK_DOC2_OLD = 0 
SET @CURS2 = CURSOR FORWARD_ONLY

FOR SELECT LINK FROM #DOC order by link 


OPEN @CURS2
FETCH NEXT FROM @CURS2 INTO @LINK_DOC2

WHILE @@FETCH_STATUS = 0	

BEGIN
		if @link_doc2_old = 0
		begin
			set @link_doc2_old = @LINK_DOC2 
		end
		INSERT INTO #ADV62A ([YEAR],[PER],[PER10],[COUNT_P],[COUNT_PK],[PFNUMBER],[DEP_NAME],[OKPO],[INN],[KPP],DATE_CRT,DATE_DOC)
		exec dbo.SZV4_PRINT_ADV62 @LINK_DOC2, 1
		UPDATE #ADV62A SET link_pu = @LINK_DOC2 FROM #ADV62A WHERE LINK_PU IS NULL 
		
		INSERT INTO #ADV62B1 ([NGROUP],[cGRP],[CODE],[INSUR],[INSUR1],[GAIN],[GAIN1],[PERS_CNT],[FNAME],[IT_ROUND])
		exec dbo.SZV4_PRINT_ADV62 @LINK_DOC2, 2
		UPDATE #ADV62B1 SET link_pu = @LINK_DOC2 FROM #ADV62B1 WHERE LINK_PU IS NULL 
				--*-* Проставляем номер в пачке
		if @link_doc2_old <> @LINK_DOC2
		begin
			UPDATE #ADV62B1 SET NGROUP = NGROUP + 1  FROM #ADV62B1 WHERE LINK_PU = @LINK_DOC2 and NGROUP is not null
			UPDATE #ADV62B1 SET cGRP = REPLACE(str((cGRP + 1),5),' ','0')  FROM #ADV62B1 WHERE LINK_PU = @LINK_DOC2 and NGROUP is not null
		end
		update #ADV62B1 SET  [FNAME]  = STUFF ( FNAME , 39, 5 ,cGRP) where  LINK_PU = @LINK_DOC2 and NGROUP is not null
		
		INSERT INTO #ADV62C1 ([NGROUP],[cGRP],[CODE],[INSUR],[INSUR1],[GAIN],[GAIN1],[sd_str],[sud_str],[sd_nak],[sud_nak],[PERS_CNT],[FNAME],[IT_ROUND])
		exec dbo.SZV4_PRINT_ADV62 @LINK_DOC2, 3
		UPDATE #ADV62C1 SET link_pu = @LINK_DOC2 FROM #ADV62C1 WHERE LINK_PU IS NULL 

		--*-* Проставляем номер в пачке
		if @link_doc2_old <> @LINK_DOC2
		begin
			set @NG1 = (select max([NGROUP]) from #ADV62B1  where  [NGROUP] is not null)
			set @cGRP2 = (select max([cGRP]) from #ADV62B1  where  [cGRP] is not null)
			
			UPDATE #ADV62C1 SET NGROUP = @NG1 + @NGPP  FROM #ADV62C1 WHERE LINK_PU = @LINK_DOC2 and NGROUP is not null
			UPDATE #ADV62C1 SET cGRP = REPLACE(str((@cGRP2 + @NGPP),5),' ','0')  FROM #ADV62C1 WHERE LINK_PU = @LINK_DOC2 and [cGRP] is not null
			set @NGPP = @NGPP +1
			set @cGRP2 = @cGRP2 +1
		
		end
		update #ADV62C1 SET  [FNAME]  = STUFF ( FNAME , 39, 5 ,cGRP) where  LINK_PU = @LINK_DOC2 and NGROUP is not null
		
		
		set @link_doc2_old = @link_doc2

	FETCH NEXT FROM @CURS2 INTO @LINK_DOC2
END

CLOSE @CURS2
DEALLOCATE @CURS2	



SELECT * INTO #ADV62B FROM #ADV62B1 ORDER BY link_PU, [CODE],  [NGROUP]
SELECT @NN = 0, @PN = 0, @ON = 0
UPDATE A
SET 
	@NN = @NN + 1,
	ID = @NN
FROM #ADV62B A


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)

DECLARE @COUNT_P VARCHAR(10), @COUNT_PK VARCHAR(10)


IF COALESCE(dbo.sa_get_option_by_code('SA_SZV4_OPT3'),0) = 1
	Set @NGROUP = COALESCE((Select MIN(NGROUP) from #ADV65),2) - 1
ELSE
	Set @NGROUP = COALESCE(@NGROUP,0) + 1


SELECT TOP 1  
	@lcFNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),CASE WHEN [YEAR] = 0 THEN 2010 ELSE [YEAR] END) + '-ORG-' + RTRIM(LTRIM(COALESCE(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),sum(COUNT_P)))),
	@COUNT_PK = RTRIM(LTRIM(CONVERT(VARCHAR(10),sum(COUNT_PK)))),
	@DATE_DOC = CONVERT(VARCHAR(10),max(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 group by PFNUMBER, [PER], PER10,[YEAR],INN,KPP,DEP_NAME


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 = 1

DECLARE @CurI CURSOR, @KATEG_CODE VARCHAR(20) , @NGR INT 
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 --+@ITER 

		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
		SET @NEXT_NUM = @NEXT_NUM  + 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 
	
	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 NGROUP,  CODE from #ADV62C order by CODE 

OPEN @CurI
FETCH NEXT FROM @CurI INTO @NGR , @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(@ITER,0),2))) + '</ПорядковыйНомер>' + CHAR(10)
		+	SPACE(4) + '<ТипСтрокиОсведениях>ПО ПАЧКЕ</ТипСтрокиОсведениях>' + CHAR(10)
		+	SPACE(4) + '<КодКатегории>' + RTRIM(LTRIM(CODE)) + '</КодКатегории>' + CHAR(10)

		+ 	SPACE(4) + '<ДоначисленоНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE([sd_str],0),15,2))) + '</ДоначисленоНаСтраховую>' + CHAR(10)
		+ 	SPACE(4) + '<ДоначисленоНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE([sd_nak],0),15,2))) + '</ДоначисленоНаНакопительную>' + CHAR(10)

		+ 	SPACE(4) + '<ДоуплаченоНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE([sud_str],0),15,2))) + '</ДоуплаченоНаСтраховую>' + CHAR(10)
		+ 	SPACE(4) + '<ДоуплаченоНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE([sud_nak],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 and  NGROUP = @NGR  ORDER BY ID
		SET @NEXT_NUM = @NEXT_NUM  +1
		
		SET @ITER = @ITER + 1		
	END

	FETCH NEXT FROM @CurI INTO  @NGR, @KATEG_CODE
END

CLOSE @CurI
DEALLOCATE @CurI		


SET @CurI = CURSOR FORWARD_ONLY

FOR select DISTINCT   CODE from #ADV62C where LTRIM(rtrim(CODE))<>'' 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(@NEXT_NUM))) + '</ПорядковыйНомер>' + CHAR(10)
		+	SPACE(4) + '<ТипСтрокиОсведениях>ПО КАТЕГОРИИ</ТипСтрокиОсведениях>' + CHAR(10)
		+	SPACE(4) + '<КодКатегории>' + RTRIM(LTRIM(CODE)) + '</КодКатегории>' + CHAR(10)

		+ 	SPACE(4) + '<ДоначисленоНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(SUM([sd_str]),0),15,2))) + '</ДоначисленоНаСтраховую>' + CHAR(10)
		+ 	SPACE(4) + '<ДоначисленоНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(SUM([sd_nak]),0),15,2))) + '</ДоначисленоНаНакопительную>' + CHAR(10)


		+ 	SPACE(4) + '<ДоуплаченоНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(SUM([sud_str]),0),15,2))) + '</ДоуплаченоНаСтраховую>' + CHAR(10)
		+ 	SPACE(4) + '<ДоуплаченоНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(SUM([sud_nak]),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   /*and LINK_PU = @LINK_DOC3*/ GROUP BY [CODE]
		
				

	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([sd_str]),0),15,2))) + '</ДоначисленоНаСтраховую>' + CHAR(10)
	+ 	SPACE(4) + '<ДоначисленоНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(SUM([sd_nak]),0),15,2))) + '</ДоначисленоНаНакопительную>' + CHAR(10)

	+ 	SPACE(4) + '<ДоуплаченоНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(SUM([sud_str]),0),15,2))) + '</ДоуплаченоНаСтраховую>' + CHAR(10)
	+ 	SPACE(4) + '<ДоуплаченоНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(SUM([sud_nak]),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_13] 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'		
	begin	
		UPDATE T1 SET USED = @iSET_VALUE
		FROM dbo.BufferGetTableByID (@strBUFFER_NAME) BUF
		INNER JOIN dbo.KL_KBK T1 ON (T1.LINK = BUF.LINK)
		if @iSET_VALUE = 1
				delete from dbo.DEPARTMENT_KBK where exists(select * from dbo.BufferGetTableByID (@strBUFFER_NAME) where LINK = KBK_LINK) 
	end
		
	--- НОМЕНКЛАТУРА ---
	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 @strTABLE_NAME = 'SAL_SFIN'		
		UPDATE T1 SET USED = @iSET_VALUE
		FROM dbo.BufferGetTableByID (@strBUFFER_NAME) BUF
		INNER JOIN dbo.SAL_SFIN 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_NULLS ON 
GO

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




CREATE                PROCEDURE dbo.FB_PRINT_KP_VYLUCH
	@dDateB		datetime,
	@dDateE		datetime,	
	@cBuffId	varchar(20),
	@iPlanType 	tinyint = 1,
	@iDopEkr 	tinyint = 1,
	@iSummaType	float = 1,
	@iZB		tinyint = 0,
	@iPlanFin	tinyint = 0
	
	

AS
DECLARE @tTemp TABLE( 
	KBK 	INT,
	EKR 	INT, 
	DOP_CL 	INT, 
	M1	[numeric](28, 2) NULL,
	M2	[numeric](28, 2) NULL,
	M3	[numeric](28, 2) NULL,
	M4	[numeric](28, 2) NULL,
	M5	[numeric](28, 2) NULL,
	M6	[numeric](28, 2) NULL,
	M7	[numeric](28, 2) NULL,
	M8	[numeric](28, 2) NULL,
	M9	[numeric](28, 2) NULL,
	M10	[numeric](28, 2) NULL,
	M11	[numeric](28, 2) NULL,
	M12	[numeric](28, 2) NULL)

DECLARE @tTempGroup TABLE( 
	KBK 	INT,
	EKR 	INT, 
	DOP_CL 	INT,
	M1	[numeric](28, 2) NULL,
	M2	[numeric](28, 2) NULL,
	M3	[numeric](28, 2) NULL,
	M4	[numeric](28, 2) NULL,
	M5	[numeric](28, 2) NULL,
	M6	[numeric](28, 2) NULL,
	M7	[numeric](28, 2) NULL,
	M8	[numeric](28, 2) NULL,
	M9	[numeric](28, 2) NULL,
	M10	[numeric](28, 2) NULL,
	M11	[numeric](28, 2) NULL,
	M12	[numeric](28, 2) NULL,
	ORDERS	int identity,
	DOP_EKR	INT)

DECLARE @tTempDopEkr TABLE( 
	KBK 	INT,
	EKR 	INT, 
	DOP_CL 	INT,
	M1	[numeric](28, 2) NULL,
	M2	[numeric](28, 2) NULL,
	M3	[numeric](28, 2) NULL,
	M4	[numeric](28, 2) NULL,
	M5	[numeric](28, 2) NULL,
	M6	[numeric](28, 2) NULL,
	M7	[numeric](28, 2) NULL,
	M8	[numeric](28, 2) NULL,
	M9	[numeric](28, 2) NULL,
	M10	[numeric](28, 2) NULL,
	M11	[numeric](28, 2) NULL,
	M12	[numeric](28, 2) NULL,
	ORDERS	int,
	DOP_EKR	INT)

DECLARE @tTempDopEkr2 TABLE( 
	KBK 	INT,
	EKR 	INT, 
	DOP_CL 	INT,
	M1	[numeric](28, 2) NULL,
	M2	[numeric](28, 2) NULL,
	M3	[numeric](28, 2) NULL,
	M4	[numeric](28, 2) NULL,
	M5	[numeric](28, 2) NULL,
	M6	[numeric](28, 2) NULL,
	M7	[numeric](28, 2) NULL,
	M8	[numeric](28, 2) NULL,
	M9	[numeric](28, 2) NULL,
	M10	[numeric](28, 2) NULL,
	M11	[numeric](28, 2) NULL,
	M12	[numeric](28, 2) NULL,
	ORDERS	int,
	DOP_EKR	INT)

declare @iDepLink int,
	@MaxOrdersLen int,
	@iPeriodNum tinyint,
	@iMonth int

set @iDepLink = isnull(dbo.BK_GetDepZB(),dbo.GetOwnDepLink())
set @iSummaType = case @iSummaType when 0 then 1 else 0.001 end 
set @iMonth = Month(@dDateE)

if @dDateB is null and @dDateE is not null
	SET @dDateB = @dDateE

if @dDateE is null and @dDateB is not null
	SET @dDateE = @dDateB
 
if @iPlanFin = 0
begin
	if isnull(@cBuffId,'') = ''
	begin
		set @cBuffId = 'KP'
		exec dbo.BufferClear @cBuffId 
		if @iPlanType = 0
			insert into dbo.BUFFER(ID,LINK)
			select @cBuffId, LINK
			from dbo.FB_PLAN
			where DATE between @dDateB and @dDateE
				and (@iZB = 0 and @iDepLink = DEP_LINK or @iZB = 1)
		
		else
			insert into dbo.BUFFER(ID,LINK)
			select @cBuffId, LINK
			from dbo.FB_PLAN_D
			where DATE between @dDateB and @dDateE
				and (@iZB = 0 and @iDepLink = DEP_LINK or @iZB = 1)
	end
	if @iPlanType = 1
		select @iPeriodNum = PERIOD from dbo.FB_PLAN_D_OPTIONS
	else
		select @iPeriodNum = PERIOD from dbo.FB_PLAN_OPTIONS

--select @iSummaType
	insert into @tTemp
	SELECT  VKR, EKR, DOP_CL,
		M1 = case @iPeriodNum when 1 then case Month(G.DATE_PROV) when 1 then sum(F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12) * @iSummaType else 0 end 
								when 2 then case Month(G.DATE_PROV) when 1 then sum(F.P1 + F.P2 + F.P3) * @iSummaType else 0 end  
								when 3 then sum(F.P1) * @iSummaType else 0 end,
		M2 = case @iPeriodNum when 1 then case Month(G.DATE_PROV) when 2 then sum(F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12) * @iSummaType else 0 end 
								when 2 then case Month(G.DATE_PROV) when 2 then sum(F.P1 + F.P2 + F.P3) * @iSummaType else 0 end  
								when 3 then sum(F.P2) * @iSummaType else 0 end,
		M3 = case @iPeriodNum when 1 then case Month(G.DATE_PROV) when 3 then sum(F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12) * @iSummaType else 0 end 
								when 2 then case Month(G.DATE_PROV) when 3 then sum(F.P1 + F.P2 + F.P3) * @iSummaType else 0 end  
								when 3 then sum(F.P3) * @iSummaType else 0 end,
		M4 = case @iPeriodNum when 1 then case when Month(G.DATE_PROV) < 5 then sum(F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12) * @iSummaType else 0 end 
								when 2 then case Month(G.DATE_PROV) when 4 then sum(F.P4 + F.P5 + F.P6) * @iSummaType else 0 end  
								when 3 then sum(F.P4) * @iSummaType else 0 end,
		M5 = case @iPeriodNum when 1 then case Month(G.DATE_PROV) when 5 then sum(F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12) * @iSummaType else 0 end 
								when 2 then case Month(G.DATE_PROV) when 5 then sum(F.P4 + F.P5 + F.P6) * @iSummaType else 0 end  
								when 3 then sum(F.P5) * @iSummaType else 0 end,
		M6 = case @iPeriodNum when 1 then case Month(G.DATE_PROV) when 6 then sum(F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12) * @iSummaType else 0 end 
								when 2 then case Month(G.DATE_PROV) when 6 then sum(F.P4 + F.P5 + F.P6) * @iSummaType else 0 end  
								when 3 then sum(F.P6) * @iSummaType else 0 end,
		M7 = case @iPeriodNum when 1 then case Month(G.DATE_PROV) when 7 then sum(F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12) * @iSummaType else 0 end 
								when 2 then case Month(G.DATE_PROV) when 7 then sum(F.P7 + F.P8 + F.P9) * @iSummaType else 0 end  
								when 3 then sum(F.P7) * @iSummaType else 0 end,
		M8 = case @iPeriodNum when 1 then case Month(G.DATE_PROV) when 8 then sum(F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12) * @iSummaType else 0 end 
								when 2 then  case when Month(G.DATE_PROV) < 9 then sum(F.P7 + F.P8 + F.P9) * @iSummaType else 0 end  
								when 3 then sum(F.P8) * @iSummaType else 0 end,
		M9 = case @iPeriodNum when 1 then case Month(G.DATE_PROV) when 9 then sum(F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12) * @iSummaType else 0 end 
								when 2 then case Month(G.DATE_PROV) when 9 then sum(F.P7 + F.P8 + F.P9) * @iSummaType else 0 end  
								when 3 then sum(F.P9) * @iSummaType else 0 end,
		M10 = case @iPeriodNum when 1 then case Month(G.DATE_PROV) when 10 then sum(F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12) * @iSummaType else 0 end 
								when 2 then case when Month(G.DATE_PROV) < 11 then sum(F.P10 + F.P11 + F.P12) * @iSummaType else 0 end  
								when 3 then sum(F.P10) * @iSummaType else 0 end,
		M11 = case @iPeriodNum when 1 then case Month(G.DATE_PROV) when 11 then sum(F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12) * @iSummaType else 0 end 
								when 2 then case Month(G.DATE_PROV) when 11 then sum(F.P10 + F.P11 + F.P12) * @iSummaType else 0 end  
								when 3 then sum(F.P11) * @iSummaType else 0 end,
		M12 = case @iPeriodNum when 1 then case Month(G.DATE_PROV) when 12 then sum(F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12) * @iSummaType else 0 end 
								when 2 then case Month(G.DATE_PROV) when 12 then sum(F.P10 + F.P11 + F.P12) * @iSummaType else 0 end  
								when 3 then sum(F.P12) * @iSummaType else 0 end

	from dbo.FINANSE F
	inner join dbo.G_PROV G on G.LINK = F.LINK_UP and G.LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	GROUP BY VKR, EKR, DOP_CL,Month(G.DATE_PROV)
end
else
	insert into @tTemp
	SELECT  VKR, EKR, DOP_CL,
		M1 =  (case when Month(G.DATE_PROV) = 1 and @iMonth = 1 and SO.CODE = 'FB_PLAN' then F.P1 
					when Month(G.DATE_PROV) = 1 and @iMonth > 1 and SO.CODE = 'FB_RESULT_FINANS' then F.P1 
					else 0 end) * @iSummaType,
		M2 = (case  when Month(G.DATE_PROV) < 3 and @iMonth = 2 and SO.CODE = 'FB_PLAN' then F.P1 + F.P2 
					when Month(G.DATE_PROV) = 2 and @iMonth > 2 and SO.CODE = 'FB_RESULT_FINANS' then F.P1 
					when Month(G.DATE_PROV) < 2 and @iMonth = 2 and SO.CODE = 'FB_RESULT_FINANS' then - F.P1 
					else 0 end) * @iSummaType,
		M3 = (case  when Month(G.DATE_PROV) < 4 and @iMonth = 3 and SO.CODE = 'FB_PLAN' then F.P1 + F.P2 + F.P3 
					when Month(G.DATE_PROV) = 3 and @iMonth > 3 and SO.CODE = 'FB_RESULT_FINANS' then F.P1 
					when Month(G.DATE_PROV) < 3 and @iMonth = 3 and SO.CODE = 'FB_RESULT_FINANS' then - F.P1 
					else 0 end) * @iSummaType,
		M4 = (case  when Month(G.DATE_PROV) < 5 and @iMonth = 4 and SO.CODE = 'FB_PLAN' then F.P1 + F.P2 + F.P3 + F.P4  
					when Month(G.DATE_PROV) = 4 and @iMonth > 4 and SO.CODE = 'FB_RESULT_FINANS' then F.P1 
					when Month(G.DATE_PROV) < 4 and @iMonth = 4 and SO.CODE = 'FB_RESULT_FINANS' then - F.P1 
					else 0 end) * @iSummaType,
		M5 = (case  when Month(G.DATE_PROV) < 6 and @iMonth = 5 and SO.CODE = 'FB_PLAN' then F.P1 + F.P2 + F.P3 + F.P4 + F.P5 
					when Month(G.DATE_PROV) = 5 and @iMonth > 5 and SO.CODE = 'FB_RESULT_FINANS' then F.P1 
					when Month(G.DATE_PROV) < 5 and @iMonth = 5 and SO.CODE = 'FB_RESULT_FINANS' then - F.P1 
					else 0 end) * @iSummaType,
		M6 = (case  when Month(G.DATE_PROV) < 7 and @iMonth = 6 and SO.CODE = 'FB_PLAN' then F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6
					when Month(G.DATE_PROV) = 6 and @iMonth > 6 and SO.CODE = 'FB_RESULT_FINANS' then F.P1 
					when Month(G.DATE_PROV) < 6 and @iMonth = 6 and SO.CODE = 'FB_RESULT_FINANS' then - F.P1 
					else 0 end) * @iSummaType,
		M7 = (case  when Month(G.DATE_PROV) < 8 and @iMonth = 7 and SO.CODE = 'FB_PLAN' then F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 
					when Month(G.DATE_PROV) = 7 and @iMonth > 7 and SO.CODE = 'FB_RESULT_FINANS' then F.P1 
					when Month(G.DATE_PROV) < 7 and @iMonth = 7 and SO.CODE = 'FB_RESULT_FINANS' then - F.P1 
					else 0 end) * @iSummaType,
		M8 = (case  when Month(G.DATE_PROV) < 9 and @iMonth = 8 and SO.CODE = 'FB_PLAN' then F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8
					when Month(G.DATE_PROV) = 8 and @iMonth > 8 and SO.CODE = 'FB_RESULT_FINANS' then F.P1 
					when Month(G.DATE_PROV) < 8 and @iMonth = 8 and SO.CODE = 'FB_RESULT_FINANS' then - F.P1 
					else 0 end) * @iSummaType,
		M9 = (case  when Month(G.DATE_PROV) < 10 and @iMonth = 9 and SO.CODE = 'FB_PLAN' then F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9
					when Month(G.DATE_PROV) = 9 and @iMonth > 9 and SO.CODE = 'FB_RESULT_FINANS' then F.P1 
					when Month(G.DATE_PROV) < 9 and @iMonth = 9 and SO.CODE = 'FB_RESULT_FINANS' then - F.P1 
					else 0 end) * @iSummaType,
		M10 = (case when Month(G.DATE_PROV) < 11 and @iMonth = 10 and SO.CODE = 'FB_PLAN' then F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10
					when Month(G.DATE_PROV) = 10 and @iMonth > 10 and SO.CODE = 'FB_RESULT_FINANS' then F.P1 
					when Month(G.DATE_PROV) < 10 and @iMonth = 10 and SO.CODE = 'FB_RESULT_FINANS' then - F.P1 
					else 0 end) * @iSummaType,
		M11 = (case when Month(G.DATE_PROV) < 12 and @iMonth = 11 and SO.CODE = 'FB_PLAN' then F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11
					when Month(G.DATE_PROV) = 11 and @iMonth > 11 and SO.CODE = 'FB_RESULT_FINANS' then F.P1 
					when Month(G.DATE_PROV) < 11 and @iMonth = 11 and SO.CODE = 'FB_RESULT_FINANS' then - F.P1 
					else 0 end) * @iSummaType,
		M12 = (case when @iMonth = 12 and SO.CODE = 'FB_PLAN' then F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12
					when Month(G.DATE_PROV) < 12 and @iMonth = 12 and SO.CODE = 'FB_RESULT_FINANS' then - F.P1 
					else 0 end) * @iSummaType
		
	from dbo.FINANSE F
	inner join dbo.G_PROV G on G.LINK = F.LINK_UP 
	inner join dbo.S_OBJECTS SO on SO.LINK = G.[OBJECT] 
	where (@iZB = 1 or @iZB = 0 and G.DEP = @iDepLink)
			and year(G.[DATE_PROV]) =  year(@dDateE)
			and G.DATE_PROV is not null
			and G.DATE_PROV <= @dDateE 
			and (SO.CODE = 'FB_PLAN' or SO.CODE = 'FB_RESULT_FINANS' and Month(G.DATE_PROV) < @iMonth)
--	where exists(select LINK from dbo.BufferGetTableByID(@cBuffId) B where B.link = G.LINK)


INSERT INTO @tTempGroup (KBK, EKR, DOP_CL, M1, M2, M3, M4, M5, M6, M7, M8, M9, M10, M11, M12, DOP_EKR)
SELECT  KBK, EKR, DOP_CL, sum(M1), sum(M2) , sum(M3), sum(M4), sum(M5), sum(M6), sum(M7), sum(M8), sum(M9), sum(M10), sum(M11), sum(M12),0
FROM @tTemp 
GROUP BY KBK, EKR, DOP_CL
having sum(M1) <> 0 or sum(M2) <> 0 or sum(M3) <> 0 or sum(M4) <> 0 or sum(M5) <> 0 or sum(M6) <> 0 or sum(M7) <> 0 or sum(M8) <> 0 or sum(M9) <> 0 or sum(M10) <> 0 or sum(M11) <> 0 or sum(M12) <> 0

INSERT INTO @tTempGroup (KBK, EKR, DOP_CL, M1, M2, M3, M4, M5, M6, M7, M8, M9, M10, M11, M12, DOP_EKR)
SELECT  KBK, EKR, NULL, sum(M1), sum(M2) , sum(M3), sum(M4), sum(M5), sum(M6), sum(M7), sum(M8), sum(M9), sum(M10), sum(M11), sum(M12), 1
FROM @tTempGroup  
WHERE @iDopEkr = 1
GROUP BY KBK, EKR
having count(*) > 1 
		and (sum(M1) <> 0 or sum(M2) <> 0 or sum(M3) <> 0 or sum(M4) <> 0 or sum(M5) <> 0 or sum(M6) <> 0 or sum(M7) <> 0 or sum(M8) <> 0 or sum(M9) <> 0 or sum(M10) <> 0 or sum(M11) <> 0 or sum(M12) <> 0)


--select * from @tTemp where EKR = 17 and kbk = 1234
--select * from @tTempGroup where EKR = 17 and kbk = 1234

INSERT INTO @tTempDopEkr
SELECT * FROM @tTempGroup UNION 
SELECT F1.KBK, EKR2.LINK, NULL, sum(M1), sum(M2) , sum(M3), sum(M4), sum(M5), sum(M6), sum(M7), sum(M8), sum(M9), sum(M10), sum(M11), sum(M12),0,1
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)
WHERE @iDopEkr = 1 and F1.DOP_EKR = 0
GROUP BY F1.KBK, EKR2.LINK 

INSERT INTO @tTempDopEkr2
SELECT F.* 
FROM @tTempDopEkr F
UNION 
SELECT F2.KBK, EKR4.LINK, null as dop_kl,sum(M1), sum(M2) , sum(M3), sum(M4), sum(M5), sum(M6), sum(M7), sum(M8), sum(M9), sum(M10), sum(M11), sum(M12),0,1
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)
WHERE @iDopEkr = 1   
GROUP BY F2.KBK,EKR4.LINK


select @MaxOrdersLen = len(ltrim(cast(MAX(ORDERS) as char(4))))
from @tTempGroup

Select F.KBK,
	F.M1, F.M2, F.M3, F.M4, F.M5, F.M6, F.M7, F.M8, F.M9, F.M10, F.M11, F.M12, 
	MI1, MI2, MI3, MI4, MI5, MI6, MI7, MI8, MI9, MI10, MI11, MI12, 
	I1, I2, I3, I4, I5, I6, I7, I8, I9, I10, I11, I12, 
	[KBK_CODE] = KBK.CODE,
	[KBK_NAME] = KBK.NAME,
	[EKR_CODE] = EKR.CODE,
	[EKR_NAME] = (case when F.DOP_CL is null then EKR.NAME 
			when @iDopEkr = 0 and F.DOP_CL is not null then rtrim(EKR.NAME) + ' ' + DCL.NAME 
				else DCL.NAME end), --EKR.NAME
	[DOP_CODE] = DCL.CODE,
	ORDERS = case F.ORDERS when 0 then '' else right('000000' + ltrim(cast(ORDERS as char(5))),@MaxOrdersLen) end,right('000000' + ltrim(cast(ORDERS as char(5))),@MaxOrdersLen)
	From @tTempDopEkr2 F  
	LEFT OUTER JOIN dbo.KL_KBK KBK ON KBK.LINK = F.KBK
	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 KBK, MI1 = sum(M1), MI2 = sum(M2) , MI3 = sum(M3), 
				MI4 = sum(M4), MI5 = sum(M5), MI6 = sum(M6), 
				MI7 = sum(M7), MI8 = sum(M8), MI9 = sum(M9), 
				MI10 = sum(M10), MI11 = sum(M11), MI12 = sum(M12)
		FROM @tTempDopEkr2
		where (0 = DOP_EKR)
		group by KBK) IT ON IT.KBK = F.KBK
	left JOIN (SELECT I1 = sum(M1), I2 = sum(M2) , I3 = sum(M3), 
			I4 = sum(M4), I5 = sum(M5), I6 = sum(M6), 
			I7 = sum(M7), I8 = sum(M8), I9 = sum(M9), 
			I10 = sum(M10), I11 = sum(M11), I12 = sum(M12)
		FROM @tTempDopEkr2
		where (0 = DOP_EKR)) I ON 1=1
	ORDER BY ORDERS --KBK.CODE,EKR.CODE, DCL.CODE 

exec dbo.BufferClear @cBuffId 
RETURN 1





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant all on dbo.FB_PRINT_KP_VYLUCH to public
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SZVK_PRINT]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SZVK_PRINT]

GO


---EXECUTE KIR_EXEC_QUERY 44922,'1,46809'
--0	93212	3


CREATE  PROCEDURE dbo.SZVK_PRINT(@Link int)

AS BEGIN


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,
	@date = [date]
	FROM DICTIONARY_DEPARTMENT D inner join dbo.SA_SZV_K_PACHKA P on D.link = P.link_dep
	WHERE P.link = @link



DECLARE @D_E1 DATETIME

/* Дата окончания периода до 01.01.2002 */
SET @D_E1 = dbo.ConvertDMY2Date(31,12,'2001')




-------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
/*Даты по условиям труда по сотрудникам*/
--территориальные условия
CREATE TABLE #R_TER (id TINYINT,nGROUP INT, link_pers INT, nom_pp INT, T_USL VARCHAR(10),  T_US_Y INT, T_US_M INT , T_US_D INT,t_lastday int )
INSERT INTO #R_TER(id, nGROUP, link_pers, nom_pp, T_USL,  T_US_Y, T_US_M, T_US_D,t_lastday)
	 select 
		id ,
		nGROUP,
		link_pers,
		nom_pp = 0,
		T_USL,
		T_US_Y,
		T_US_M,
		T_US_D,
		t_lastday
		from 
		(SELECT 	
			DEP_LINK = @varKSDEP,
			[DATE_DOC] = @date,
			TYPE_SVED = p.TYPE_SVED, 
			[ID] = S.orders,
			[NGROUP] = S.pachka,
			LINK_PERS = S.LINK_FACE,
			ID_WORK = SWD.ORDERS, 
			/*сведения по стажу*/
			OSN = 1,
			ID_ST = ST.ORDERS,
			DATE_BEGIN = st.date1 ,
			DATE_END = st.date2,
			T_USL = ltrim(rtrim(st.TER_USL)),
			T_KOEF = isnull(st.TER_KOEF,0),
			F_T_USL = st.f_ter_usl,
			t_US_y = year(st.date2+1) - year(st.date1),
			t_US_m = month(st.date2+1) - month(st.date1), 
			t_US_d = day(st.date2+1) - day(st.date1),
			t_lastday = 30
		 from 
			dbo.SA_SZV_K_PACHKA P INNER JOIN dbo.SA_SZV_K_SVEDENIA S ON P.link = S.link
			inner join SZV_K_SVEDENIA s1 on s1.link = s.link1
			INNER JOIN dbo.SA_SZV_K_SVED_WORK_DEP SWD ON SWD.LINK = S1.LINK 	
			LEFT JOIN dbo.SA_SZV_K_STAZH ST ON ST.link = SWD.link1 
		where
			P.link = @Link
			--and S.forma = 1
			and P.proverka = 1

			/*дополнительные сведения по стажу*/
		UNION all
		
		SELECT
			DEP_LINK = @varKSDEP,
			[DATE_DOC] = @date,
			TYPE_SVED = p.TYPE_SVED, 
			[ID] = S.orders,
			[NGROUP] = S.pachka,
			LINK_PERS = S.LINK_FACE,
			ID_WORK = SWD.ORDERS, 
			/*сведения по стажу*/
			OSN = 0 ,
			ID_ST = isnull(std.orders,0),
			DATE_BEGIN = std.date1 ,
			DATE_END = std.date2,
			T_USL = ltrim(rtrim(std.TER_USL)) ,
			T_KOEF = std.TER_KOEF,
			F_T_USL = std.f_ter_usl,
			t_US_y = year(std.date2+1) - year(std.date1),
			t_US_m = month(std.date2+1) - month(std.date1), 
			t_US_d = day(std.date2+1) - day(std.date1),
			t_lastday = 30
		from 
			dbo.SA_SZV_K_PACHKA P INNER JOIN dbo.SA_SZV_K_SVEDENIA S ON P.link = S.link
			inner join SZV_K_SVEDENIA s1 on s1.link = s.link1
			INNER JOIN dbo.SA_SZV_K_SVED_WORK_DEP SWD ON SWD.LINK = S1.LINK 	
			LEFT JOIN dbo.SA_SZV_K_STAZH ST ON ST.link = SWD.link1 
			LEFT JOIN dbo.SA_SZV_K_STAZH_DOP STD ON STD.link = ST.link1 
		where
			P.link = @Link
			--and S.forma = 1
			and P.proverka = 1
			AND isnull(std.orders,0) <> 0
) t
GROUP BY id , nGROUP, link_pers, T_USL, T_US_Y, T_US_M, T_US_D, t_lastday

	UPDATE #R_TER SET t_US_y = convert(int, t_US_y), t_US_m = t_US_m + (t_US_y-convert(int, t_US_y)) * 12
	UPDATE #R_TER SET t_US_m = convert(int, t_US_m), t_US_d = t_US_d + (t_US_m-convert(int, t_US_m)) * t_lastday
	UPDATE #R_TER SET t_US_m = t_US_m - 1, t_US_d = t_US_d + t_lastday WHERE t_US_d<0
	UPDATE #R_TER SET t_US_y = t_US_y - 1, t_US_m = t_US_m + 12 WHERE t_US_m<0


CREATE TABLE #R_TER1 (id TINYINT,nGROUP INT, link_pers INT, nom_pp INT, T_USL VARCHAR(10),  T_US_Y INT, T_US_M INT , T_US_D INT,t_lastday int )
INSERT INTO #R_TER1(id, nGROUP, link_pers, nom_pp, T_USL,  T_US_Y, T_US_M, T_US_D,t_lastday)
-- exec SZVK_PRINT 2
SELECT id ,
	nGROUP,
	link_pers,
	nom_pp = ROW_NUMBER() OVER (PARTITION BY link_pers, id ORDER BY t_usl),
	T_USL,  T_US_Y = SUM(T_US_Y),
	T_US_M = SUM(T_US_M),
	T_US_D = SUM(T_US_D),
	t_lastday 
FROM #R_TER
	WHERE ltrim(rtrim(T_USL)) <> '' 
	GROUP BY id , nGROUP, link_pers, T_USL,t_lastday

	UPDATE #R_TER1 SET t_US_y = convert(int, t_US_y), t_US_m = t_US_m + (t_US_y-convert(int, t_US_y)) * 12
	UPDATE #R_TER1 SET t_US_m = convert(int, t_US_m), t_US_d = t_US_d + (t_US_m-convert(int, t_US_m)) * t_lastday
	UPDATE #R_TER1 SET t_US_m = t_US_m - 1, t_US_d = t_US_d + t_lastday WHERE t_US_d<0
	UPDATE #R_TER1 SET t_US_y = t_US_y - 1, t_US_m = t_US_m + 12 WHERE t_US_m<0

DROP TABLE #R_TER

------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
--особые условия
CREATE TABLE #R_os(id TINYINT,nGROUP INT, link_pers INT, nom_pp INT, O_USL VARCHAR(10),  O_US_Y INT, O_US_M INT , O_US_D INT,O_lastday int )
INSERT INTO #R_os(id, nGROUP, link_pers, nom_pp, O_USL,  O_US_Y, O_US_M, O_US_D,O_lastday)
	 select 
		id ,
		nGROUP,
		link_pers,
		nom_pp = 0,
		O_USL,
		O_US_Y,
		O_US_M,
		O_US_D,
		O_lastday
		from 
		(SELECT 	
			DEP_LINK = @varKSDEP,
			[DATE_DOC] = @date,
			TYPE_SVED = p.TYPE_SVED, 
			[ID] = S.orders,
			[NGROUP] = S.pachka,
			LINK_PERS = S.LINK_FACE,
			ID_WORK = SWD.ORDERS, 
			/*сведения по стажу*/
			OSN = 1,
			ID_ST = ST.ORDERS,
			DATE_BEGIN = st.date1 ,
			DATE_END = st.date2,
			O_USL = st.OSOB_USL,
			O_US_y = year(st.date2+1) - year(st.date1),
			O_US_m = month(st.date2+1) - month(st.date1), 
			O_US_d = day(st.date2+1) - day(st.date1),
			O_lastday = 30
		 from 
			dbo.SA_SZV_K_PACHKA P INNER JOIN dbo.SA_SZV_K_SVEDENIA S ON P.link = S.link
			inner join SZV_K_SVEDENIA s1 on s1.link = s.link1
			INNER JOIN dbo.SA_SZV_K_SVED_WORK_DEP SWD ON SWD.LINK = S1.LINK 	
			LEFT JOIN dbo.SA_SZV_K_STAZH ST ON ST.link = SWD.link1 
		where
			P.link = @Link
			--and S.forma = 1
			and P.proverka = 1

			/*дополнительные сведения по стажу*/
		UNION all
		
		SELECT
			DEP_LINK = @varKSDEP,
			[DATE_DOC] = @date,
			TYPE_SVED = p.TYPE_SVED, 
			[ID] = S.orders,
			[NGROUP] = S.pachka,
			LINK_PERS = S.LINK_FACE,
			ID_WORK = SWD.ORDERS, 
			/*сведения по стажу*/
			OSN = 0 ,
			ID_ST = isnull(std.orders,0),
			DATE_BEGIN = std.date1 ,
			DATE_END = std.date2,
			O_USL = stD.OSOB_USL,
			O_US_y = year(stD.date2+1) - year(stD.date1),
			O_US_m = month(stD.date2+1) - month(stD.date1), 
			O_US_d = day(stD.date2+1) - day(stD.date1),
			O_lastday = 30
		from 
			dbo.SA_SZV_K_PACHKA P INNER JOIN dbo.SA_SZV_K_SVEDENIA S ON P.link = S.link
			inner join SZV_K_SVEDENIA s1 on s1.link = s.link1
			INNER JOIN dbo.SA_SZV_K_SVED_WORK_DEP SWD ON SWD.LINK = S1.LINK 	
			LEFT JOIN dbo.SA_SZV_K_STAZH ST ON ST.link = SWD.link1 
			LEFT JOIN dbo.SA_SZV_K_STAZH_DOP STD ON STD.link = ST.link1 
		where
			P.link = @Link
			--and S.forma = 1
			and P.proverka = 1
			AND isnull(std.orders,0) <> 0
) t
GROUP BY id , nGROUP, link_pers, O_USL, O_US_Y, O_US_M, O_US_D, O_lastday

	UPDATE #R_os SET O_US_y = convert(int, O_US_y), O_US_m = O_US_m + (O_US_y-convert(int, O_US_y)) * 12
	UPDATE #R_os SET O_US_m = convert(int, O_US_m), O_US_d = O_US_d + (O_US_m-convert(int, O_US_m)) * O_lastday
	UPDATE #R_os SET O_US_m = O_US_m - 1, O_US_d = O_US_d + O_lastday WHERE O_US_d<0
	UPDATE #R_os SET O_US_y = O_US_y - 1, O_US_m = O_US_m + 12 WHERE O_US_m<0


CREATE TABLE #R_os1 (id TINYINT,nGROUP INT, link_pers INT, nom_pp INT, O_USL VARCHAR(10),  O_US_Y INT, O_US_M INT , O_US_D INT,O_lastday int )
INSERT INTO #R_os1(id, nGROUP, link_pers, nom_pp, O_USL,  O_US_Y, O_US_M, O_US_D,O_lastday)
-- exec SZVK_PRINT 2
SELECT id ,
	nGROUP,
	link_pers,
	nom_pp = ROW_NUMBER() OVER (PARTITION BY link_pers, id ORDER BY O_usl),
	O_USL,  O_US_Y = SUM(O_US_Y),
	O_US_M = SUM(O_US_M),
	O_US_D = SUM(O_US_D),
	O_lastday 
FROM #R_os
	WHERE ltrim(rtrim(O_USL)) <> '' 
	GROUP BY id , nGROUP, link_pers, O_USL,O_lastday

	UPDATE #R_os1 SET O_US_y = convert(int, O_US_y), O_US_m = O_US_m + (O_US_y-convert(int, O_US_y)) * 12
	UPDATE #R_os1 SET O_US_m = convert(int, O_US_m), O_US_d = O_US_d + (O_US_m-convert(int, O_US_m)) * O_lastday
	UPDATE #R_os1 SET O_US_m = O_US_m - 1, O_US_d = O_US_d + O_lastday WHERE O_US_d<0
	UPDATE #R_os1 SET O_US_y = O_US_y - 1, O_US_m = O_US_m + 12 WHERE O_US_m<0

DROP TABLE #R_os
-------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
--выслуга лет
CREATE TABLE #R_ud(id TINYINT,nGROUP INT, link_pers INT, nom_pp INT, UD_osn VARCHAR(10),  UD_US_Y INT, UD_US_M INT , UD_US_D INT,UD_lastday int )
INSERT INTO #R_ud(id, nGROUP, link_pers, nom_pp, UD_osn,  UD_US_Y, UD_US_M, UD_US_D,UD_lastday)
	 select 
		id ,
		nGROUP,
		link_pers,
		nom_pp = 0,
		ud_osn,
		UD_US_Y,
		UD_US_M,
		UD_US_D,
		UD_lastday
		from 
		(SELECT 	
			DEP_LINK = @varKSDEP,
			[DATE_DOC] = @date,
			TYPE_SVED = p.TYPE_SVED, 
			[ID] = S.orders,
			[NGROUP] = S.pachka,
			LINK_PERS = S.LINK_FACE,
			ID_WORK = SWD.ORDERS, 
			/*сведения по стажу*/
			OSN = 1,
			ID_ST = ST.ORDERS,
			DATE_BEGIN = st.date1 ,
			DATE_END = st.date2,
			ud_osn = st.ud_osnov,
			uD_US_y = year(st.date2+1) - year(st.date1),
			uD_US_m = month(st.date2+1) - month(st.date1), 
			uD_US_d = day(st.date2+1) - day(st.date1),	
			UD_lastday = 30
		 from 
			dbo.SA_SZV_K_PACHKA P INNER JOIN dbo.SA_SZV_K_SVEDENIA S ON P.link = S.link
			inner join SZV_K_SVEDENIA s1 on s1.link = s.link1
			INNER JOIN dbo.SA_SZV_K_SVED_WORK_DEP SWD ON SWD.LINK = S1.LINK 	
			LEFT JOIN dbo.SA_SZV_K_STAZH ST ON ST.link = SWD.link1 
		where
			P.link = @Link
			--and S.forma = 1
			and P.proverka = 1

			/*дополнительные сведения по стажу*/
		UNION all
		
		SELECT
			DEP_LINK = @varKSDEP,
			[DATE_DOC] = @date,
			TYPE_SVED = p.TYPE_SVED, 
			[ID] = S.orders,
			[NGROUP] = S.pachka,
			LINK_PERS = S.LINK_FACE,
			ID_WORK = SWD.ORDERS, 
			/*сведения по стажу*/
			OSN = 0 ,
			ID_ST = isnull(std.orders,0),
			DATE_BEGIN = std.date1 ,
			DATE_END = std.date2,
			ud_OSN = stD.ud_osnov,
			UD_US_y = year(stD.date2+1) - year(stD.date1),
			UD_US_m = month(stD.date2+1) - month(stD.date1), 
			UD_US_d = day(stD.date2+1) - day(stD.date1),
			UD_lastday = 30
		from 
			dbo.SA_SZV_K_PACHKA P INNER JOIN dbo.SA_SZV_K_SVEDENIA S ON P.link = S.link
			inner join SZV_K_SVEDENIA s1 on s1.link = s.link1
			INNER JOIN dbo.SA_SZV_K_SVED_WORK_DEP SWD ON SWD.LINK = S1.LINK 	
			LEFT JOIN dbo.SA_SZV_K_STAZH ST ON ST.link = SWD.link1 
			LEFT JOIN dbo.SA_SZV_K_STAZH_DOP STD ON STD.link = ST.link1 
		where
			P.link = @Link
			--and S.forma = 1
			and P.proverka = 1
			AND isnull(std.orders,0) <> 0
) t
GROUP BY id , nGROUP, link_pers, UD_osn, ud_US_Y, ud_US_M, ud_US_D, ud_lastday

	UPDATE #R_ud SET ud_US_y = convert(int, ud_US_y), ud_US_m = ud_US_m + (ud_US_y-convert(int, ud_US_y)) * 12
	UPDATE #R_ud SET ud_US_m = convert(int, ud_US_m), ud_US_d = ud_US_d + (ud_US_m-convert(int, ud_US_m)) * ud_lastday
	UPDATE #R_ud SET ud_US_m = ud_US_m - 1, ud_US_d = ud_US_d + ud_lastday WHERE ud_US_d<0
	UPDATE #R_ud SET ud_US_y = ud_US_y - 1, ud_US_m = ud_US_m + 12 WHERE ud_US_m<0


CREATE TABLE #R_ud1 (id TINYINT,nGROUP INT, link_pers INT, nom_pp INT, UD_osn VARCHAR(10),  ud_US_Y INT, ud_US_M INT , ud_US_D INT,ud_lastday int )
INSERT INTO #R_ud1(id, nGROUP, link_pers, nom_pp, UD_osn,  ud_US_Y, ud_US_M, ud_US_D,ud_lastday)

SELECT id ,
	nGROUP,
	link_pers,
	nom_pp = ROW_NUMBER() OVER (PARTITION BY link_pers, id ORDER BY UD_osn),
	UD_osn,  ud_US_Y = SUM(ud_US_Y),
	ud_US_M = SUM(ud_US_M),
	ud_US_D = SUM(ud_US_D),
	ud_lastday 
FROM #R_ud
	WHERE ltrim(rtrim(UD_osn)) <> ''    
	GROUP BY id , nGROUP, link_pers, UD_osn,ud_lastday

	UPDATE #R_ud1 SET ud_US_y = convert(int, ud_US_y), ud_US_m = ud_US_m + (ud_US_y-convert(int, ud_US_y)) * 12
	UPDATE #R_ud1 SET ud_US_m = convert(int, ud_US_m), ud_US_d = ud_US_d + (ud_US_m-convert(int, ud_US_m)) * ud_lastday
	UPDATE #R_ud1 SET ud_US_m = ud_US_m - 1, ud_US_d = ud_US_d + ud_lastday WHERE ud_US_d<0
	UPDATE #R_ud1 SET ud_US_y = ud_US_y - 1, ud_US_m = ud_US_m + 12 WHERE ud_US_m<0

DROP TABLE #R_ud




SELECT 	
	link = p.link, 
	DEP_LINK = @varKSDEP,
	DEP_NAME = @varKSname,
	OKPO = @varKSOKPO,
	INN = @varKSINN,
	KPP = @varKSKPP,
	PF_NUMBER = @varKSNOM_PF,
	[DATE_DOC] = @date,
	TYPE_SVED = p.TYPE_SVED, 
	[ID] = S.orders,
	[NGROUP] = S.pachka,
	cGRP = '',
	LINK_PERS = S.LINK_FACE,
	FM = s.FM,
	IM = s.IM,
	OT = S.OT,
	BIRTHDATE = S.BIRTHDATE, 
	INSUR_NUM = s.PF_NUM,
	TER_USL = s.TER_USL,
	ter_koef = isnull(s.ter_koef,0),
	F_TER_USL = s.F_TER_USL,
	ALL_ST_Y = S.ALL_STAZH_Y,
	ALL_ST_M = S.ALL_STAZH_M,
	ALL_ST_D = S.ALL_STAZH_D,
	ID_WORK = SWD.ORDERS, 
	W_NDEP = LTRIM(rtrim(SWD.NAME_DEP)),
	W_INN = SWD.INN,
	W_KPP = SWD.KPP,
	W_OKPO = SWD.OKPO,
	VID_WORK = SWD.VID_WORK, 
	/*сведения по стажу*/
	ID_ST = ST.ORDERS,
	DATE_BEGIN = st.date1 ,
	DATE_END = st.date2,
	POST  = st.POST,
	s_T_USL = st.TER_USL,
	s_T_KOEF = isnull(st.TER_KOEF,0),
	s_F_T_USL = st.f_ter_usl,
	s_O_USL = st.OSOB_USL,
	s_O_k1 = isnull(st.OSOB_k1,''),
	s_O_k2 = isnull(st.OSOB_k2,''),
	s_O_k3 = isnull(st.OSOB_k3,''),
	s_F_O_USL = st.F_OSOB_USL,
	s_is_OSNOV = st.is_OSNOV,
	s_is_dop_m = isnull(st.is_dop_m,0),
	s_is_dop_d = isnull(st.is_dop_d,0),
	s_is_dop = st.is_dop,
	s_F_is_osnov = st.F_is_osnov,
	s_F_is_dop = st.F_is_dop,
	s_ud_osnov = st.ud_osnov,
	s_ud_dop_m = isnull(st.ud_dop_m,0),
	s_ud_dop_d = isnull(st.ud_dop_d,0),
	s_ud_dop_k = isnull(st.ud_dop_k,0),
	s_f_ud_osnov = st.f_ud_osnov,
	s_f_ud_dop = st.f_ud_dop,
	/*дополнительные сведения по стажу*/

	ID_SD = isnull(std.orders,0),
	d_POST  = std.POST,
	d_T_USL = std.TER_USL,
	d_T_KOEF = isnull(std.TER_KOEF,0),
	d_F_T_USL = std.f_ter_usl,
	d_O_USL = std.OSOB_USL,
	d_O_k1 = isnull(std.OSOB_k1,''),
	d_O_k2 = isnull(std.OSOB_k2,''),
	d_O_k3 = isnull(std.OSOB_k3,''),
	d_F_O_USL = std.F_OSOB_USL,
	d_is_OSNOV = std.is_OSNOV,
	d_is_dop_m = std.is_dop_m,
	d_is_dop_d = std.is_dop_d,
	d_is_dop = std.is_dop,
	d_F_is_osnov = std.F_is_osnov,
	d_F_is_dop = std.F_is_dop,
	d_ud_osnov = std.ud_osnov,
	d_ud_dop_m = std.ud_dop_m,
	d_ud_dop_d = std.ud_dop_d,
	d_ud_dop_k = isnull(std.ud_dop_k,0),
	d_f_ud_osnov = std.f_ud_osnov,
	d_f_ud_dop = std.f_ud_dop,

	T_usL1 = (SELECT T_USL FROM  #R_TER1 rt  WHERE RT.nom_pp = 1 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE), 
	T_us_y1 = (SELECT T_US_y FROM  #R_TER1 rt  WHERE RT.nom_pp = 1 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_us_M1 = (SELECT T_US_m FROM  #R_TER1 rt  WHERE RT.nom_pp = 1 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_us_D1 = (SELECT T_US_d FROM  #R_TER1 rt  WHERE RT.nom_pp = 1 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_usL2 = (SELECT T_USL FROM  #R_TER1 rt  WHERE RT.nom_pp = 2 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_us_y2 = (SELECT T_US_y FROM  #R_TER1 rt  WHERE RT.nom_pp = 2 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_us_M2 = (SELECT T_US_m FROM  #R_TER1 rt  WHERE RT.nom_pp = 1 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_us_D2 = (SELECT T_US_d FROM  #R_TER1 rt  WHERE RT.nom_pp = 1 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_usL3 = (SELECT T_USL FROM  #R_TER1 rt  WHERE RT.nom_pp = 3 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_us_y3 = (SELECT T_US_y FROM  #R_TER1 rt  WHERE RT.nom_pp = 3 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_us_M3 = (SELECT T_US_M FROM  #R_TER1 rt  WHERE RT.nom_pp = 3 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_us_D3 = (SELECT T_US_D FROM  #R_TER1 rt  WHERE RT.nom_pp = 3 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_usL4 = (SELECT T_USL FROM  #R_TER1 rt  WHERE RT.nom_pp = 4 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_us_y4 = (SELECT T_US_y FROM  #R_TER1 rt  WHERE RT.nom_pp = 4 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_us_M4 = (SELECT T_US_M FROM  #R_TER1 rt  WHERE RT.nom_pp = 4 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_us_D4 = (SELECT T_US_D FROM  #R_TER1 rt  WHERE RT.nom_pp = 4 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_usL5 = (SELECT T_USL FROM  #R_TER1 rt  WHERE RT.nom_pp = 5 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_us_y5 = (SELECT T_US_y FROM  #R_TER1 rt  WHERE RT.nom_pp = 5 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_us_M5 = (SELECT T_US_M FROM  #R_TER1 rt  WHERE RT.nom_pp = 5 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	T_us_D5 = (SELECT T_US_D FROM  #R_TER1 rt  WHERE RT.nom_pp = 5 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_usL1 = (SELECT o_USL FROM  #R_os1 rt  WHERE RT.nom_pp = 1 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE), 
	o_us_y1 = (SELECT O_US_y FROM  #R_OS1 rt  WHERE RT.nom_pp = 1 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_us_M1 = (SELECT O_US_M FROM  #R_OS1 rt  WHERE RT.nom_pp = 1 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_us_D1 = (SELECT O_US_D FROM  #R_OS1 rt  WHERE RT.nom_pp = 1 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_usL2 = (SELECT o_USL FROM  #R_os1 rt  WHERE RT.nom_pp = 2 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_us_y2 = (SELECT O_US_y FROM  #R_OS1 rt  WHERE RT.nom_pp = 2 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_us_M2 = (SELECT O_US_M FROM  #R_OS1 rt  WHERE RT.nom_pp = 2 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_us_D2 = (SELECT O_US_D FROM  #R_OS1 rt  WHERE RT.nom_pp = 2 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_usL3 = (SELECT o_USL FROM  #R_os1 rt  WHERE RT.nom_pp = 3 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_us_y3 = (SELECT O_US_y FROM  #R_OS1 rt  WHERE RT.nom_pp = 3 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_us_M3 = (SELECT O_US_M FROM  #R_OS1 rt  WHERE RT.nom_pp = 3 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_us_D3 = (SELECT O_US_D FROM  #R_OS1 rt  WHERE RT.nom_pp = 3 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_usL4 = (SELECT o_USL FROM  #R_os1 rt  WHERE RT.nom_pp = 4 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_us_y4 = (SELECT O_US_y FROM  #R_OS1 rt  WHERE RT.nom_pp = 4 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_us_M4 = (SELECT O_US_M FROM  #R_OS1 rt  WHERE RT.nom_pp = 4 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_us_D4 = (SELECT O_US_D FROM  #R_OS1 rt  WHERE RT.nom_pp = 4 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),	
	o_usL5 = (SELECT o_USL FROM  #R_os1 rt  WHERE RT.nom_pp = 5 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_us_y5 = (SELECT O_US_y FROM  #R_OS1 rt  WHERE RT.nom_pp = 5 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_us_M5 = (SELECT O_US_M FROM  #R_OS1 rt  WHERE RT.nom_pp = 5 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	o_us_D5 = (SELECT O_US_D FROM  #R_OS1 rt  WHERE RT.nom_pp = 5 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),	
	UD_usL1 = (SELECT UD_osn FROM  #R_UD1 rt  WHERE RT.nom_pp = 1 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE), 
	UD_us_y1 = (SELECT ud_US_y FROM  #R_UD1 rt  WHERE RT.nom_pp = 1 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_us_M1 = (SELECT ud_US_M FROM  #R_UD1 rt  WHERE RT.nom_pp = 1 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_us_D1 = (SELECT ud_US_D FROM  #R_UD1 rt  WHERE RT.nom_pp = 1 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_usL2 = (SELECT UD_osn FROM  #R_UD1 rt  WHERE RT.nom_pp = 2 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_us_y2 =(SELECT ud_US_y FROM  #R_UD1 rt  WHERE RT.nom_pp = 2 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_us_M2 = (SELECT ud_US_M FROM  #R_UD1 rt  WHERE RT.nom_pp = 2 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_us_D2 = (SELECT ud_US_D FROM  #R_UD1 rt  WHERE RT.nom_pp = 2 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_usL3 = (SELECT UD_osn FROM  #R_UD1 rt  WHERE RT.nom_pp = 3 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_us_y3 = (SELECT ud_US_y FROM  #R_UD1 rt  WHERE RT.nom_pp = 3 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_us_M3 = (SELECT ud_US_M FROM  #R_UD1 rt  WHERE RT.nom_pp = 3 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_us_D3 = (SELECT ud_US_D FROM  #R_UD1 rt  WHERE RT.nom_pp = 3 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_usL4 = (SELECT UD_osn FROM  #R_UD1 rt  WHERE RT.nom_pp = 4 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_us_y4 = (SELECT ud_US_y FROM  #R_UD1 rt  WHERE RT.nom_pp = 4 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_us_M4 = (SELECT ud_US_M FROM  #R_UD1 rt  WHERE RT.nom_pp = 4 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_us_D4 = (SELECT ud_US_D FROM  #R_UD1 rt  WHERE RT.nom_pp = 4 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_usL5 = (SELECT UD_osn FROM  #R_UD1 rt  WHERE RT.nom_pp = 5 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_us_y5 = (SELECT ud_US_y FROM  #R_UD1 rt  WHERE RT.nom_pp = 5 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_us_M5 = (SELECT ud_US_M FROM  #R_UD1 rt  WHERE RT.nom_pp = 5 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE),
	UD_us_D5 = (SELECT ud_US_D FROM  #R_UD1 rt  WHERE RT.nom_pp = 5 AND  rt.id = S.orders AND rt.nGROUP=S.pachka AND rt.link_pers = S.LINK_FACE)	
INTO #RES
from 
	dbo.SA_SZV_K_PACHKA P INNER JOIN dbo.SA_SZV_K_SVEDENIA S ON P.link = S.link
	inner join SZV_K_SVEDENIA s1 on s1.link = s.link1
	INNER JOIN dbo.SA_SZV_K_SVED_WORK_DEP SWD ON SWD.LINK = S1.LINK 	
	LEFT JOIN dbo.SA_SZV_K_STAZH ST ON ST.link = SWD.link1 
	LEFT JOIN dbo.SA_SZV_K_STAZH_DOP STD ON STD.link = ST.link1 
where
	P.link = @Link
	--and S.forma = 1
	and P.proverka = 1
order by
	 S.pachka, S.orders, SWD.orders , ST.ORDERS, STD.ORDERS		




SELECT * FROM #RES  ORDER BY type_sved, NGROUP , FM 
-- exec SZVK_PRINT 2 

DROP TABLE #R_TER1
DROP TABLE #R_OS1
DROP TABLE #R_ud1
DROP TABLE #RES

--drop table #SUBDIV

END	




GO


GRANT EXECUTE ON dbo.[SZVK_PRINT] TO PUBLIC

GO



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

GO

CREATE      PROCEDURE [dbo].SS_SZVK_EXPORT_700 (
												@nLink int  /*Ссылка на расчет*/
												) 
AS

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

SET NOCOUNT  ON

CREATE TABLE #DOC(LINK INT)

INSERT INTO #DOC (LINK)
SELECT @nLink


-- Сведения по документу СЗВ-К	
CREATE TABLE #SZV_K (
	link_szvk INT,
	DEP_LINK INT,
	DEP_NAME VARCHAR(254),
	OKPO VARCHAR(20),
	INN VARCHAR(12),
	KPP VARCHAR(9),
	REG_NOM_PF varchar(20),
	[PFNUMBER] VARCHAR(20),
	DOCCOUNT INT,
	DATE_DOC DATETIME ,
	TYPE_SVED tinyint,
	ID int,
	NGROUP int ,
	cGRP VARCHAR(5),
	LINK_PERS INT ,
	FM VARCHAR(100),
	IM VARCHAR(100),
	OT VARCHAR(100),
	BIRTHDATE datetime,
	INSUR_NUM VARCHAR(14),
	ter_usl VARCHAR(10), 
	ter_koef NUMERIC(4,2), 
	F_TER_USL VARCHAR(31),
	ALL_ST_Y int,
	ALL_ST_M int,
	ALL_ST_D INT,
	ID_WORK int,
	W_NDEP VARCHAR(254),
	W_INN VARCHAR(12),
	W_KPP VARCHAR(9),
	W_OKPO VARCHAR(20),
	VID_WORK VARCHAR(30),
	ID_ST int,
	DATE_BEGIN datetime,
	DATE_END datetime,
	POST VARCHAR(254),
	s_T_USL VARCHAR(10),
	s_T_KOEF NUMERIC(18,2),
	s_F_T_USL VARCHAR(31),
	s_O_USL VARCHAR(10),
	s_O_k1 VARCHAR(20),
	s_O_k2 VARCHAR(20),
	s_O_k3 VARCHAR(20),
	s_F_O_USL varchar(73),
	s_is_OSNOV VARCHAR(10),
	s_is_dop_m tinyint,
	s_is_dop_d tinyint,
	s_is_dop VARCHAR(10),
	s_F_is_osnov VARCHAR(73),
	s_F_is_dop VARCHAR(63),
	s_ud_osnov VARCHAR(10),
	s_ud_dop_m tinyint,
	s_ud_dop_d tinyint,
	s_ud_dop_k NUMERIC(18,2),
	s_f_ud_osnov VARCHAR(65),
	s_f_ud_dop VARCHAR(54),
	ID_SD INT ,
	d_POST VARCHAR(254),
	d_T_USL VARCHAR(10),
	d_T_KOEF NUMERIC(18,2),
	d_F_T_USL VARCHAR(31),
	d_O_USL VARCHAR(10),
	d_O_k1 VARCHAR(20),
	d_O_k2 VARCHAR(20),
	d_O_k3 VARCHAR(20),
	d_F_O_USL varchar(73),
	d_is_OSNOV VARCHAR(10),
	d_is_dop_m tinyint,
	d_is_dop_d tinyint,
	d_is_dop VARCHAR(10),
	d_F_is_osnov VARCHAR(73),
	d_F_is_dop VARCHAR(63),
	d_ud_osnov  VARCHAR(10),
	d_ud_dop_m tinyint,
	d_ud_dop_d TINYINT,
	d_ud_dop_k NUMERIC(18,2),
	d_f_ud_osnov VARCHAR(65),
	d_f_ud_dop VARCHAR(54),
	T_usL1 VARCHAR(10), T_us_y1 INT,T_us_M1 int,T_us_D1 INT, 
	T_usL2 VARCHAR(10),T_us_y2 INT,T_us_M2 INT,T_us_D2 INT,      
	T_usL3 VARCHAR(10),T_us_y3 INT,T_us_M3 INT,T_us_D3 INT,     
	T_usL4 VARCHAR(10),T_us_y4 INT,T_us_M4 INT,T_us_D4 INT,     
	T_usL5 VARCHAR(10),T_us_y5 INT,T_us_M5 INT,T_us_D5 INT,     
	o_usL1 VARCHAR(10),o_us_y1 INT,o_us_M1 INT,o_us_D1 INT,     
	o_usL2 VARCHAR(10),o_us_y2 INT,o_us_M2 INT,o_us_D2 INT,     
	o_usL3 VARCHAR(10),o_us_y3 INT,o_us_M3 INT,o_us_D3 INT,     
	o_usL4 VARCHAR(10),o_us_y4 INT,o_us_M4 INT,o_us_D4 INT,     
	o_usL5 VARCHAR(10),o_us_y5 INT,o_us_M5 INT,o_us_D5 INT,     
	UD_usL1 VARCHAR(10),UD_us_y1 INT,UD_us_M1 INT,UD_us_D1 INT,    
	UD_usL2 VARCHAR(10),UD_us_y2 INT,UD_us_M2 INT,UD_us_D2 INT,    
	UD_usL3 VARCHAR(10),UD_us_y3 INT,UD_us_M3 INT,UD_us_D3 INT,    
	UD_usL4 VARCHAR(10),UD_us_y4 INT,UD_us_M4 INT,UD_us_D4 INT,    
	UD_usL5 VARCHAR(10),UD_us_y5 INT,UD_us_M5 INT,UD_us_D5 INT,
	NPP  int identity (1,1))
		


CREATE TABLE #PERS_INFO2 (
	link_szvk INT,
	DEP_LINK INT,
	DEP_NAME VARCHAR(254),
	OKPO VARCHAR(20),
	INN VARCHAR(12),
	KPP VARCHAR(9),
	REG_NOM_PF varchar(20),
	[PFNUMBER] VARCHAR(20),
	DATE_DOC DATETIME ,
	TYPE_SVED tinyint,
	ID int,
	NGROUP int ,
	cGRP VARCHAR(5),
	LINK_PERS INT ,
	FM VARCHAR(100),
	IM VARCHAR(100),
	OT VARCHAR(100),
	BIRTHDATE datetime,
	INSUR_NUM VARCHAR(14),
	ter_usl VARCHAR(10), 
	ter_koef numeric(18,2), 
	F_TER_USL VARCHAR(31),
	ALL_ST_Y int,
	ALL_ST_M int,
	ALL_ST_D int,
	ID_WORK int,
	W_DEP_LINK int,
	W_NDEP VARCHAR(254),
	W_FULL_NAME VARCHAR(2000),
	W_INN VARCHAR(12),
	W_KPP VARCHAR(9),
	W_OKPO VARCHAR(20),
	VID_WORK VARCHAR(30),
	ID_ST int,
	DATE_BEGIN datetime,
	DATE_END datetime,
	POST VARCHAR(254),
	s_T_USL VARCHAR(10),
	s_T_KOEF NUMERIC(18,2),
	s_F_T_USL VARCHAR(31),
	s_O_USL VARCHAR(10),
	s_O_k1 VARCHAR(20),
	s_O_k2 VARCHAR(20),
	s_O_k3 VARCHAR(20),
	s_F_O_USL varchar(73),
	s_is_OSNOV VARCHAR(10),
	s_is_dop_m tinyint,
	s_is_dop_d tinyint,
	s_is_dop VARCHAR(10),
	s_F_is_osnov VARCHAR(73),
	s_F_is_dop VARCHAR(63),
	s_ud_osnov VARCHAR(10),
	s_ud_dop_m tinyint,
	s_ud_dop_d tinyint,
	s_ud_dop_k NUMERIC(18,2),
	s_f_ud_osnov VARCHAR(65),
	s_f_ud_dop VARCHAR(54),
	ID_SD INT ,
	d_POST VARCHAR(254),
	d_T_USL VARCHAR(10),
	d_T_KOEF NUMERIC(18,2),
	d_F_T_USL VARCHAR(31),
	d_O_USL VARCHAR(10),
	d_O_k1 VARCHAR(20),
	d_O_k2 VARCHAR(20),
	d_O_k3 VARCHAR(20),
	d_F_O_USL varchar(73),
	d_is_OSNOV VARCHAR(10),
	d_is_dop_m tinyint,
	d_is_dop_d tinyint,
	d_is_dop VARCHAR(10),
	d_F_is_osnov VARCHAR(73),
	d_F_is_dop VARCHAR(63),
	d_ud_osnov  VARCHAR(10),
	d_ud_dop_m tinyint,
	d_ud_dop_d tinyint,
	d_ud_dop_k NUMERIC(18,2),
	d_f_ud_osnov VARCHAR(65),
	d_f_ud_dop VARCHAR(54))

-- Курсор для выбранных из буфера документов перс учета
DECLARE @CURS1 CURSOR, @link_DOC int, @link_doc_old int, @NG int, @NGPP1 int, @Typ int
set @NGPP1 = 1
set @NG = 0 
set @Typ = 0
set @link_doc_old = 0
SET @CURS1 = CURSOR FORWARD_ONLY

FOR SELECT LINK FROM #DOC order by link 


OPEN @CURS1
FETCH NEXT FROM @CURS1 INTO @LINK_DOC

WHILE @@FETCH_STATUS = 0	

BEGIN

			if @link_doc_old = 0
			begin
				set @link_doc_old = @LINK_DOC 
			end
			--Опись на пачку
			--Опись на документы



			INSERT INTO #SZV_K  (link_szvk,DEP_LINK,DEP_NAME,OKPO,INN,KPP,REG_NOM_PF,DATE_DOC,TYPE_SVED,ID,
								 NGROUP, cGRP,LINK_PERS,FM,IM,OT,BIRTHDATE,INSUR_NUM,ter_usl,ter_koef, 
								 F_TER_USL,ALL_ST_Y,ALL_ST_M,ALL_ST_D,ID_WORK,W_NDEP,W_INN,W_KPP,W_OKPO,VID_WORK,
								 ID_ST,DATE_BEGIN,DATE_END,POST,s_T_USL,s_T_KOEF,s_F_T_USL,s_O_USL,s_O_k1,s_O_k2,s_O_k3,
								 s_F_O_USL,s_is_OSNOV,s_is_dop_m,s_is_dop_d,s_is_dop,s_F_is_osnov,
								 s_F_is_dop,s_ud_osnov,s_ud_dop_m,s_ud_dop_d,s_ud_dop_k,s_f_ud_osnov,s_f_ud_dop,
								 ID_SD,d_POST,d_T_USL,d_T_KOEF,d_F_T_USL,d_O_USL,d_O_k1,d_O_k2,d_O_k3,d_F_O_USL,
								 d_is_OSNOV,d_is_dop_m,d_is_dop_d,d_is_dop,d_F_is_osnov,d_F_is_dop,d_ud_osnov,d_ud_dop_m,
								 d_ud_dop_d,d_ud_dop_k,d_f_ud_osnov,d_f_ud_dop,
								  T_usL1,T_us_y1,T_us_M1,T_us_D1,
								  T_usL2,T_us_y2,T_us_M2,T_us_D2,
								  T_usL3,T_us_y3,T_us_M3,T_us_D3,
								  T_usL4,T_us_y4,T_us_M4,T_us_D4,
								  T_usL5,T_us_y5,T_us_M5,T_us_D5,
								  o_usL1,o_us_y1,o_us_M1,o_us_D1,
								  o_usL2,o_us_y2,o_us_M2,o_us_D2,
								  o_usL3,o_us_y3,o_us_M3,o_us_D3,
								  o_usL4,o_us_y4,o_us_M4,o_us_D4,
								  o_usL5,o_us_y5,o_us_M5,o_us_D5,
								  UD_usL1,UD_us_y1,UD_us_M1,UD_us_D1,
								  UD_usL2,UD_us_y2,UD_us_M2,UD_us_D2,
								  UD_usL3,UD_us_y3,UD_us_M3,UD_us_D3,
								  UD_usL4,UD_us_y4,UD_us_M4,UD_us_D4,
								  UD_usL5,UD_us_y5,UD_us_M5,UD_us_D5)
			exec dbo.SZVK_PRINT @LINK_DOC 

			UPDATE #SZV_K SET link_szvk = @LINK_DOC FROM #SZV_K WHERE link_szvk IS NULL 


			UPDATE #SZV_K SET cGRP = REPLACE(str((NGROUP),5),' ','0')  FROM #SZV_K WHERE LINK_SZVK = @LINK_DOC

			if @link_doc_old <> @LINK_DOC
			begin
				
				UPDATE #SZV_K SET NGROUP = NGROUP + 1  FROM #SZV_K WHERE LINK_PU = @LINK_DOC
				UPDATE #SZV_K SET cGRP = REPLACE(str((cGRP + 1),5),' ','0')  FROM #SZV_K WHERE LINK_SZVK = @LINK_DOC
			end

			

			--Вдруг ПФР номер не указан

			UPDATE #SZV_K SET PFNUMBER = case when LEN(RTRIM(LTRIM(COALESCE(REG_NOM_PF,'')))) < 14 AND link_szvk = @LINK_DOC	then REPLACE(SPACE(14),'              ','000-000-000000') 
													else RTRIM(LTRIM(COALESCE(REG_NOM_PF,''))) end 		

			---- КОЛИЧЕСТВО ДОКУМЕНТОВ В ПАЧКЕ 
			declare @CURS_NUM CURSOR , @LINK_SZVK1 int,@TYPE_SVED1 TINYINT , @NGROUP1 int  , @DOCCOUNT1 INT 
			SET @CURS_NUM = CURSOR FORWARD_ONLY
			
			FOR SELECT link_szvk, TYPE_SVED, NGROUP  FROM #SZV_K GROUP BY link_szvk, TYPE_SVED,NGROUP,ID ORDER BY  ID 


			OPEN @CURS_NUM
			FETCH NEXT FROM @CURS_NUM INTO @LINK_SZVK1,@TYPE_SVED1,@NGROUP1

			WHILE @@FETCH_STATUS = 0	
			BEGIN
					CREATE TABLE #tmp ( LINK_SZVK INT ,TYPE_SVED tinyint, NGROUP int,ID INT)
					INSERT INTO #tmp ( LINK_SZVK,TYPE_SVED, NGROUP,ID)
					SELECT LINK_SZVK,TYPE_SVED, NGROUP,ID 
					FROM #SZV_K 
					WHERE  LINK_SZVK = @LINK_SZVK1 AND TYPE_SVED = @TYPE_SVED1 and NGROUP = @NGROUP1 
					GROUP BY LINK_SZVK,TYPE_SVED, NGROUP,ID
							
					SET @DOCCOUNT1 = (SELECT  COUNT(*) FROM #tmp WHERE  LINK_SZVK = @LINK_SZVK1 AND TYPE_SVED = @TYPE_SVED1 and NGROUP = @NGROUP1 )
					
					DROP TABLE #tmp
					
					update #SZV_K set DOCCOUNT = @DOCCOUNT1 
					from #SZV_K   where LINK_SZVK = @LINK_SZVK1 AND TYPE_SVED = @TYPE_SVED1 and NGROUP = @NGROUP1

				FETCH NEXT FROM @CURS_NUM INTO @LINK_SZVK1,@TYPE_SVED1,@NGROUP1
			END

			CLOSE @CURS_NUM
			DEALLOCATE @CURS_NUM		
			--- заполнение #PERS_INFO2
			INSERT INTO #PERS_INFO2 (link_szvk,DEP_LINK,DEP_NAME,OKPO,INN,KPP,REG_NOM_PF,[PFNUMBER],DATE_DOC,TYPE_SVED,ID,NGROUP, cGRP,LINK_PERS,FM,IM,OT,BIRTHDATE,INSUR_NUM,ter_usl,ter_koef, 
									F_TER_USL,ALL_ST_Y,ALL_ST_M,ALL_ST_D,ID_WORK,W_NDEP,W_INN,W_KPP,W_OKPO,VID_WORK,ID_ST,DATE_BEGIN,DATE_END,
									POST,s_T_USL,s_T_KOEF,s_F_T_USL,s_O_USL,s_O_k1,s_O_k2,s_O_k3,s_F_O_USL,s_is_OSNOV,s_is_dop_m,s_is_dop_d,s_is_dop,s_F_is_osnov,
									s_F_is_dop,s_ud_osnov,s_ud_dop_m,s_ud_dop_d,s_ud_dop_k,s_f_ud_osnov,s_f_ud_dop,ID_SD,d_POST,d_T_USL,d_T_KOEF,d_F_T_USL,d_O_USL,
									d_O_k1,d_O_k2,d_O_k3,d_F_O_USL,d_is_OSNOV,d_is_dop_m,d_is_dop_d,d_is_dop,d_F_is_osnov,d_F_is_dop,d_ud_osnov,d_ud_dop_m,
									d_ud_dop_d,d_ud_dop_k,d_f_ud_osnov,d_f_ud_dop) 
			SELECT link_szvk,DEP_LINK,DEP_NAME,OKPO,INN,KPP,REG_NOM_PF,[PFNUMBER],DATE_DOC,TYPE_SVED,ID,NGROUP, cGRP,LINK_PERS,FM,IM,OT,BIRTHDATE,INSUR_NUM,ter_usl,ter_koef, 
									F_TER_USL,ALL_ST_Y,ALL_ST_M,ALL_ST_D,ID_WORK,W_NDEP,W_INN,W_KPP,W_OKPO,VID_WORK,ID_ST,DATE_BEGIN,DATE_END,
									POST,isnull(s_T_USL,''),isnull(s_T_KOEF,0),isnull(s_F_T_USL,''),isnull(s_O_USL,''),isnull(s_O_k1,''),isnull(s_O_k2,''),isnull(s_O_k3,''),
									isnull(s_F_O_USL,''),isnull(s_is_OSNOV,''),isnull(s_is_dop_m,0),isnull(s_is_dop_d,0),isnull(s_is_dop,''),isnull(s_F_is_osnov,''),
									isnull(s_F_is_dop,''),isnull(s_ud_osnov,''),isnull(s_ud_dop_m,0),isnull(s_ud_dop_d,0),isnull(s_ud_dop_k,0),isnull(s_f_ud_osnov,''),
									isnull(s_f_ud_dop,''),ID_SD,isnull(d_POST,''),isnull(d_T_USL,''),isnull(d_T_KOEF,0),isnull(d_F_T_USL,''),isnull(d_O_USL,''),
									isnull(d_O_k1,''),isnull(d_O_k2,''),isnull(d_O_k3,''),isnull(d_F_O_USL,''),isnull(d_is_OSNOV,''),isnull(d_is_dop_m,0),
									isnull(d_is_dop_d,0),isnull(d_is_dop,''),isnull(d_F_is_osnov,''),isnull(d_F_is_dop,''),isnull(d_ud_osnov,''),isnull(d_ud_dop_m,0),
									isnull(d_ud_dop_d,0),isnull(d_ud_dop_k,0),isnull(d_f_ud_osnov,''),isnull(d_f_ud_dop,'')
			FROM #SZV_K	WHERE link_szvk = @LINK_DOC	 order by NGROUP , ID , ID_WORK, ID_ST , ID_SD


			set @link_doc_old = @link_doc


	FETCH NEXT FROM @CURS1 INTO @LINK_DOC
END

CLOSE @CURS1
DEALLOCATE @CURS1			

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

DECLARE @NN INT, @PN INT, @ON INT
SELECT @NN = 0, @PN = 0, @ON = 0

SELECT *
INTO #PERS_INFO 
FROM #PERS_INFO2 ORDER BY link_szvk,ter_usl , NGROUP,   [ID] 


DECLARE @PI_NGROUP INT, @PI_ID INT, @PI_link_szvk int , @PI_ter_usl VARCHAR(10)  
DECLARE @Cur_PI CURSOR
SET @Cur_PI = CURSOR FORWARD_ONLY

FOR select link_szvk, NGROUP,ter_usl, [ID]  from #PERS_INFO order by link_szvk, NGROUP,ter_usl, [ID] 

OPEN @Cur_PI
FETCH NEXT FROM @Cur_PI INTO @PI_link_szvk, @PI_NGROUP, @PI_ter_usl, @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 link_szvk = @PI_link_szvk and  NGROUP = @PI_NGROUP and  ter_usl = @PI_ter_usl AND ID = @PI_ID 

		SET @ON = @NN				

	END

	FETCH NEXT FROM @Cur_PI INTO @PI_link_szvk, @PI_NGROUP, @PI_ter_usl, @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, @LINK_SZVK INT, @NGROUP int /*Номер пачки*/, @cGRP VARCHAR(5), @lcFNAME varchar(254) /*регистрационный номер ПФР*/, 
	@TIPD varchar(254), @DATE_DOC VARCHAR(10), @EGRUL VARCHAR(13), @ID INT,
	@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), @TYPE_SVED VARCHAR(20),
	@TYPE VARCHAR(20)



SELECT 
	@EGRUL = LTRIM(RTRIM(EGRUL))
FROM DICTIONARY_DEPARTMENT D inner join dbo.SA_SZV_K_PACHKA P on D.link = P.link_dep
WHERE P.link = (SELECT TOP 1 LINK FROM #DOC )


SET @Cur1 = CURSOR FORWARD_ONLY
FOR 
select 	
	LINK_SZVK,
	NGROUP, 
	FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),YEAR(DATE_DOC)) + '-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(5),cGRP))), 	
	DOCCOUNT = RTRIM(LTRIM(CONVERT(VARCHAR(10),DOCCOUNT))), 	
	TYPDOC =  'СЗВ-К',
	PERSCNT = RTRIM(LTRIM(STR(DOCCOUNT))),
	DATE_CRT = CONVERT(VARCHAR(10),GETDATE(),104),
	DATE_DOC = CONVERT(VARCHAR(10),DATE_DOC,104),
	[YEAR] = CONVERT(VARCHAR(4),YEAR(DATE_DOC)),
	TYP_SVED = (CASE WHEN TYPE_SVED = 1 THEN 'ИСХОДНАЯ' WHEN TYPE_SVED = 2 THEN 'КОРРЕКТИРУЮЩАЯ' else 'ОТМЕНЯЮЩАЯ' end)
from #SZV_K GROUP BY LINK_SZVK,TYPE_SVED ,PFNUMBER, NGROUP, cGRP, INN , KPP,DEP_NAME,DOCCOUNT, DATE_DOC order by  LINK_SZVK,TYPE_SVED, NGROUP

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @LINK_SZVK,@NGROUP,@lcFNAME, @INN, @KPP,@DEP_NAME,@PFNUMBER,@PACHNUM,@DOCCOUNT,@TYPDOC,@PERSCNT,@DATE_CRT, @DATE_DOC,@YEAR,@TYPE_SVED

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) + CASE WHEN @TYPE_SVED <> 'ИСХОДНАЯ' THEN '<ВХОДЯЩАЯ_ОПИСЬ>'  ELSE '<ВХОДЯЩАЯ_ОПИСЬ>' END 
					   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) + '<Количество>' + @DOCCOUNT + '</Количество>'
						 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) + '</ВХОДЯЩАЯ_ОПИСЬ>' 

		--Экспорт СЗВ-К	

		DECLARE @Cur2 CURSOR, @PERS_ID int,  @PERS_INFO1 varchar(8000), @PERS_INFO2 varchar(8000),   
				@Cur3 CURSOR, @WORK_ID int,  @PERS_INFO11 varchar(8000), @PERS_INFO22 varchar(8000)   , @COUNT_W INT ,	
				@Cur4 CURSOR, @ID_ST int,  @PERS_INFO111 varchar(8000), @PERS_INFO222 varchar(8000)   , @ST_W INT , @SD_W int
		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_SVED+'</ТипСведений>' + CHAR(10)
		+ 	SPACE(3) + '<СтраховойНомер>'+ RTRIM(LTRIM(COALESCE(INSUR_NUM,''))) +'</СтраховойНомер>' + CHAR(10)
		+ 	SPACE(3) + '<ФИО>' + CHAR(10)
		+ 		SPACE(4) + '<Фамилия>'+ UPPER(RTRIM(LTRIM(COALESCE(FM,'')))) +'</Фамилия>' + CHAR(10)
		+ 		SPACE(4) + '<Имя>'+ UPPER(RTRIM(LTRIM(COALESCE(IM,'')))) +'</Имя>' + CHAR(10)
		+ 		SPACE(4) + '<Отчество>'+ UPPER(RTRIM(LTRIM(COALESCE(OT,'')))) +'</Отчество>' + CHAR(10)
		+ 	SPACE(3) + '</ФИО>' + CHAR(10)
		+ 	SPACE(3) + '<ДатаРождения>'+ CONVERT(VARCHAR(10),BIRTHDATE,104) +'</ДатаРождения>' + CHAR(10)
	    + CASE WHEN  ISNULL(TER_USL,'') <> '' THEN 	
	    	SPACE(3) + '<ТерриториальныеУсловияНа31.12.2001>' + CHAR(10)
		+ 		SPACE(4) + '<ОснованиеТУ>'+ UPPER(RTRIM(LTRIM(COALESCE(TER_USL,'')))) +'</ОснованиеТУ>' + CHAR(10)	
		+ 		SPACE(4) + '<Коэффициент>'+ RTRIM(LTRIM(STR(COALESCE(TER_KOEF,0),4,2))) +'</Коэффициент>' + CHAR(10)	
		+ 	SPACE(3) + '</ТерриториальныеУсловияНа31.12.2001>' + CHAR(10)
	    ELSE ''  END	
	    + 	SPACE(3) + '<ДатаЗаполнения>'+ CONVERT(VARCHAR(10),DATE_DOC,104) +'</ДатаЗаполнения>' + CHAR(10)
		,
		SPACE(1) +  CHAR(10) + '</КОНВЕРТАЦИЯ>' 
		from #PERS_INFO where LINK_SZVK = @LINK_SZVK  and TYPE_SVED = (case @TYPE_SVED WHEN 'ИСХОДНАЯ' then 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END ) and NGROUP = @NGROUP 
		GROUP BY LINK_SZVK, TYPE_SVED , NGROUP,  INSUR_NUM ,FM ,IM,OT,TER_USL,TER_KOEF,DATE_DOC ,BIRTHDATE, ID
		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 LINK_SZVK = @LINK_SZVK and TYPE_SVED = (case @TYPE_SVED WHEN 'ИСХОДНАЯ' then 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END ) and NGROUP = @NGROUP and ID_WORK is not null) --AND @SZV = 1 AND @TYPDOC = 'СПВ-1'
					BEGIN
					
						SET @COUNT_W = 0
							
						CREATE table #TMP1 (ID_WORK INT )
						INSERT INTO #TMP1 (ID_WORK)
						SELECT ID_WORK
						from #PERS_INFO where LINK_SZVK = @LINK_SZVK and NGROUP = @NGROUP AND [ID] = @PERS_ID  and TYPE_SVED = (case @TYPE_SVED WHEN 'ИСХОДНАЯ' then 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END )
						GROUP BY LINK_SZVK ,NGROUP ,[ID],TYPE_SVED,LINK_PERS,FM,IM,OT,ID_WORK,W_NDEP,VID_WORK/*,ID_ST,DATE_BEGIN,DATE_END,s_T_USL */
						ORDER BY [ID],ID_WORK
						
						SET @COUNT_W = (SELECT COUNT(*) FROM #TMP1 )
																		
						DROP TABLE #TMP1
						
						INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
						Select @lcFNAME,+	SPACE(3) + '<СтажДоРегистрации>' + CHAR(10)
										+		SPACE(4) + '<Количество>' + RTRIM(LTRIM(STR(@COUNT_W))) + '</Количество>' + CHAR(10)
						
						SET @Cur3 = CURSOR FORWARD_ONLY
						FOR 
						Select ID_WORK,
						''--SPACE(4) + '<Количество>' + RTRIM(LTRIM(STR(@COUNT_W))) + '</Количество>' + CHAR(10)
								,
						''
						from #PERS_INFO where LINK_SZVK = @LINK_SZVK and NGROUP = @NGROUP AND [ID] = @PERS_ID  and TYPE_SVED = (case @TYPE_SVED WHEN 'ИСХОДНАЯ' then 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END )
						GROUP BY LINK_SZVK ,NGROUP ,[ID],TYPE_SVED,LINK_PERS,FM,IM,OT,ID_WORK,W_NDEP,VID_WORK/*,ID_ST,DATE_BEGIN,DATE_END,s_T_USL */
						ORDER BY [ID],ID_WORK
						
						OPEN @Cur3
							FETCH NEXT FROM @Cur3 INTO @WORK_ID, @PERS_INFO11, @PERS_INFO22
							WHILE (@@fetch_status <> -1)
							BEGIN
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
								SELECT @lcFNAME, @PERS_INFO11
								
								IF (@@fetch_status <> -2)
								BEGIN


									-- exec SS_SZVK_EXPORT_700 2
									
									IF EXISTS (select LINK_SZVK, TYPE_SVED , NGROUP , ID , ID_WORK from #PERS_INFO where LINK_SZVK = @LINK_SZVK and TYPE_SVED = (case @TYPE_SVED WHEN 'ИСХОДНАЯ' then 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END ) and NGROUP = @NGROUP AND ID = @PERS_ID AND ID_WORK= @WORK_ID  GROUP BY  LINK_SZVK, TYPE_SVED , NGROUP , ID , ID_WORK ) 
									BEGIN
										
											
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
											Select @lcFNAME,
												+	SPACE(4) + '<ПериодДеятельности>' + CHAR(10)	
													+	SPACE(5) + '<ВидДеятельности>' + UPPER(RTRIM(LTRIM(VID_WORK))) + '</ВидДеятельности>' + CHAR(10)
													+	SPACE(5) + '<НаименованиеОрганизации>' + UPPER(RTRIM(LTRIM(W_NDEP))) + '</НаименованиеОрганизации>' 
											from #PERS_INFO where LINK_SZVK = @LINK_SZVK and TYPE_SVED = (case @TYPE_SVED WHEN 'ИСХОДНАЯ' then 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END ) and NGROUP = @NGROUP AND ID = @PERS_ID AND ID_WORK= @WORK_ID  GROUP BY  LINK_SZVK, TYPE_SVED , NGROUP , ID , ID_WORK , W_NDEP, VID_WORK	
												
												set @ST_W = 0
												set @ST_W = (select count(*) from (select LINK_SZVK, TYPE_SVED , NGROUP , ID , ID_WORK , ID_ST ,DATE_BEGIN, DATE_END , post, s_t_usl, s_t_koef, s_o_usl, s_o_k1, s_o_k2, s_o_k3,s_is_osnov, s_is_dop_m, s_is_dop_d,s_ud_osnov,s_ud_dop_m,s_ud_dop_d, s_ud_dop_k from #PERS_INFO where LINK_SZVK = @LINK_SZVK and TYPE_SVED = (case @TYPE_SVED WHEN 'ИСХОДНАЯ' then 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END ) and NGROUP = @NGROUP AND ID = @PERS_ID AND ID_WORK= @WORK_ID  GROUP BY  LINK_SZVK, TYPE_SVED , NGROUP , ID , ID_WORK , ID_ST ,DATE_BEGIN, DATE_END , post, s_t_usl, s_t_koef, s_o_usl, s_o_k1, s_o_k2, s_o_k3,s_is_osnov, s_is_dop_m, s_is_dop_d,s_ud_osnov,s_ud_dop_m,s_ud_dop_d, s_ud_dop_k ) a)
												
												IF EXISTS (select LINK_SZVK, TYPE_SVED , NGROUP , ID , ID_WORK , ID_ST ,DATE_BEGIN, DATE_END , post, s_t_usl, s_t_koef, s_o_usl, s_o_k1, s_o_k2, s_o_k3,s_is_osnov, s_is_dop_m, s_is_dop_d,s_ud_osnov,s_ud_dop_m,s_ud_dop_d, s_ud_dop_k from #PERS_INFO where LINK_SZVK = @LINK_SZVK and TYPE_SVED = (case @TYPE_SVED WHEN 'ИСХОДНАЯ' then 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END ) and NGROUP = @NGROUP AND ID = @PERS_ID AND ID_WORK= @WORK_ID  GROUP BY  LINK_SZVK, TYPE_SVED , NGROUP , ID , ID_WORK , ID_ST ,DATE_BEGIN, DATE_END , post, s_t_usl, s_t_koef, s_o_usl, s_o_k1, s_o_k2, s_o_k3,s_is_osnov, s_is_dop_m, s_is_dop_d,s_ud_osnov,s_ud_dop_m,s_ud_dop_d, s_ud_dop_k )
												BEGIN
													
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														Select @lcFNAME, +	SPACE(5) + '<ВсеПериодыРаботы>' + CHAR(10)
																			+	SPACE(6) + '<Количество>' + UPPER(RTRIM(LTRIM(@ST_W))) + '</Количество>' + CHAR(10)
																					
													
													
														SET @Cur4 = CURSOR FORWARD_ONLY
														FOR 
														Select ID_ST,
														SPACE(1) +  CHAR(10) +	SPACE(6) + '<ПериодРаботы>' + CHAR(10)	 --SPACE(4) + '<Количество>' + RTRIM(LTRIM(STR(@COUNT_W))) + '</Количество>' + CHAR(10)
														,
														SPACE(1) +  CHAR(10) + SPACE(6) + '</ПериодРаботы>' 
														
														from #PERS_INFO where LINK_SZVK = @LINK_SZVK and NGROUP = @NGROUP AND [ID] = @PERS_ID  and TYPE_SVED = (case @TYPE_SVED WHEN 'ИСХОДНАЯ' then 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END ) AND ID_WORK = @WORK_ID
														GROUP BY LINK_SZVK ,NGROUP ,[ID],TYPE_SVED,LINK_PERS,FM,IM,OT,ID_WORK,W_NDEP,VID_WORK,ID_ST,DATE_BEGIN,DATE_END/*,s_T_USL */
														ORDER BY [ID],ID_WORK, ID_ST
															
														OPEN @Cur4
															FETCH NEXT FROM @Cur4 INTO @ID_ST, @PERS_INFO111, @PERS_INFO222
															WHILE (@@fetch_status <> -1)
															BEGIN
																INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
																SELECT @lcFNAME, @PERS_INFO111
																
																IF (@@fetch_status <> -2)
																BEGIN
														
							
																	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
																	Select @lcFNAME,
																	+	SPACE(7) + '<ОсновнаяСтрока>' + CHAR(10)
																			+	SPACE(8) + '<НомерСтроки>' + UPPER(RTRIM(LTRIM(STR(ID_ST)))) + '</НомерСтроки>' + CHAR(10)
																			+	SPACE(8) + '<ДатаНачалаПериода>' + CONVERT(VARCHAR(10),DATE_BEGIN,104) + '</ДатаНачалаПериода>' + CHAR(10)
																			+	SPACE(8) + '<ДатаКонцаПериода>' + CONVERT(VARCHAR(10),DATE_END,104) + '</ДатаКонцаПериода>' + CHAR(10)
																			+	SPACE(8) + '<ОсобенностиУчета>' + CHAR(10)
																				+	SPACE(9) + '<ТерриториальныеУсловия>' + CHAR(10)
																					+	SPACE(10) + '<ОснованиеТУ>' + UPPER(RTRIM(LTRIM(s_t_usl))) + '</ОснованиеТУ>' + CHAR(10)           
																					+	SPACE(10) + '<Коэффициент>' + RTRIM(LTRIM(STR(COALESCE(s_t_koef,0),4,2))) + '</Коэффициент>' + CHAR(10)
																				+	SPACE(9) + '</ТерриториальныеУсловия>' + CHAR(10)
																				+	SPACE(9) + '<ОсобыеУсловияТруда>' + CHAR(10)
																					+	SPACE(10) + '<ОснованиеОУТ>' + UPPER(RTRIM(LTRIM(s_o_usl))) + '</ОснованиеОУТ>' + CHAR(10)           
																					+	SPACE(10) + '<ПозицияСписка>' + case when s_o_k1 <> '' THEN  UPPER(RTRIM(LTRIM(s_o_k1))) 
																															 when s_o_k2 <> '' THEN  UPPER(RTRIM(LTRIM(s_o_k2))) 
																															 when s_o_k3 <> '' THEN  UPPER(RTRIM(LTRIM(s_o_k3)))
																															 ELSE '' end
																								  + '</ПозицияСписка>' + CHAR(10)
																				+	SPACE(9) + '</ОсобыеУсловияТруда>' + CHAR(10)
																				+	SPACE(9) + '<ИсчисляемыйСтаж>' + CHAR(10)
																					+	SPACE(10) + '<ОснованиеИС>' + UPPER(RTRIM(LTRIM(s_is_osnov))) + '</ОснованиеИС>' + CHAR(10)           
																					+ CASE WHEN COALESCE(s_f_is_dop,'') LIKE '%Ч.%' OR COALESCE(s_f_is_dop,'') LIKE '%МИН.%' THEN
																							+ SPACE(10) + '<ВыработкаВчасах>' + CHAR(10)
																	+							SPACE(11) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE(s_is_dop_m,0),3))) + '</Часы>' + CHAR(10)
																	+							SPACE(11) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE(s_is_dop_d,0),3))) + '</Минуты>' + CHAR(10)
																	+ 						SPACE(10) + '</ВыработкаВчасах>' + CHAR(10)	
																						ELSE '' END
																	+					CASE WHEN COALESCE(s_f_is_dop,'') LIKE '%МЕС.%' OR COALESCE(s_f_is_dop,'') LIKE '%ДН.%' THEN				
																						+	SPACE(10) + '<ВыработкаКалендарная>' + CHAR(10)
																							+	SPACE(11) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)           
																							+	SPACE(11) + '<ВсеМесяцы>' +  (RTRIM(LTRIM(STR(s_is_dop_m)))) + '</ВсеМесяцы>' + CHAR(10)
																							+	SPACE(11) + '<ВсеДни>' +  (RTRIM(LTRIM(STR(s_is_dop_d)))) + '</ВсеДни>' + CHAR(10)
																						+	SPACE(10) + '</ВыработкаКалендарная>' + CHAR(10)
																						ELSE '' END
																				+	SPACE(9) + '</ИсчисляемыйСтаж>' + CHAR(10)
																				
												
																				+ CASE WHEN RTRIM(LTRIM(COALESCE(s_is_dop,''))) <> '' THEN					
																				+	SPACE(9) + '<ДекретДети>' + RTRIM(LTRIM(COALESCE(s_is_dop,''))) + '</ДекретДети>' + CHAR(10)
																				 ELSE '' END
																				+	SPACE(9) + '<ВыслугаЛет>' + CHAR(10)
																					+	SPACE(10) + '<ОснованиеВЛ>' + UPPER(RTRIM(LTRIM(s_ud_osnov))) + '</ОснованиеВЛ>' + CHAR(10)           
																					+	SPACE(10) + '<ВыработкаКалендарная>' + CHAR(10)
																						+	SPACE(11) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)           
																						+	SPACE(11) + '<ВсеМесяцы>' +  (RTRIM(LTRIM(STR(s_ud_dop_m)))) + '</ВсеМесяцы>' + CHAR(10)
																						+	SPACE(11) + '<ВсеДни>' + (RTRIM(LTRIM(STR(s_ud_dop_d)))) + '</ВсеДни>' + CHAR(10)
																					+	SPACE(10) + '</ВыработкаКалендарная>' + CHAR(10)
																				+	SPACE(9) + '</ВыслугаЛет>' + CHAR(10)
																				+	SPACE(9) + '<ПрофессияДолжность>' + UPPER(RTRIM(LTRIM(post))) + '</ПрофессияДолжность>' + CHAR(10)   

																			+	SPACE(8) + '</ОсобенностиУчета>' + CHAR(10)
																		+	SPACE(7) + '</ОсновнаяСтрока>'

																	--select LINK_SZVK, TYPE_SVED , NGROUP , ID , ID_WORK , ID_ST ,DATE_BEGIN, DATE_END , post, s_t_usl, s_t_koef, s_o_usl, s_o_k1, s_o_k2, s_o_k3,s_is_osnov, s_is_dop_m, s_is_dop_d,s_ud_osnov,s_ud_dop_m,s_ud_dop_d, s_ud_dop_k 
																	from #PERS_INFO 
																	where LINK_SZVK = @LINK_SZVK and TYPE_SVED = (case @TYPE_SVED WHEN 'ИСХОДНАЯ' then 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END ) and NGROUP = @NGROUP AND ID = @PERS_ID AND ID_WORK= @WORK_ID  AND ID_ST = @ID_ST
																	GROUP BY  LINK_SZVK, TYPE_SVED , NGROUP , ID , ID_WORK , ID_ST ,DATE_BEGIN, DATE_END , post, s_t_usl, s_t_koef, s_o_usl, s_o_k1, s_o_k2, s_o_k3,s_is_osnov, s_is_dop_m ,s_f_is_dop, s_is_dop_d,s_is_dop,s_ud_osnov,s_ud_dop_m,s_ud_dop_d, s_ud_dop_k
																	ORDER BY ID,ID_WORK,ID_ST
														
														
											
																	IF EXISTS (select LINK_SZVK, TYPE_SVED , NGROUP , ID , ID_WORK , ID_ST ,DATE_BEGIN, DATE_END ID_SD , post, d_t_usl, d_t_koef, d_o_usl, d_o_k1, d_o_k2, d_o_k3,d_is_osnov, d_is_dop_m, d_is_dop_d,d_is_dop,d_ud_osnov,d_ud_dop_m,d_ud_dop_d, d_ud_dop_k 
																						from #PERS_INFO where LINK_SZVK = @LINK_SZVK and TYPE_SVED = (case @TYPE_SVED WHEN 'ИСХОДНАЯ' then 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END ) and NGROUP = @NGROUP AND ID = @PERS_ID AND ID_WORK= @WORK_ID  AND ID_ST = @ID_ST  AND ISNULL(ID_SD,0) <> 0
																	           GROUP BY  LINK_SZVK, TYPE_SVED , NGROUP , ID , ID_WORK , ID_ST ,DATE_BEGIN, DATE_END , ID_SD , post, d_t_usl, d_t_koef, d_o_usl, d_o_k1, d_o_k2, d_o_k3,d_is_osnov, d_is_dop_m, d_is_dop_d,d_is_dop,d_ud_osnov,d_ud_dop_m,d_ud_dop_d, d_ud_dop_k)
																	BEGIN
																		
																		set @SD_W = 0
																		set @SD_W = (select count(*) from (select LINK_SZVK, TYPE_SVED , NGROUP , ID , ID_WORK , ID_ST ,DATE_BEGIN, DATE_END ID_SD , post, d_t_usl, d_t_koef, d_o_usl, d_o_k1, d_o_k2, d_o_k3,d_is_osnov, d_is_dop_m, d_is_dop_d,d_is_dop,d_ud_osnov,d_ud_dop_m,d_ud_dop_d, d_ud_dop_k 
																						from #PERS_INFO where LINK_SZVK = @LINK_SZVK and TYPE_SVED = (case @TYPE_SVED WHEN 'ИСХОДНАЯ' then 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END ) and NGROUP = @NGROUP AND ID = @PERS_ID AND ID_WORK= @WORK_ID  AND ID_ST = @ID_ST  AND ISNULL(ID_SD,0) <> 0
																	           GROUP BY  LINK_SZVK, TYPE_SVED , NGROUP , ID , ID_WORK , ID_ST ,DATE_BEGIN, DATE_END , ID_SD , post, d_t_usl, d_t_koef, d_o_usl, d_o_k1, d_o_k2, d_o_k3,d_is_osnov, d_is_dop_m, d_is_dop_d,d_is_dop,d_ud_osnov,d_ud_dop_m,d_ud_dop_d, d_ud_dop_k) a)
																			
																		
																		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
																		Select @lcFNAME, +	SPACE(6) + '<ДополнительныеСтроки>' + CHAR(10)
																							+	SPACE(7) + '<Количество>' + UPPER(RTRIM(LTRIM(@SD_W))) + '</Количество>' + CHAR(10)
																														
																		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
																		Select @lcFNAME,
																				+	SPACE(7) + '<ОсобенностиУчета>' + CHAR(10)
																					+	SPACE(8) + '<ТерриториальныеУсловия>' + CHAR(10)
																						+	SPACE(9) + '<ОснованиеТУ>' + UPPER(RTRIM(LTRIM(d_t_usl))) + '</ОснованиеТУ>' + CHAR(10)           
																						+	SPACE(9) + '<Коэффициент>' + RTRIM(LTRIM(STR(COALESCE(d_t_koef,0),4,2))) + '</Коэффициент>' + CHAR(10)
																					+	SPACE(9) + '</ТерриториальныеУсловия>' + CHAR(10)
																					+	SPACE(9) + '<ОсобыеУсловияТруда>' + CHAR(10)
																						+	SPACE(10) + '<ОснованиеОУТ>' + UPPER(RTRIM(LTRIM(d_o_usl))) + '</ОснованиеОУТ>' + CHAR(10)           
																						+	SPACE(10) + '<ПозицияСписка>' + case when d_o_k1 <> '' THEN  UPPER(RTRIM(LTRIM(d_o_k1))) 
																																 when d_o_k2 <> '' THEN  UPPER(RTRIM(LTRIM(d_o_k2))) 
																																 when d_o_k3 <> '' THEN  UPPER(RTRIM(LTRIM(d_o_k3)))
																																 ELSE '' end
																									  + '</ПозицияСписка>' + CHAR(10)
																					+	SPACE(9) + '</ОсобыеУсловияТруда>' + CHAR(10)

																					
																					+	SPACE(9) + '<ИсчисляемыйСтаж>' + CHAR(10)
																						+	SPACE(10) + '<ОснованиеИС>' + UPPER(RTRIM(LTRIM(d_is_osnov))) + '</ОснованиеИС>' + CHAR(10)           
																					+ CASE WHEN COALESCE(d_f_is_dop,'') LIKE '%Ч.%' OR COALESCE(d_f_is_dop,'') LIKE '%МИН.%' THEN
																							+ SPACE(10) + '<ВыработкаВчасах>' + CHAR(10)
																	+							SPACE(11) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE(d_is_dop_m,0),3))) + '</Часы>' + CHAR(10)
																	+							SPACE(11) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE(d_is_dop_d,0),3))) + '</Минуты>' + CHAR(10)
																	+ 						SPACE(10) + '</ВыработкаВчасах>' + CHAR(10)	
																						ELSE '' END
																	+					CASE WHEN COALESCE(d_f_is_dop,'') LIKE '%МЕС.%' OR COALESCE(d_f_is_dop,'') LIKE '%ДН.%' THEN				
																						+	SPACE(10) + '<ВыработкаКалендарная>' + CHAR(10)
																							+	SPACE(11) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)           
																							+	SPACE(11) + '<ВсеМесяцы>' +  (RTRIM(LTRIM(STR(d_is_dop_m)))) + '</ВсеМесяцы>' + CHAR(10)
																							+	SPACE(11) + '<ВсеДни>' +  (RTRIM(LTRIM(STR(d_is_dop_d)))) + '</ВсеДни>' + CHAR(10)
																						+	SPACE(10) + '</ВыработкаКалендарная>' + CHAR(10)
																						ELSE '' END
																					+	SPACE(9) + '</ИсчисляемыйСтаж>' + CHAR(10)
																					
													
																					+ CASE WHEN RTRIM(LTRIM(COALESCE(d_is_dop,''))) <> '' THEN					
																					+	SPACE(9) + '<ДекретДети>' + RTRIM(LTRIM(COALESCE(d_is_dop,''))) + '</ДекретДети>' + CHAR(10)
																					 ELSE '' END
																					+	SPACE(9) + '<ВыслугаЛет>' + CHAR(10)
																						+	SPACE(10) + '<ОснованиеВЛ>' + UPPER(RTRIM(LTRIM(d_ud_osnov))) + '</ОснованиеВЛ>' + CHAR(10)           
																						+	SPACE(10) + '<ВыработкаКалендарная>' + CHAR(10)
																							+	SPACE(11) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)           
																							+	SPACE(11) + '<ВсеМесяцы>' +  (RTRIM(LTRIM(STR(d_ud_dop_m)))) + '</ВсеМесяцы>' + CHAR(10)
																							+	SPACE(11) + '<ВсеДни>' + (RTRIM(LTRIM(STR(d_ud_dop_d)))) + '</ВсеДни>' + CHAR(10)
																						+	SPACE(10) + '</ВыработкаКалендарная>' + CHAR(10)
																					+	SPACE(9) + '</ВыслугаЛет>' + CHAR(10)
																					+	SPACE(9) + '<ПрофессияДолжность>' + UPPER(RTRIM(LTRIM(d_post))) + '</ПрофессияДолжность>' + CHAR(10)   

																				+	SPACE(7) + '</ОсобенностиУчета>' + CHAR(10)

																		--select LINK_SZVK, TYPE_SVED , NGROUP , ID , ID_WORK , ID_ST ,DATE_BEGIN, DATE_END , post, s_t_usl, s_t_koef, s_o_usl, s_o_k1, s_o_k2, s_o_k3,s_is_osnov, s_is_dop_m, s_is_dop_d,s_ud_osnov,s_ud_dop_m,s_ud_dop_d, s_ud_dop_k 
																		from #PERS_INFO 
																		where LINK_SZVK = @LINK_SZVK and TYPE_SVED = (case @TYPE_SVED WHEN 'ИСХОДНАЯ' then 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END ) and NGROUP = @NGROUP AND ID = @PERS_ID AND ID_WORK= @WORK_ID   AND ID_ST = @ID_ST AND ISNULL(ID_SD,0) <> 0
																		GROUP BY  LINK_SZVK, TYPE_SVED , NGROUP , ID , ID_WORK , ID_ST ,DATE_BEGIN, DATE_END , ID_SD , d_post, d_t_usl, d_t_koef, d_o_usl, d_o_k1, d_o_k2, d_o_k3,d_is_osnov, d_is_dop_m,d_is_dop_d,d_is_dop, d_f_is_dop,d_ud_osnov,d_ud_dop_m,d_ud_dop_d, d_ud_dop_k
																		ORDER BY ID,ID_WORK,ID_ST,ID_SD
																	
																		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
																		Select @lcFNAME,  SPACE(6) + '</ДополнительныеСтроки>' 
																				
																	END    -- exec SS_SZVK_EXPORT_700 2
																end

															INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
															SELECT @lcFNAME, @PERS_INFO222	

															FETCH NEXT FROM @Cur4 INTO @ID_ST, @PERS_INFO111, @PERS_INFO222							
															

														END

															
														CLOSE @Cur4
														DEALLOCATE @Cur4
													
												
													
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														Select @lcFNAME,  SPACE(5) + '</ВсеПериодыРаботы>' 
													
												end			


							
									END 
									
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
									SELECT @lcFNAME, SPACE(4) + '</ПериодДеятельности>'
									

								end



								FETCH NEXT FROM @Cur3 INTO @WORK_ID, @PERS_INFO11, @PERS_INFO22							
								
							END
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
								SELECT @lcFNAME, @PERS_INFO22	
								
							CLOSE @Cur3
							DEALLOCATE @Cur3
						
						INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
						Select @lcFNAME,	SPACE(3) + '</СтажДоРегистрации>' 
					
					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  @LINK_SZVK,@NGROUP,@lcFNAME, @INN, @KPP,@DEP_NAME,@PFNUMBER,@PACHNUM,@DOCCOUNT,@TYPDOC,@PERSCNT,@DATE_CRT, @DATE_DOC,@YEAR,@TYPE_SVED
END

CLOSE @Cur1
DEALLOCATE @Cur1
-- exec SS_SZVK_EXPORT_700 2



SET NOCOUNT OFF

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


GO


GRANT EXECUTE ON dbo.[SS_SZVK_EXPORT_700] TO PUBLIC

GO


GO

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

GO

CREATE procedure dbo.I_REPORT_FORMULA_4_FSS_PP_RAZD1
	@varKSOUT_VAL varchar(50) OUTPUT,
	@varKScCode	char(10) = '',
	@varKSiCol	smallint = '0'
AS
DECLARE @varKSname VARCHAR(100), 
	@varKSSQL VARCHAR(8000)
	SET @varKSname = (SELECT ID FROM BUFFER WHERE LINK = -115 AND SID = SUSER_SID() )

	CREATE     TABLE #TMP(
		NUM_PP varchar(50))

	SET @varKSSQL = '

		INSERT INTO #TMP
		SELECT  NUM_PP
		FROM ' + @varKSname + ' 
		WHERE CODE_STR=' + ltrim(@varKScCode)

	EXEC (@varKSSQL)

	IF @varKSiCol = 3
		SET @varKSOUT_VAL = (SELECT  LTRIM(RTRIM(NUM_PP)) FROM #TMP)
	DROP TABLE #TMP
	SELECT @varKSOUT_VAL = ISNULL(@varKSOUT_VAL, '')



GO


GRANT EXECUTE ON dbo.[I_REPORT_FORMULA_4_FSS_PP_RAZD1] TO PUBLIC

GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS(SELECT * 
          FROM dbo.SYSOBJECTS 
          WHERE [ID] = OBJECT_ID(N'dbo.[RO_EXPORT_REPORT_XML]') AND 
                OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RO_EXPORT_REPORT_XML]
END

GO

/*

 c Кейсистемс (Keysystems), 2010
	Экспорт отчетов в формате xml

	create table #Files ([TXT]             VARCHAR(8000), 
                        [ORDERS]          INT IDENTITY(1,1), 
                        [NAMEFILE]        VARCHAR(100), 
                        [NAMEFILE_ARH]    VARCHAR(100), 
                        [OrderFile]       INT DEFAULT(0),
                        [LINK_SAVED_FORM] INT)
	create table #Reports (LSF int)

*/
CREATE PROCEDURE dbo.[RO_EXPORT_REPORT_XML]
	@varKSiLSF	int
AS
	SET NOCOUNT ON
	-- поиск шаблона экспорта
	declare @CodeForm varchar(30), @StartDate datetime, @LinkE int, @NameDate varchar(30), @CodeBudg varchar(30), @CodeOrg varchar(30), @LF int, @BeginDate datetime, @LinkOrg int, @LinkBudg int, @ExecStr nvarchar(4000), @PeriodType TINYINT, @orderCol VARCHAR(100), @value VARCHAR(8000)
	select  @PeriodType = RSF.Period_Type, @BeginDate = RSF.begin_date, @LinkOrg = RSF.Link_Organization, @LinkBudg = RSF.Link_Type_Svod, @LF = RSF.Link_Form, @CodeForm = RF.Code, @StartDate = RF.Start_date from report_forms RF join report_saved_forms RSF on RF.Link_Form = RSF.Link_Form and RSF.Link_Saved_Form = @varKSiLSF
	select @LinkE = Link from REPORT_EXPORT_XML_Forms where Code_Form =  @CodeForm and Start_Date = @StartDate

	if @LinkE is NULL
		select @LinkE = Link from REPORT_EXPORT_XML_Forms where Code_Form =  @CodeForm

	if @LinkE is NULL
		return 1

     IF @CodeForm=RTRIM(LTRIM('0503738G')) AND @LinkE IS NOT NULL  
    BEGIN  
       EXEC dbo.[RA_EXPORT_FORM_FNS_738] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503725G')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_725] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503710G')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_710] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503779G')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_779] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm IN (RTRIM(LTRIM('0503769G_D')),RTRIM(LTRIM('0503769G_K'))) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_769] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503730G_BU')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_730] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503830G')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_830] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503721G')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_721] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503737G')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_737] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503760G')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_760] @varKSiLSF,NULL,1
       RETURN   
    END
    ELSE IF @CodeForm=RTRIM(LTRIM('0503130G')) AND @LinkE IS NOT NULL  
    BEGIN
       EXEC dbo.[RA_EXPORT_FORM_FNS_130] @varKSiLSF,NULL,1
       RETURN   
    END
	--declare #t_LSF table (LSF int)
	create table #t_LSF (LSF int, atr varchar(1000))
	create table #t_Exec (txt varchar(8000))

	insert #t_LSF (LSF, atr)
	select distinct LSF, RSF.atr_code
	from #Reports R join report_saved_forms RSF on R.LSF = RSF.Link_Saved_Form
	where RSF.Link_Form = @LF and RSF.begin_date = @BeginDate and RSF.Link_Organization = @LinkOrg and isnull(RSF.Link_Type_Svod,0) = isnull(@LinkBudg,0)
	union
	select distinct link, RSF.atr_code from dbo.buffer B join report_saved_forms RSF on B.Link = RSF.Link_Saved_Form and sid = suser_sid() and ID = 'REPORT_ATR_EXPORT'
	where RSF.Link_Form = @LF and RSF.begin_date = @BeginDate and RSF.Link_Organization = @LinkOrg and isnull(RSF.Link_Type_Svod,0) = isnull(@LinkBudg,0)

   DELETE R	
	from #Reports R join report_saved_forms RSF on R.LSF = RSF.Link_Saved_Form
	where RSF.Link_Form = @LF and RSF.begin_date = @BeginDate and RSF.Link_Organization = @LinkOrg and isnull(RSF.Link_Type_Svod,0) = isnull(@LinkBudg,0)
	
   DELETE B
   from dbo.buffer B join report_saved_forms RSF on B.Link = RSF.Link_Saved_Form and sid = suser_sid() and ID = 'REPORT_ATR_EXPORT'
	where RSF.Link_Form = @LF and RSF.begin_date = @BeginDate and RSF.Link_Organization = @LinkOrg and isnull(RSF.Link_Type_Svod,0) = isnull(@LinkBudg,0)

		-- готовим данные
------------------------------------------------------------------------------------------------------
	declare @i int
	declare @t_Header table (Code varchar(100), Value varchar(8000), LSF int default 0)

	if @PeriodType = 1
	begin
		insert @t_Header (Code, Value)
		select '@DATE@', convert(varchar(10), dbo.DateBeginOfYear(@beginDate), 120) 

		set @NameDate = LTRIM(RTRIM(STR(YEAR(@beginDate)))) + ' год' 
	end
	else begin
		insert @t_Header (Code, Value)
		select '@DATE@', convert(varchar(10), dbo.DateBeginOfMonth(@beginDate), 120) 

		set @NameDate = RTRIM(dbo.DateMonthName(MONTH(@begindate))) + ' ' + LTRIM(RTRIM(STR(YEAR(@beginDate)))) + ' года' 
	end

	insert @t_Header (Code, Value)
	select '@NAME_DATE@', @NameDate

	set @codeBudg = isnull((select RTRIM(isnull(B.OutCode,'')) from  dbo.kl_budg_type B where  B.link = @LinkBudg ),'')

	insert @t_Header (Code, Value)
	select '@CODE_BUDG@',  @CodeBudg

	insert @t_Header (Code, Value)
	select '@NAME_BUDG@',  isnull((select dbo.[RA_XML_MASK] (RTRIM(isnull(B.Name, ''))) from dbo.kl_budg_type B where B.link = @LinkBudg), '') 

	select @CodeOrg = RTRIM(isnull(D.budg,'')) from dbo.departments D where D.link = @LinkOrg

	insert @t_Header (Code, Value)
	select '@CODE_ORG@',  @CodeOrg

	insert @t_Header (Code, Value)
	select '@NAME_ORG@',  dbo.[RA_XML_MASK](RTRIM(isnull(D.Name,'')))  from dbo.departments D where D.link = @LinkOrg

	insert @t_Header (Code, Value, LSF)
	select '@' + LTRIM(RTRIM(code))+ '@',  RTRIM(dbo.RN_GET_ATR_VALUE(Link_Saved_Form , Code)), Link_Saved_Form 
	from dbo.N_REPORT_ATRIBUTS_VIEW V
			left join report_saved_forms RSF on charindex(RTRIM(V.Code), RSF.atr_code) > 0
			join #t_LSF L on L.LSF = RSF.Link_Saved_Form


	
	--declare #t_Data table (OrderTable tinyint, CodeRow varchar(50), OrderCol char(4), Value varchar(8000), LSF int)
	create table #t_Data (LSF int, OrderTable tinyint, CodeRow varchar(50), OrderCol char(4), Value varchar(8000))
	Create index #IX_DATA on  #t_Data (LSF, OrderTable, CodeRow)
	-- пока только динамика
	insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)
	select RT.orders, RD.Code_Row, '@' + LTRIM(STR(RC.orders)) + '@', case when RC.Col_Type = 0 then LTRIM(STR(RD.float_val, 20, 4)) else dbo.[RA_XML_MASK] (RTRIM(RD.Str_Val)) end, RSF.Link_Saved_form
	from dbo.report_saved_forms RSF 
		join #t_LSF L on RSF.Link_Saved_Form = L.LSF
		join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form
		join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table
		join dbo.report_dinamics_all RD on RD.Link_SF = RSF.Link_Saved_Form and RC.Link_Col = RD.Link_Col
	where RT.Val_Type = 1 --and exists(select top 1 * from dbo.report_dinamics_all RD1 where RD1.Link_SF = RD.Link_SF and RD1.Code_Row = RD.Code_Row and RD1.float_val <> 0) 
			and not exists(select * from dbo.report_export_xml_data D where D.link_up = @LinkE and (RT.orders = D.OT) and (RC.orders = D.OC or D.OC = 0))

	insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)
	select RT.orders, RR.Code, '@' + LTRIM(STR(RC.orders)) + '@', case when RC.Col_Type = 0 then LTRIM(STR(isnull(RS.summa,0), 20, 4)) else case when RC.IsEdited = 1 then dbo.[RA_XML_MASK] (RTRIM(isnull(RST.Str_Val,''))) else dbo.[RA_XML_MASK] (RTRIM(isnull(RF.Formula,''))) end end, RSF.Link_Saved_form
	from dbo.report_saved_forms RSF 
		join #t_LSF L on RSF.Link_Saved_Form = L.LSF
		join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form
		join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table
		join i_report_rows RR on RR.Link_Table = RT.Link_Table
		left join dbo.report_summa_all RS on RS.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RS.Link_Col and RR.Link_Row = RS.Link_Row
		left join dbo.report_string_all RST on RST.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RST.Link_Col and RR.Link_Row = RST.Link_Row
		left join dbo.report_formula RF on RC.Link_Col = RF.Link_Col and RR.Link_Row = RF.Link_Row
	where RT.Val_Type = 0 and exists(select top 1 * from dbo.report_summa S1 where S1.Link_Saved_Form = RSF.Link_Saved_Form and S1.Link_Row = RR.Link_Row and S1.summa <> 0) 
		and not exists(select * from dbo.report_export_xml_data D where D.link_up = @LinkE and RT.orders = D.OT and (RC.orders = D.OC or D.OC = 0))

	insert #t_Exec (txt)
	select 'insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)
	select ' + isnull(T.COND, 'RT.orders') + ', RD.Code_Row, ''@'' + LTRIM(STR(RC.orders)) + ''@'', case when RC.Col_Type = 0 then LTRIM(STR(RD.float_val, 20, 4)) else dbo.[RA_XML_MASK] (' + isnull(C.COND, 'RD.Str_Val') +  ') end, RSF.Link_Saved_form
	from dbo.report_saved_forms RSF 
		join #t_LSF L on RSF.Link_Saved_Form = L.LSF
		join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form and RT.orders = ' + case when LTRIM(STR(COALESCE(C.OT, T.OT, 0))) = '0' then 'RT.orders' else LTRIM(STR(COALESCE(C.OT, T.OT, 0))) end  + '
		join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table and (RC.orders = ' + LTRIM(STR(isnull(C.OC, 0))) + ' or 0 = ' + LTRIM(STR(isnull(C.OC,0))) + ')
		join dbo.report_dinamics_all RD on RD.Link_SF = RSF.Link_Saved_Form and RC.Link_Col = RD.Link_Col '
	from (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC <> 0) C
		full join (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC = 0) T on C.OT = T.OT
	where isnull(C.OT, T.OT) in (select orders from dbo.report_tables where Link_Form = @LF and Val_Type = 1)

	
	insert #t_Exec (txt)
	select ' insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)
	select ' + isnull(T.COND, 'RT.orders') + ', RR.Code, ''@'' + LTRIM(STR(RC.orders)) + ''@'', case when RC.Col_Type = 0 then LTRIM(STR(isnull(RS.summa,0), 20, 4)) else case when RC.IsEdited = 1 then dbo.[RA_XML_MASK] (RTRIM(isnull(RST.Str_Val,''''))) else dbo.[RA_XML_MASK] (' + isnull(C.COND,'RTRIM(isnull(RF.Formula,''''))') + ') end end, RSF.Link_Saved_form
	from dbo.report_saved_forms RSF 
		join #t_LSF L on RSF.Link_Saved_Form = L.LSF
		join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form and RT.orders = ' + case when LTRIM(STR(COALESCE(C.OT, T.OT, 0))) = '0' then 'RT.orders' else LTRIM(STR(COALESCE(C.OT, T.OT, 0))) end  + '
		join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table and (RC.orders = ' + LTRIM(STR(isnull(C.OC, 0))) + ' or 0 = ' + LTRIM(STR(isnull(C.OC,0))) + ')
		join i_report_rows RR on RR.Link_Table = RT.Link_Table
		left join dbo.report_summa_all RS on RS.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RS.Link_Col and RR.Link_Row = RS.Link_Row
		left join dbo.report_string_all RST on RST.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RST.Link_Col and RR.Link_Row = RST.Link_Row
		left join dbo.report_formula RF on RC.Link_Col = RF.Link_Col and RR.Link_Row = RF.Link_Row
	where exists(select top 1 * from dbo.report_summa S1 where S1.Link_Saved_Form = RSF.Link_Saved_Form and S1.Link_Row = RR.Link_Row and S1.summa <> 0)'
	from (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC <> 0) C
		full join (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC = 0) T on C.OT = T.OT
	where isnull(C.OT, T.OT)  in (select orders from dbo.report_tables where Link_Form = @LF and Val_Type = 0)

	insert #t_Exec (txt)
	select top 1 ' insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)
	select ' + isnull(T.COND, 'RT.orders') + ', RR.Code, ''@'' + LTRIM(STR(RC.orders)) + ''@'', case when RC.Col_Type = 0 then LTRIM(STR(isnull(RS.summa,0), 20, 4)) else case when RC.IsEdited = 1 then dbo.[RA_XML_MASK] (RTRIM(isnull(RST.Str_Val,''''))) else dbo.[RA_XML_MASK] (RTRIM(isnull(RF.Formula,''''))) end end, RSF.Link_Saved_form
	from dbo.report_saved_forms RSF 
		join #t_LSF L on RSF.Link_Saved_Form = L.LSF
		join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form and RT.orders = ' + LTRIM(STR(COALESCE(T.OT, 0))) + '
		join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table 
		join i_report_rows RR on RR.Link_Table = RT.Link_Table
		left join dbo.report_summa_all RS on RS.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RS.Link_Col and RR.Link_Row = RS.Link_Row
		left join dbo.report_string_all RST on RST.Link_Saved_Form = RSF.Link_Saved_Form and RC.Link_Col = RST.Link_Col and RR.Link_Row = RST.Link_Row
		left join dbo.report_formula RF on RC.Link_Col = RF.Link_Col and RR.Link_Row = RF.Link_Row
	where exists(select top 1 * from dbo.report_summa S1 where S1.Link_Saved_Form = RSF.Link_Saved_Form and S1.Link_Row = RR.Link_Row and S1.summa <> 0)
		and not exists(select top 1 * from #t_Data D where D.OrderTable = '+ isnull(T.COND, 'RT.orders') + ' and D.CodeRow = RR.Code and D.OrderCol = ''@'' + LTRIM(STR(RC.orders)) + ''@'' and D.LSF = RSF.Link_Saved_form)'
	from (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC = 0) T 
	where  T.OT  in (select orders from dbo.report_tables where Link_Form = @LF and Val_Type = 0)


	insert #t_Exec (txt)
	select top 1 'insert #t_Data (OrderTable, CodeRow, OrderCol, Value, LSF)
	select ' + isnull(T.COND, 'RT.orders') + ', RD.Code_Row, ''@'' + LTRIM(STR(RC.orders)) + ''@'', case when RC.Col_Type = 0 then LTRIM(STR(RD.float_val, 20, 4)) else dbo.[RA_XML_MASK] (RD.Str_Val) end, RSF.Link_Saved_form
	from dbo.report_saved_forms RSF 
		join #t_LSF L on RSF.Link_Saved_Form = L.LSF
		join dbo.report_tables RT on RSF.Link_Form = RT.Link_Form and RT.orders = ' + LTRIM(STR(COALESCE(T.OT, 0)))  + '
		join dbo.report_coloumns RC on RT.Link_Table = RC.Link_Table 
		join dbo.report_dinamics_all RD on RD.Link_SF = RSF.Link_Saved_Form and RC.Link_Col = RD.Link_Col 
	where not exists(select top 1 * from #t_Data D where D.OrderTable = '+ isnull(T.COND, 'RT.orders') + ' and D.CodeRow = RD.Code_Row and D.OrderCol = ''@'' + LTRIM(STR(RC.orders)) + ''@'' and D.LSF = RSF.Link_Saved_form)'
	from (select * from dbo.report_export_xml_data D where D.link_up = @LinkE and OC = 0) T 
	where  T.OT  in (select orders from dbo.report_tables where Link_Form = @LF and Val_Type = 1)


	exec ssp_execresultset 'select txt from #t_Exec'--, @varKSDebug = 1
   
--select * 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.[RI_REPORT_FORMULA_4_FSS_PP_RAZD1]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RI_REPORT_FORMULA_4_FSS_PP_RAZD1]

GO


/*
c Кейсистемс (Keysystems), 2005
*/
CREATE               PROCEDURE dbo.RI_REPORT_FORMULA_4_FSS_PP_RAZD1
	@res varchar(50) output, @varcStr varchar(250), @vardBegin datetime = '20050101', @vardEnd datetime = '20051231', @variCol int, @variRow int, @variLSF int
AS
	declare @tmp int, @cStr varchar(250), @cSubStr1 varchar(250)
	set @cStr = @varcStr
	set @res = ''
	exec dbo.RO_FORMULA_FUNCTIONS 1, @cStr output, @cSubStr1 output, ','
	if LEN(@cStr) = 0
	begin
		set @cStr = @cSubStr1
		set @cSubStr1 = ''
	end
	if @cStr = ''
		return 0
	set @tmp = CONVERT(int, @cStr)
	exec dbo.I_REPORT_FORMULA_4_FSS_PP_RAZD1 @res output, @cSubStr1, @tmp






GO


GRANT EXECUTE ON dbo.[RI_REPORT_FORMULA_4_FSS_PP_RAZD1] TO PUBLIC

GO



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

GO

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

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

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

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

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

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


set nocount on

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


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

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

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

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

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


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

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

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

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

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

	CLOSE PK_List
	DEALLOCATE PK_List

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

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

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

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

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

	IF @varKSlCheck = 0 and @varKSlCascDel = 0

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


	ELSE
	BEGIN

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

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

		ELSE

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

	END

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

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

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

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

CLOSE ConStr
DEALLOCATE  ConStr
drop table #tmp

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

GO


GRANT EXECUTE ON dbo.[XI_CREATE_TEST_REC_FUNC] TO PUBLIC

GO

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

GO

CREATE   PROCEDURE dbo.SA_PRINT_TABEL_NEW
	@varKSnLINKDoc INT,
	@varKSnOption1 INT= 1,
	@varKSnCheck1 INT = 0,
	@nSort3 int = 0 /*сортировка 3*/,
	@nCheck3 tinyint = 0 /*Фио полностью*/,
	@nCheck5 tinyint = 0 /* Пустой табель */,
	@varKSSUBDIV VARCHAR(254) OUTPUT, 
	@varKSSUBDIV_CODE VARCHAR(10) OUTPUT,
	@varKSDIV_CODE VARCHAR(10) OUTPUT, 
	@varKSDIV_NAME VARCHAR(254) OUTPUT,
	@varKSTI_CODE VARCHAR(10) OUTPUT, 
	@varKSTI_NAME VARCHAR(254) OUTPUT,
	@varKSEXP_CODE VARCHAR(10) OUTPUT, 
	@varKSEXP_NAME VARCHAR(254) OUTPUT

AS
BEGIN


	declare @varKSdDate1 DATETIME, @varKSdDate2 DATETIME
	SELECT @varKSdDate1 = PERIOD FROM TABELS WHERE LINK_DOC = @varKSnLINKDoc
	SELECT @varKSdDate1 = dbo.DateBeginOfMonth(@varKSdDate1)
	SELECT @varKSdDate2 = dbo.DateEndOfMonth(@varKSdDate1)

	CREATE TABLE #T_RES00 (
		ID VARCHAR(20),
		LINK_FACE INT, 
		LINK_EMPL INT,
		LINK_SOVM INT,
		FIO VARCHAR(254),
		NAME_EMPL VARCHAR(254),
		TN VARCHAR(10) ,
		SUBDIV_LINK INT, 
		CODE_SUB VARCHAR(10),
		SUBDIV VARCHAR(254) ,
		POST_LINK INT,
		CODE_POST VARCHAR(10),
		POST VARCHAR(254) ,
		LINK_DAY INT,
		SYMB VARCHAR(4),
		DAY_1 CHAR(2),	DAY_2 CHAR(2),	DAY_3 CHAR(2),	DAY_4 CHAR(2),	DAY_5 CHAR(2),
		DAY_6 CHAR(2),	DAY_7 CHAR(2),	DAY_8 CHAR(2),	DAY_9 CHAR(2),	DAY_10 CHAR(2),
		DAY_11 CHAR(2),	DAY_12 CHAR(2),	DAY_13 CHAR(2),	DAY_14 CHAR(2),	DAY_15 CHAR(2),
		DAY_16 CHAR(2),	DAY_17 CHAR(2),	DAY_18 CHAR(2),	DAY_19 CHAR(2),	DAY_20 CHAR(2),
		DAY_21 CHAR(2),	DAY_22 CHAR(2),	DAY_23 CHAR(2),	DAY_24 CHAR(2),	DAY_25 CHAR(2),
		DAY_26 CHAR(2),	DAY_27 CHAR(2),	DAY_28 CHAR(2),	DAY_29 CHAR(2),	DAY_30 CHAR(2),
		DAY_31 CHAR(2),
		
		H_1 NUMERIC(6,2),  H_2 NUMERIC(6,2),  H_3 NUMERIC(6,2),  H_4 NUMERIC(6,2),  H_5 NUMERIC(6,2),  H_6 NUMERIC(6,2),
		H_7 NUMERIC(6,2),  H_8 NUMERIC(6,2),  H_9 NUMERIC(6,2),  H_10 NUMERIC(6,2), H_11 NUMERIC(6,2), H_12 NUMERIC(6,2),
		H_13 NUMERIC(6,2), H_14 NUMERIC(6,2), H_15 NUMERIC(6,2), H_16 NUMERIC(6,2), H_17 NUMERIC(6,2), H_18 NUMERIC(6,2),
		H_19 NUMERIC(6,2), H_20 NUMERIC(6,2), H_21 NUMERIC(6,2), H_22 NUMERIC(6,2), H_23 NUMERIC(6,2), H_24 NUMERIC(6,2),
		H_25 NUMERIC(6,2), H_26 NUMERIC(6,2), H_27 NUMERIC(6,2), H_28 NUMERIC(6,2), H_29 NUMERIC(6,2), H_30 NUMERIC(6,2),
		H_31 NUMERIC(6,2),
		
		HALF_D INT, HALF_H NUMERIC(6,2), 	
		HALF2_D INT, HALF2_H NUMERIC(6,2), 	
		ALL_D INT, ALL_H NUMERIC(6,2), 		
		NONE_DAYS INT, NONE_HOURS NUMERIC(6,2)	,
		
		TYPE_1 INT, TYPE_1H NUMERIC(6,2), TYPE_2H INT, TYPE_2 INT, TYPE_3 INT, TYPE_4 INT, TYPE_5 INT, TYPE_6 INT, 
		TYPE_7 INT, TYPE_8 INT, TYPE_9 INT, TYPE_10 INT, TYPE_11 INT, TYPE_12 INT,

		TYPE_13 INT,	-- ОТРАБОТАНО В МЕСЯЦ СВЕРУХРОЧНЫХ ЧАСОВ
		TYPE_14 INT,	-- ОТРАБОТАНО В МЕСЯЦ НОЧНЫХ ЧАСОВ
		TYPE_15 INT,	-- ОТРАБОТАНО В МЕСЯЦ ЧАСОВ В ВЫХОДНЫЕ И ПРАЗДНИЧНЫЕ ДНИ
	) 

	---
	DECLARE @ISMINUTES TINYINT
	SET @ISMINUTES = DBO.SA_GET_OPTION_BY_CODE('TABEL_OPT10') --УЧЕТ ВРЕМЕНИ В ЧАСАХ И МИНУТАХ

	---
	declare @def_tdlink int, @def_tdname varchar(254), @def_tdsymb varchar(4)
	Select @def_tdlink = LINK, @def_tdname = [NAME], @def_tdsymb = SYMB from dbo.KD_TYP_DAYS where RTRIM(SYMB) = 'Я'

	select  LINK_DOC, NUMBER, DATE, LINK_EMPL, PERIOD, [DAY], 
		SUM([HOUR]) as [HOUR], 
		MAX(WORK_D) as WORK_D,
		MAX(TYP_YAV) AS TYP_YAV,
		(CASE when count(TYPE_DAY) = 1 then MAX(TYPE_DAY) else @def_tdlink end) as TYPE_DAY,
		(CASE when count(SYMB) = 1 then MAX(SYMB) else @def_tdsymb end) as SYMB,	
		(CASE when count(SYMB) = 1 then MAX(TYPE_DATY_NAME) else @def_tdname end) as TYPE_DATY_NAME
	into #tabel 
	from TABEL WHERE LINK_DOC = @varKSnLINKDoc
	group by LINK_DOC, NUMBER, DATE, LINK_EMPL, PERIOD, [DAY]
--	having count(SYMB) > 1
--AND TYPE_DAY not in (Select KOD from [dbo].[SA_TYPES_DOP_TAB])

	--- Информация об отработанных днях
	SELECT W.LINK_UP1, W.LINK_SOVM,
	DAYS_H1 = 
		CASE WHEN SUM(W.D1) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D2) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D3) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D4) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D5) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D6) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D7) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D8) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D9) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D10) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D11) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D12) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D13) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D14) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D15) > 0 THEN 1 ELSE 0 END,

	DAYS_H2 = 
		CASE WHEN SUM(W.D16) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D17) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D18) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D19) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D20) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D21) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D22) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D23) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D24) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D25) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D26) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D27) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D28) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D29) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D30) > 0 THEN 1 ELSE 0 END 
	+	CASE WHEN SUM(W.D31) > 0 THEN 1 ELSE 0 END,

	HORS_H1 = SUM(W.D1) + SUM(W.D2) + SUM(W.D3) + SUM(W.D4) + SUM(W.D5) + SUM(W.D6) + SUM(W.D7) + SUM(W.D8) + SUM(W.D9) + SUM(W.D10) + SUM(W.D11) + SUM(W.D12) + SUM(W.D13) + SUM(W.D14) + SUM(W.D15),
	HORS_H2 = SUM(W.D16) + SUM(W.D17) + SUM(W.D18) + SUM(W.D19) + SUM(W.D20) + SUM(W.D21) + SUM(W.D22) + SUM(W.D23) + SUM(W.D24) + SUM(W.D25) + SUM(W.D26) + SUM(W.D27) + SUM(W.D28) + SUM(W.D29) + SUM(W.D30) + SUM(W.D31)
		
	INTO 
		#WORK_DAYS
	FROM 
		DBO.SA_TABELS_W W
	WHERE 
		LINK_UP = @varKSnLINKDoc
	GROUP BY 
		W.LINK_UP1, W.LINK_SOVM

	--- Информация об отработанных днях
	SELECT W.LINK_UP1, W.LINK_SOVM,
	DAYS_Y7 = 
			CASE WHEN SUM(W.D1) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D2) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D3) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D4) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D5) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D6) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D7) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D8) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D9) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D10) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D11) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D12) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D13) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D14) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D15) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D16) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D17) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D18) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D19) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D20) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D21) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D22) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D23) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D24) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D25) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D26) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D27) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D28) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D29) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D30) > 0 THEN 1 ELSE 0 END 
		+	CASE WHEN SUM(W.D31) > 0 THEN 1 ELSE 0 END
	INTO 
		#WORK_DAYS1
	FROM 
		DBO.SA_TABELS_W W INNER JOIN dbo.TYP_DAYS TD ON TD.LINK = W.LINK_DAY
	WHERE 
		LINK_UP = @varKSnLINKDoc
		AND
		TYP_YAVKA = 7
	GROUP BY 
		W.LINK_UP1, W.LINK_SOVM			

	--- Информация о неявках сотрудников
	SELECT 
		N.LINK_UP1,
		T.WORK_D,
		COUNT_DAYS = 
			CASE WHEN N.D1 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D2 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D3 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D4 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D5 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D6 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D7 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D8 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D9 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D10 = T.LINK THEN 1 ELSE 0 END

			+ CASE WHEN N.D11 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D12 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D13 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D14 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D15 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D16 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D17 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D18 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D19 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D20 = T.LINK THEN 1 ELSE 0 END

			+ CASE WHEN N.D21 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D22 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D23 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D24 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D25 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D26 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D27 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D28 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D29 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D30 = T.LINK THEN 1 ELSE 0 END 
			+ CASE WHEN N.D31 = T.LINK THEN 1 ELSE 0 END 
	INTO 
		#NOTWORK_DAYS
	FROM
		DBO.SA_TABELS_N N, DBO.TYP_DAYS T
	WHERE
		LINK_UP = @varKSnLINKDoc

	---
	INSERT INTO #T_RES00
		(ID,LINK_FACE, LINK_EMPL, LINK_SOVM, FIO, NAME_EMPL, TN, SUBDIV_LINK, CODE_SUB, SUBDIV, POST_LINK, CODE_POST, POST,
		LINK_DAY,
		SYMB,
		DAY_1,  DAY_2,  DAY_3,  DAY_4,  DAY_5,  DAY_6,  DAY_7,  DAY_8,  DAY_9,  DAY_10, 
		DAY_11, DAY_12, DAY_13, DAY_14, DAY_15, DAY_16, DAY_17, DAY_18, DAY_19, DAY_20, 
		DAY_21, DAY_22, DAY_23, DAY_24, DAY_25, DAY_26, DAY_27, DAY_28, DAY_29, DAY_30,
		DAY_31,
		H_1,  H_2, H_3,  H_4,  H_5,  H_6,  H_7,  H_8,  H_9,  H_10, 
		H_11, H_12, H_13, H_14, H_15, H_16, H_17, H_18, H_19, H_20, 
		H_21, H_22, H_23, H_24, H_25, H_26, H_27, H_28, H_29, H_30, 
		H_31,
		HALF_D, HALF_H,
		HALF2_D, HALF2_H,
		ALL_D, ALL_H,
		NONE_DAYS, NONE_HOURS,
		TYPE_1, TYPE_1H, TYPE_2, TYPE_2H, TYPE_3, TYPE_4, TYPE_5, TYPE_6, 
		TYPE_7, TYPE_8, TYPE_9, TYPE_10, TYPE_11, TYPE_12,

		TYPE_13,TYPE_14,TYPE_15

	)
	
	
	
	SELECT 
	
	ID,LINK_FACE, LINK_EMPL, LINK_SOVM, FIO, NAME_EMPL, TN, SUBDIV_LINK, CODE_SUB, SUBDIV, POST_LINK, CODE_POST, POST,
	LINK_DAY = null,
	SYMB = '',
	DAY_1,  DAY_2,  DAY_3,  DAY_4,  DAY_5,  DAY_6,  DAY_7, DAY_8,  DAY_9, DAY_10, 
	DAY_11, DAY_12, DAY_13, DAY_14, DAY_15, DAY_16, DAY_17,DAY_18, DAY_19,DAY_20, 
	DAY_21, DAY_22, DAY_23, DAY_24, DAY_25, DAY_26, DAY_27,DAY_28, DAY_29,DAY_30,
	DAY_31,
	sum(H1),  sum(H2), sum(H3),  sum(H4),  sum(H5),  sum(H6),  sum(H7),  sum(H8),  sum(H9),  sum(H10), 
	sum(H11), sum(H12), sum(H13), sum(H14), sum(H15), sum(H16), sum(H17), sum(H18), sum(H19), sum(H20), 
	sum(H21), sum(H22), sum(H23), sum(H24), sum(H25), sum(H26), sum(H27), sum(H28), sum(H29), sum(H30), 
	sum(H31),
	HALF_D, sum(HALF_H),
	HALF_D2, sum(HALF_H2),
	ALL_D, ALL_H,
	NONE_DAYS, NONE_HOURS,
	TYPE_1, sum(TYPE_1H), sum(TYPE_2), sum(TYPE_2H), sum(TYPE_3), sum(TYPE_4), sum(TYPE_5), sum(TYPE_6), 
	sum(TYPE_7), sum(TYPE_8), sum(TYPE_9), sum(TYPE_10), sum(TYPE_11), sum(TYPE_12),
	sum(TYPE_13),sum(TYPE_14),sum(TYPE_15)

	
	
	
	
	from ( SELECT
		ID = RIGHT( REPLACE(SPACE(20),SPACE(1),'0') + CONVERT(VARCHAR(20),WP.LINK_EMPL),10) +RIGHT( REPLACE(SPACE(20),SPACE(1),'0') + CONVERT(VARCHAR(20),WP.LINK_SOVM),10) ,
		[LINK_FACE] = P.LINK,
		WP.LINK_EMPL,
		WP.LINK_SOVM,
		[FIO]  = (case when coalesce(@nCheck3,0) = 1 then  coalesce(LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(P.FM)) + ' ' + LTRIM(RTRIM(P.IM)) + ' ' + LTRIM(RTRIM(P.OT)),'Не заполнено'))),100), SPACE(100)) 
					else coalesce(LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(FM)) + ' ' + LEFT(LTRIM(RTRIM(IM)),1) + '.' + LEFT(LTRIM(RTRIM(OT)),1) + '.', 'Не заполнено'))),30), SPACE(100)) end),
		[NAME_EMPL] = LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(FM)) + ' ' + LEFT(LTRIM(RTRIM(IM)),1) + '.' + LEFT(LTRIM(RTRIM(OT)),1) + '.', 'Не заполнено'))),30),
		[TN] 		= ISNULL(TE.TAB, SPACE(10)),
		[SUBDIV_LINK] = TE.SUBDIV_LINK,
		[CODE_SUB] = ISNULL( TE.SUBDIV_CODE, SPACE(10) ),
		[SUBDIV] = ISNULL( TE.SUBDIV_NAME, SPACE(254) ),
		[POST_LINK] = WP.POST_LINK,
		[CODE_POST] = ISNULL( WP.POST_CODE, SPACE(10) ),
		[POST] 		= ISNULL( WP.POST_NAME, SPACE(120) ),
		W.LINK_DAY,		
		W.SYMB,
		[DAY_1] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB1, SPACE(2) ) end,
		[DAY_2] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB2, SPACE(2) ) end,
		[DAY_3] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB3, SPACE(2) ) end,
		[DAY_4] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB4, SPACE(2) ) end,
		[DAY_5] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB5, SPACE(2) ) end,
		[DAY_6] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB6, SPACE(2) ) end,
		[DAY_7] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB7, SPACE(2) ) end,
		[DAY_8] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB8, SPACE(2) ) end,
		[DAY_9] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB9, SPACE(2) ) end,
		[DAY_10] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB10, SPACE(2) ) end,

		[DAY_11] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB11, SPACE(2) ) end,
		[DAY_12] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB12, SPACE(2) ) end,
		[DAY_13] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB13, SPACE(2) ) end,
		[DAY_14] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB14, SPACE(2) ) end,
		[DAY_15] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB15, SPACE(2) ) end,
		[DAY_16] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB16, SPACE(2) ) end,
		[DAY_17] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB17, SPACE(2) ) end,
		[DAY_18] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB18, SPACE(2) ) end,
		[DAY_19] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB19, SPACE(2) ) end,
		[DAY_20] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB20, SPACE(2) ) end,

		[DAY_21] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB21, SPACE(2) ) end,
		[DAY_22] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB22, SPACE(2) ) end,
		[DAY_23] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB23, SPACE(2) ) end,
		[DAY_24] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB24, SPACE(2) ) end,
		[DAY_25] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB25, SPACE(2) ) end,
		[DAY_26] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB26, SPACE(2) ) end,
		[DAY_27] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB27, SPACE(2) ) end,
		[DAY_28] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB28, SPACE(2) ) end,
		[DAY_29] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB29, SPACE(2) ) end,
		[DAY_30] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB30, SPACE(2) ) end,
		[DAY_31] =  case when @nCheck5 = 1 then '' else ISNULL( SYMB31, SPACE(2) ) end,

		[H1] = case when @nCheck5 = 1 then 0 else W.D1 end, 
		[H2] = case when @nCheck5 = 1 then 0 else W.D2 end,
		[H3] = case when @nCheck5 = 1 then 0 else W.D3 end,
		[H4] = case when @nCheck5 = 1 then 0 else W.D4 end, 
		[H5] = case when @nCheck5 = 1 then 0 else W.D5 end,
		[H6] = case when @nCheck5 = 1 then 0 else W.D6 end,
		[H7] = case when @nCheck5 = 1 then 0 else W.D7 end,  
		[H8] = case when @nCheck5 = 1 then 0 else W.D8 end, 
		[H9] = case when @nCheck5 = 1 then 0 else W.D9 end, 
		[H10] = case when @nCheck5 = 1 then 0 else W.D10 end,

		[H11] = case when @nCheck5 = 1 then 0 else W.D11 end,
		[H12] = case when @nCheck5 = 1 then 0 else W.D12 end, 
		[H13] = case when @nCheck5 = 1 then 0 else W.D13 end, 
		[H14] = case when @nCheck5 = 1 then 0 else W.D14 end, 
		[H15] = case when @nCheck5 = 1 then 0 else W.D15 end, 
		[H16] = case when @nCheck5 = 1 then 0 else W.D16 end, 
		[H17] = case when @nCheck5 = 1 then 0 else W.D17 end, 
		[H18] = case when @nCheck5 = 1 then 0 else W.D18 end, 
		[H19] = case when @nCheck5 = 1 then 0 else W.D19 end, 
		[H20] = case when @nCheck5 = 1 then 0 else W.D20 end, 

		[H21] = case when @nCheck5 = 1 then 0 else W.D21 end, 
		[H22] = case when @nCheck5 = 1 then 0 else W.D22 end, 
		[H23] = case when @nCheck5 = 1 then 0 else W.D23 end, 
		[H24] = case when @nCheck5 = 1 then 0 else W.D24 end, 
		[H25] = case when @nCheck5 = 1 then 0 else W.D25 end, 
		[H26] = case when @nCheck5 = 1 then 0 else W.D26 end, 
		[H27] = case when @nCheck5 = 1 then 0 else W.D27 end, 
		[H28] = case when @nCheck5 = 1 then 0 else W.D28 end, 
		[H29] = case when @nCheck5 = 1 then 0 else W.D29 end, 
		[H30] = case when @nCheck5 = 1 then 0 else W.D30 end, 
		[H31] = case when @nCheck5 = 1 then 0 else W.D31 end, 
--
		[HALF_D] = case when @nCheck5 = 1 then 0 else isnull(WD.DAYS_H1,0) end, 
		[HALF_H] = case when @nCheck5 = 1 then 0 else isnull(WD.HORS_H1,0) end,

		[HALF_D2] = case when @nCheck5 = 1 then 0 else isnull(WD.DAYS_H2,0) end,
		[HALF_H2] = case when @nCheck5 = 1 then 0 else isnull(WD.HORS_H2,0) end,

		[ALL_D] = case when @nCheck5 = 1 then 0 else isnull(WD.DAYS_H1,0) + isnull(WD.DAYS_H2,0) end,
		[ALL_H] = case when @nCheck5 = 1 then 0 else isnull(WD.HORS_H1,0) + isnull(WD.HORS_H2,0) end,

		[NONE_DAYS] = case when @nCheck5 = 1 then 0 else (case when   W.name NOT like '%часы работы%' then 0 else (SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D IN (4, 5, 6, 7, 8, 9, 10, 13)) end ) end,
		[NONE_HOURS] = case when @nCheck5 = 1 then 0 else 0 end,

		--Дни явок		
		[TYPE_1] = case when @nCheck5 = 1 then 0 else (case when   W.name NOT like '%часы работы%' then 0 else COALESCE(WD.DAYS_H1,0) + COALESCE(WD.DAYS_H2,0) end) end,
		--Часы явок
		[TYPE_1H] =  case when @nCheck5 = 1 then 0 else 
			DBO.MINUTES_TO_NUM( 
			DBO.NUM_TO_MINUTES(W.D1,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D2,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D3,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D4,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D5,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D6,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D7,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D8,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D9,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D10,@ISMINUTES)

		+	DBO.NUM_TO_MINUTES(W.D11,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D12,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D13,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D14,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D15,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D16,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D17,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D18,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D19,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D20,@ISMINUTES)

		+	DBO.NUM_TO_MINUTES(W.D21,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D22,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D23,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D24,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D25,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D26,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D27,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D28,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D29,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D30,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D31,@ISMINUTES)
		,@ISMINUTES) end,

		[TYPE_2] = case when @nCheck5 = 1 then 0 else (SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D = 2) end,		-- командировка (дни)
		[TYPE_2H] = 0,	-- командировка (часы)
		[TYPE_3] = case when @nCheck5 = 1 then 0 else ISNULL((SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D = 3),0) + ISNULL(Y.DAYS_Y7,0) end,		-- повышение квалификации (дни)
		[TYPE_4] = case when @nCheck5 = 1 then 0 else (SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D = 4) end,		-- очередной ежегодный отпуск НЕЯВКА (дни)
		[TYPE_5] = case when @nCheck5 = 1 then 0 else (SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D = 5) end,		-- учебный отпуск НЕЯВКА (дни)
		[TYPE_6] = case when @nCheck5 = 1 then 0 else (SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D = 6) end,		-- больничный НЕЯВКА (дни)
		[TYPE_7] = case when @nCheck5 = 1 then 0 else (SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D IN (7,13)) end, 	-- уход за ребенком НЕЯВКА (дни)
		[TYPE_8] = case when @nCheck5 = 1 then 0 else (SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D = 8) end,		-- с разрешения администрации НЕЯВКА (дни)
		[TYPE_9] = case when @nCheck5 = 1 then 0 else (SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D = 9) end,		-- прогул НЕЯВКА (дни)
		[TYPE_10] = case when @nCheck5 = 1 then 0 else (SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D = 10) end,	-- невыясненные причины НЕЯВКА (дни)
		[TYPE_11] = case when @nCheck5 = 1 then 0 else (case when   W.name NOT like '%часы работы%' then 0 else (SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D IN (11,14)) end ) end,	-- выходные и праздничые НЕЯВКА (дни)
		[TYPE_12] = case when @nCheck5 = 1 then 0 else (SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D = 12) end,
		--
		[TYPE_13] = case when @nCheck5 = 1 then 0 else (SELECT COUNT(*)  FROM #TABEL WHERE LINK_EMPL = T.LINK_EMPL AND WORK_D = 1 and TYP_YAV = 4) end,	-- явка сверхурочно
		[TYPE_14] = case when @nCheck5 = 1 then 0 else (SELECT COUNT(*)  FROM #TABEL WHERE LINK_EMPL = T.LINK_EMPL AND WORK_D = 1 and TYP_YAV = 2) end, -- явка в ночное время
		[TYPE_15] = case when @nCheck5 = 1 then 0 else (SELECT COUNT(*)  FROM #TABEL WHERE LINK_EMPL = T.LINK_EMPL AND WORK_D = 1 and TYP_YAV = 3) end	-- явка в вызодные и праздничные
	FROM 
		DBO.TABELS T 
		INNER JOIN DBO.SA_TABELS_EMPLS TE ON T.LINK = TE.LINK
		INNER JOIN DBO.SA_TABELS_EMPLS_WP WP ON TE.LINK = WP.LINK_UP1
		INNER JOIN DBO.EMPL E ON E.LINK = TE.LINK_EMPL
		INNER JOIN DBO.PERSON P ON P.LINK = E.PERS_LINK
		LEFT JOIN DBO.SA_TABELS_N N ON TE.LINK = N.LINK_UP1
		LEFT JOIN DBO.SA_TABELS_W W ON TE.LINK = W.LINK_UP1 AND W.LINK_SOVM = WP.LINK_SOVM
		LEFT JOIN #WORK_DAYS WD ON TE.LINK = WD.LINK_UP1 AND WD.LINK_SOVM = WP.LINK_SOVM
		LEFT JOIN #WORK_DAYS1 Y ON TE.LINK = Y.LINK_UP1 AND WD.LINK_SOVM = Y.LINK_SOVM
	WHERE 
		T.LINK_DOC = @varKSnLINKDoc
	/*ORDER BY 
		1*/) a 
	GROUP BY  ID,LINK_FACE, LINK_EMPL, LINK_SOVM, FIO, NAME_EMPL, TN, SUBDIV_LINK, CODE_SUB, SUBDIV, POST_LINK, CODE_POST, POST,NONE_DAYS, NONE_HOURS,
	[DAY_1],[DAY_2],[DAY_3],[DAY_4],[DAY_5],[DAY_6],[DAY_7],[DAY_8],[DAY_9],[DAY_10],[DAY_11],[DAY_12],[DAY_13],[DAY_14],[DAY_15],[DAY_16],[DAY_17],[DAY_18],
	[DAY_19],[DAY_20],[DAY_21],[DAY_22],[DAY_23],[DAY_24],[DAY_25],[DAY_26],[DAY_27],[DAY_28],[DAY_29],[DAY_30],[DAY_31],ALL_D, ALL_H,HALF_D, HALF_D2,TYPE_1
	ORDER BY 
		1


IF (SELECT COUNT(DISTINCT SUBDIV_LINK) FROM #T_RES00) <> 1 BEGIN
		SELECT @varKSSUBDIV = '', @varKSSUBDIV_CODE = ''
	END
	ELSE 
		BEGIN
			SELECT TOP 1 @varKSSUBDIV = SUBDIV, @varKSSUBDIV_CODE = CODE_SUB FROM  #T_RES00
		END

	DECLARE 
		@varKSCNT1 INT, @varKSCNT2 INT, @varKSCNT3 INT
	
	SELECT TOP 1 
		@varKSCNT1 = COUNT(DISTINCT LINK_FKR_D), 
		@varKSCNT2 = COUNT(DISTINCT LINK_FKR_T), 
		@varKSCNT3 = COUNT(DISTINCT LINK_FKR_E),
		@varKSDIV_CODE = MAX(CODE_FKR_D),
		@varKSDIV_NAME = MAX(NAME_FKR_D),
		@varKSTI_CODE = MAX(CODE_FKR_T),
		@varKSTI_NAME = MAX(NAME_FKR_T),
		@varKSEXP_CODE = MAX(CODE_FKR_E),
		@varKSEXP_NAME = MAX(NAME_FKR_E)
	FROM DICTIONARY_PAYS_EMPL DPE
	INNER JOIN dbo.PAYS P ON DPE.LINK_PAYS = P.LINK
	INNER JOIN bi_diction_vkr VKR ON VKR.LINK = DPE.LINK_KBK
	INNER JOIN #T_RES00 R ON DPE.LINK_EMPL = R.LINK_EMPL
	where date_begin <= @varKSdDate2
		AND (DATE_END >= @varKSdDate1 OR DATE_END IS NULL) 


		declare @LINK_DEP int
		Set @LINK_DEP = Coalesce( (SELECT TOP 1 ZB_LINK FROM dbo.KS_OPTIONS_ZB), dbo.GetOwnDepLink())

		declare @nAVGCount numeric(18,2), @nMCount numeric(18,2)

		Select @nAVGCount = dbo.sa_ssch_empls(@varKSdDate1, @varKSdDate2, null, 0, 1, 0, DEFAULT)
		Select @nMCount = dbo.sa_sch_empls(@varKSdDate2, null, 0, 1, 0, DEFAULT)


	IF @varKSCNT1 <> 1
		SELECT @varKSDIV_CODE = '', @varKSDIV_NAME = ''
	IF @varKSCNT2 <> 1
		SELECT @varKSTI_CODE = '', @varKSTI_NAME = ''
	IF @varKSCNT3 <> 1
		SELECT @varKSEXP_CODE = '', @varKSEXP_NAME = ''

	SELECT *, @nAVGCount as AVGCount, @nMCount as MCount 
	FROM #T_RES00
	ORDER BY 
		LTRIM(RTRIM(CASE @varKSnOption1 
			WHEN 1 THEN REPLICATE ('0',10 - len(ltrim(rtrim((TN))))) + ltrim(rtrim((TN))) 
			WHEN 2 THEN REPLICATE ('0',10 - len(ltrim(rtrim((CODE_POST))))) + ltrim(rtrim((CODE_POST)))
			WHEN 3 THEN POST
			WHEN 4 THEN FIO
			WHEN 5 THEN REPLICATE ('0',10 - len(ltrim(rtrim((CODE_SUB))))) + ltrim(rtrim((CODE_SUB)))
			WHEN 6 THEN SUBDIV
			ELSE ''
		END)),

		LTRIM(RTRIM(CASE @varKSnCheck1 
			WHEN 2 THEN REPLICATE ('0',10 - len(ltrim(rtrim((TN))))) + ltrim(rtrim((TN))) 
			WHEN 3 THEN REPLICATE ('0',10 - len(ltrim(rtrim((CODE_POST))))) + ltrim(rtrim((CODE_POST)))
			WHEN 4 THEN POST
			WHEN 5 THEN FIO
			WHEN 6 THEN REPLICATE ('0',10 - len(ltrim(rtrim((CODE_SUB))))) + ltrim(rtrim((CODE_SUB)))
			WHEN 7 THEN SUBDIV
			ELSE ''
		END)),
		
		LTRIM(RTRIM(CASE @nSort3 
			WHEN 2 THEN '' + REPLICATE ('0',10 - len(ltrim(rtrim((TN))))) + ltrim(rtrim((TN))) 
			WHEN 3 THEN '' +REPLICATE ('0',10 - len(ltrim(rtrim((CODE_POST))))) + ltrim(rtrim((CODE_POST)))
			WHEN 4 THEN '' +POST
			WHEN 5 THEN '' +FIO
			WHEN 6 THEN '' +REPLICATE ('0',10 - len(ltrim(rtrim((CODE_SUB))))) + ltrim(rtrim((CODE_SUB)))
			WHEN 7 THEN '' +SUBDIV
			ELSE ''
		END))

END












GO


GRANT EXECUTE ON dbo.[SA_PRINT_TABEL_NEW] TO PUBLIC

GO




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

GO

CREATE PROCEDURE [dbo].[SD_U_NDFL_FILL]
	@varKSlinkEmpl	 int,  
	@varKSRef_Pay  int, 	 
	@varKSDate datetime, 	 
	@varKSLinkVKR int,
	@varKSLinkEKR int,	
	@varKSfl int = 0

AS 
SET NOCOUNT ON
DECLARE @varKSMonth int, 
	  @varKSYear int, 
	  @varKSLINK_FACE int, 
	  @varKSPred_Mesto_Rab numeric(15,2), 
	  @varKSFlagD int,
	  @Status int	-->>NEW

IF @varKSfl>0
	SET @varKSfl = 1

DECLARE @NDFL_OPT8 TINYINT --Разрешить отрицательные суммы налога
SET @NDFL_OPT8 = dbo.sa_get_option_by_code('NDFL_OPT8')

SET @varKSMonth= month(@varKSDate)
SET @varKSYear = year(@varKSDate)

declare @DEP_LINK int
SELECT @DEP_LINK = DEP_LINK, @varKSLINK_FACE = PERS_LINK FROM DBO.EMPL WHERE LINK = @varKSlinkEmpl

DECLARE @Link211EKR int
Set @Link211EKR = ISNULL((SELECT TOP 1 LINK FROM KOSGU WHERE CODE = '211'),0)

if @varKSfl = 1
	Select [Организация] = [NAME] from dbo.DEPARTMENTS where link = @DEP_LINK

Select @Status= [STATUS] from dbo.ITEM_MOVE where ACTIVE = 1 and EMPL_LINK = @varKSlinkEmpl	-->>NEW

SET @varKSFlagD = 0

DECLARE @DIS_DATE DATETIME
SET @DIS_DATE = COALESCE((SELECT TOP 1 IDF.DIS_DATE FROM DBO.ITEM_DIS_FACE IDF with (nolock) WHERE IDF.EMPL_LINK = @varKSlinkEmpl AND IDF.ACTIVE=1),'29990101')

SET @varKSPred_Mesto_Rab = 0
IF YEAR(dbo.kd_DateBeginWork(@varKSlinkEmpl,@varKSDate)) = @varKSYear
BEGIN

	SET @varKSPred_Mesto_Rab =(SELECT ISNULL(SUM(SUMMA_TYP_INCOMS),0) FROM dbo.SD_EMPL_PREV_DOHOD WHERE LINK_EMPL = @varKSlinkEmpl)
			- (SELECT ISNULL(SUM(SUMMA_DED),0) FROM dbo.SD_EMPL_PREV_DED WHERE LINK_EMPL = @varKSlinkEmpl and 
					LINK_DED IN (SELECT distinct REF_DEDUCT FROM DICTIONARY_TYP_INCOMS where REF_DEDUCT is not null) )
	IF @varKSPred_Mesto_Rab IS null or @varKSPred_Mesto_Rab < 0
		SET @varKSPred_Mesto_Rab = 0
	SET @varKSFlagD = 1
END


IF @varKSfl = 1 
	SELECT Case @Status when 1 then 'Основной сотрудник' when 2 then 'Внутренний совместитель' else 'Внешний совместитель' end + 
	': '+rtrim(TAB)+ ' ' +rtrim(dbo.sd_GetEmplName(LINK))+  ', месяц ' + rtrim(convert(varchar(100),@varKSMonth))+ 
			 ', год ' +rtrim( convert(varchar(100),@varKSYear )) as 'Исходные данные'  FROM dbo.EMPL WHERE LINK = @varKSlinkEmpl   
IF  @varKSfl = 1 
	SELECT 'Совокупный доход: '+ rtrim(isnull(convert(varchar(100),(select sum(summa_TYP_INCOMS) from dbo.SD_EMPL_PREV_DOHOD where link_empl =@varKSlinkEmpl)),'0')) + ' , предоставленные вычеты: '+
	 rtrim( isnull( convert(varchar(100),(select sum(summa_ded) from dbo.SD_EMPL_PREV_DED where link_empl =@varKSlinkEmpl and LINK_DED NOT IN (SELECT distinct REF_DEDUCT FROM DICTIONARY_TYP_INCOMS where REF_DEDUCT is not null) )),'0'))
	+ ' , предоставлены скидки: '+
	 rtrim( isnull( convert(varchar(100),(select sum(summa_ded) from dbo.SD_EMPL_PREV_DED where link_empl =@varKSlinkEmpl and LINK_DED IN (SELECT distinct REF_DEDUCT FROM DICTIONARY_TYP_INCOMS where REF_DEDUCT is not null) )),'0'))  as 'Данные с предыдущего места работы'


/*Доходы*/
Declare @isPrevPreiod tinyint
--Суммы начислений включать в базу расчета в том месяце, в котором он был начислен.                   
Set @isPrevPreiod = dbo.sa_get_option_by_code('NDFL_OPT6')
Set @isPrevPreiod = 1 - ISNULL(@isPrevPreiod,0)

Declare @SJC table (link_empl int, link_pays int, link_vkr int, link_ekr int, typ_per tinyint, typ_oper tinyint, summa numeric(18,2), period_begin datetime, date1 datetime)

Insert into @SJC (link_empl, link_pays, link_vkr, link_ekr, typ_per, typ_oper, summa, period_begin, date1)
Select 
	JC.LINK_EMPL, P.LINK, link_vkr, ISNULL(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_PREMIUM' and d.code <> 'DOCUMENTS_ADD_PERCENT'
					then JC.DATE_BEGIN else JC.period_begin 
				end) 
			end),
	JC.DATE_BEGIN
from 
	dbo.CALCULATE_JURNAL JC 
	INNER JOIN dbo.EMPL E ON JC.LINK_EMPL = E.LINK
	INNER JOIN dbo.PAYS P ON JC.LINK_PAYS = P.LINK
	LEFT JOIN (Select d.link, o.code from sdoc d inner join dbo.s_objects o on d.object = o.link) d on jc.LINK_DOC = d.link
where
	P.OBJECT = 1
	AND
	P.LINK in (Select TAX_LINK from dbo.group_tax(@varKSRef_Pay)) 
	AND (
			@isPrevPreiod = 0 and @varKSMonth >= month(JC.PERIOD_BEGIN) and @varKSYear = year(JC.PERIOD_BEGIN)
		or 
			@isPrevPreiod = 1 
			and (@varKSMonth >= month(JC.DATE_BEGIN) or @varKSMonth >= month(JC.PERIOD_BEGIN) )
			and (@varKSYear = year(JC.DATE_BEGIN) or @varKSYear = year(JC.PERIOD_BEGIN) )
		)
	AND  
		(	-->>NEW
		@Status <> 1 AND JC.LINK_EMPL = @varKSlinkEmpl /*Если не основной сотрудник, то доход по своему табельному номеру*/
		or
		@Status = 1 AND E.PERS_LINK = @varKSLINK_FACE /*Если основной сотрудник, то доход по всем табельным номерам*/
		)	
	AND JC.LINK_DEP = @DEP_LINK 
	

DECLARE @varKSVal TABLE 
([MONTH] 		[int],
 [EMPL_SUMMA] 		[numeric](19, 2),
 [SUMMA] 		[numeric](19, 2),
 [EMPL_SUMMA_VKR]	[numeric](19, 2),
 [SUMMA_VKR]		[numeric](19, 2),
 [SUMMA_M]		[numeric](19, 2),
 [SUMMA_M_211]  [numeric](19, 2), --для расчёта коэффициента при предоставлении вычета только по 211 ЭКР
 [SUMMA_M_VKR]		[numeric](19, 2)
 --[SUMMA_M_VKR1]		[numeric](19, 2)
)

INSERT INTO @varKSVal([MONTH],[SUMMA],[EMPL_SUMMA], [SUMMA_VKR], [EMPL_SUMMA_VKR],[SUMMA_M],[SUMMA_M_211],[SUMMA_M_VKR])--,[SUMMA_M_VKR1])
SELECT T.NUM AS [MONTH],  
		[SUMMA] = SUM(SJ.SUMMA), 
		[EMPL_SUMMA] = SUM(CASE WHEN SJ.LINK_EMPL = @varKSlinkEmpl THEN SJ.SUMMA ELSE 0 END),
		[SUMMA_VKR] = SUM(CASE WHEN SJ.LINK_VKR = @varKSLinkVKR   AND SJ.LINK_EKR = @varKSLinkEKR THEN SJ.SUMMA ELSE 0 END), 
		[EMPL_SUMMA_VKR] = SUM(CASE WHEN SJ.LINK_VKR = @varKSLinkVKR AND SJ.LINK_EMPL = @varKSlinkEmpl AND SJ.LINK_EKR = @varKSLinkEKR THEN SJ.SUMMA ELSE 0 END), 
		[SUMMA_M] = SUM(CASE WHEN Month(sj.period_begin) = T.NUM AND SJ.LINK_EMPL = @varKSlinkEmpl THEN SJ.SUMMA ELSE 0 END), 
		[SUMMA_M_211] = SUM(CASE WHEN Month(sj.period_begin) = T.NUM AND SJ.LINK_EMPL = @varKSlinkEmpl AND SJ.LINK_EKR = @Link211EKR THEN SJ.SUMMA ELSE 0 END), 
		[SUMMA_M_VKR] = SUM(CASE WHEN Month(sj.period_begin) =T.NUM AND SJ.LINK_VKR = @varKSLinkVKR AND SJ.LINK_EMPL = @varKSlinkEmpl AND SJ.LINK_EKR = @varKSLinkEKR THEN SJ.SUMMA ELSE 0 END)
--		[SUMMA_M_VKR1] = SUM(CASE WHEN Month(sj.period_begin) =T.NUM AND SJ.LINK_VKR = @varKSLinkVKR AND SJ.LINK_EMPL = @varKSlinkEmpl THEN SJ.SUMMA ELSE 0 END)
FROM dbo.MONTHS T, @SJC SJ
WHERE SJ.TYP_OPER = 1 AND T.NUM <= @varKSMonth
		AND T.NUM >= Month(sj.period_begin)
		AND  @varKSYear = Year(sj.period_begin)
GROUP BY  T.NUM

if @varKSfl = 1 
	select [month] as [Месяц], [summa] as [Сумма ФЛ с нач года ],summa_vkr as [Сумма ФЛ с нач года по ВКР], summa_m as [Сумма сотр за месяц], 
	summa_m_vkr as [Сумма сотр за месяц по ВКР]  from @varKSVal

/*Доходы для вычетов*/
DECLARE @varKSVal2 TABLE 
([MONTH] 		[int],
 [SUMMA] 		[numeric](19, 2),
 [EMPL_SUMMA] 		[numeric](19, 2),
 [SUMMA_VKR]		[numeric](19, 2),
 [EMPL_SUMMA_VKR]	[numeric](19, 2),
 [SUMMA_M]		[numeric](19, 2),
 [SUMMA_M_VKR]		[numeric](19, 2))


INSERT INTO @varKSVal2([MONTH],[SUMMA],[EMPL_SUMMA], [SUMMA_VKR], [EMPL_SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR])
SELECT T.NUM AS [MONTH],
		[SUMMA] = SUM(SJ.SUMMA),
		[EMPL_SUMMA] = SUM(CASE WHEN SJ.LINK_EMPL = @varKSlinkEmpl THEN SJ.SUMMA ELSE 0 END),
		[SUMMA_VKR] = SUM(CASE WHEN SJ.LINK_VKR = @varKSLinkVKR AND SJ.LINK_EKR = @varKSLinkEKR THEN SJ.SUMMA ELSE 0 END),
		[EMPL_SUMMA_VKR] = SUM(CASE WHEN SJ.LINK_VKR = @varKSLinkVKR AND (SJ.LINK_EMPL = @varKSlinkEmpl) AND SJ.LINK_EKR = @varKSLinkEKR THEN SJ.SUMMA ELSE 0 END), 
		[SUMMA_M] = SUM(CASE WHEN (CASE WHEN SJ.TYP_PER=1 THEN Month(sj.period_begin) ELSE MONTH(sj.DATE1) END)=T.num AND SJ.LINK_EMPL = @varKSlinkEmpl then sj.summa else 0 end),
		[SUMMA_M_VKR] = SUM(CASE WHEN ((CASE WHEN SJ.TYP_PER=1 THEN Month(sj.period_begin) ELSE MONTH(sj.DATE1) END)=T.num)
							AND sj.link_vkr = @varKSLinkVKR AND SJ.LINK_EMPL = @varKSlinkEmpl AND SJ.LINK_EKR = @varKSLinkEKR THEN SJ.SUMMA ELSE 0 END)
FROM dbo.MONTHS T, @SJC SJ
WHERE SJ.TYP_OPER = 1 
		AND T.NUM <= @varKSMonth AND
		T.NUM >=(CASE WHEN SJ.TYP_PER=1 THEN Month(sj.period_begin) ELSE MONTH(SJ.DATE1) END)
		AND @varKSYear =(case WHEN SJ.TYP_PER=1 THEN Year(sj.period_begin) ELSE YEAR(sj.DATE1) END)
GROUP BY  T.NUM

insert into @varKSVal2 ([MONTH],[SUMMA],[EMPL_SUMMA], [SUMMA_VKR], [EMPL_SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR])
select T.NUM, 0, 0, 0, 0, 0, 0  from dbo.MONTHS T where T.NUM < (Select min([month]) from @varKSVal2)

if @varKSfl = 1 
	select [month] as [Месяц], [summa] as [Сумма ФЛ с нач года], @varKSPred_Mesto_Rab as [Сумма ФЛ с предыдущего места работы], summa_vkr as [Сумма ФЛ с нач года по ВКР ], summa_m as [Сумма сотр за месяц], 
	summa_m_vkr as [Сумма сотр за месяц по ВКР]  from @varKSVal2 order by [month]

/*Какие бывают скидки*/
if @varKSfl=1 
   select code as [Код вычета], name as [Наименование вычета], SUMMA as [Сумма] from dbo.Salary_deductions(@varKSDate) WHERE TYPE = 5


/*
Если это не внешний совместитель, то Скидки и вычеты предоставляем только по основному табельному номеру
Если это внешний совместитель, предоставляем скидки
*/

/*Какие скидки у физ.лица*/
DECLARE @varKSTemp1 TABLE 
([NUM] 			[int],
 [REF_PAY]		[int],	
 [MP]		 	[numeric](19, 2),
 [MP_M]			[numeric](19, 2),
 [MP_M_VKR]		[numeric](19, 2),
 [PREDEL]		[numeric](19, 2))

--Расчет скидок
INSERT INTO @varKSTemp1 ([NUM],[REF_PAY],[MP],[MP_M],[MP_M_VKR],[PREDEL])
SELECT m.num,T1.REF_PAY,
	/*Годовая сумма дохода со скидкой по физ.лицу*/
	[mp] = SUM(case when Month(sj.period_begin)<=m.num then SJ.summa else 0 end), 
	/*Месячная сумма дохода со скидкой по физ.лицу*/
	[mp_m] = sum(case when Month(sj.period_begin)=m.num then (case when Month(sj.period_begin)<=m.num then SJ.summa else 0 end) else 0 end),
	/*Месячная сумма дохода со скидкой по физ. лицу  в разрезе КБК*/
	[mp_m_vkr] = sum(case when Month(sj.period_begin) = m.num AND sj.link_vkr = @varKSLinkVKR AND SJ.LINK_EKR = @varKSLinkEKR then (case when Month(sj.period_begin)<=m.num then SJ.summa else 0 end) else 0 end),
	[PREDEL] = T1.SUMMA -(case when @varKSFlagD = 1 then isnull((select sum(summa_ded) from dbo.SD_EMPL_PREV_DED where LINK_DED = T1.REF_PAY and  link_empl=@varKSlinkEmpl),0)  else 0 end) 
FROM 
	dbo.MONTHS M, @SJC SJ, dbo.Salary_deductions(@varKSDate) T1
WHERE  
	Year(sj.period_begin) = @varKSYear and m.num<=@varKSMonth AND T1.TYPE = 6 --Тип вычета "Скидка на материальную помощь"
	AND T1.REF_PAY = (select ref_deduct  from dbo.DICTIONARY_TYP_INCOMS where link = (select LINK_INC from dbo.PAYS where LINK = SJ.LINK_PAYS)) 
	AND @Status in (1 /*Основной*/, 3 /*Внешний совместитель*/) AND SJ.LINK_EMPL = @varKSlinkEmpl
GROUP BY m.num, T1.REF_PAY, T1.SUMMA

IF @varKSfl=1 
	select [num] as [Месяц], [Вычет] = (select name from diction where link = ref_pay), [mp] as [Сумма ФЛ с нач года], mp_m as [Сумма ФЛ за месяц], 
	mp_m_vkr as [Сумма ФЛ за месяц по ВКР], predel as [Предел]  from @varKSTemp1

DECLARE @varKSTemp2 TABLE 
([NUM] 			[int],
 [REF_PAY]		[int],	
 [MP]		 	[numeric](19, 2),
 [MP_M]			[numeric](19, 2),
 [MP_M_VKR]		[numeric](19, 2), [PREDEL]		[numeric](19, 2),
 [SALDO]		[numeric](19, 2),
 [KOEF] 		[numeric](19, 4))

INSERT INTO @varKSTemp2 ([NUM],[REF_PAY],[MP],[MP_M],[MP_M_VKR],[PREDEL],[SALDO],[KOEF])
SELECT T1.NUM,T1.REF_PAY,T1.MP,T1.MP_M,T1.MP_M_VKR,T1.PREDEL, 
	[SALDO] = (CASE WHEN PREDEL < 0 THEN 0 ELSE PREDEL END) - ISNULL((select sum(mp_m) from @varKSTemp1 T2 where T2.num < T1.num and T2.REF_PAY = T1.REF_PAY),0),
	[KOEF] =  (CASE WHEN MP_M = 0 THEN 0 ELSE MP_M_VKR/MP_M END)
FROM @varKSTemp1 T1

DECLARE @varKSTemp3 TABLE 
([NUM] 			[int],
 [REF_PAY]		[int],	
 [MP_M]			[numeric](19, 2),
 [MP_M_VKR]		[numeric](19, 2),
 [KOEF] 		[numeric](19, 4),
 [DED]			[numeric](19, 2)
  )

INSERT INTO @varKSTemp3 ([NUM],[REF_PAY],[MP_M],[MP_M_VKR],[KOEF],[DED])
SELECT [NUM],[REF_PAY],[MP_M],[MP_M_VKR],[KOEF], 
	   [DED] = 	case when SALDO < 0 then 
				- case when (CASE WHEN PREDEL < 0 THEN 0 ELSE PREDEL END) - ISNULL(MP,0) > 0	then
					(CASE WHEN PREDEL < 0 THEN 0 ELSE PREDEL END) - ISNULL(MP,0) 
					else 0
				end
			else
				(CASE WHEN MP_M > SALDO THEN SALDO ELSE MP_M END)
			end
FROM @varKSTemp2 

/*Очитстка от мусора: были рассчитаны вычеты и скидки с КБК, которые теперь в этом году больше не используются.
Врезультате эти суммы вычетов не очищаются при расчете и вылазят в 2НДФЛ*/
delete
from 
	dbo.SAL_DED_MONTH
where
	YEAR(dbo.SAL_DED_MONTH.DATE_DED) = YEAR(@varKSDate)
	and
	not exists (
		Select j.LINK 
		from dbo.calculate_jurnal j
		where 
			j.link_pays in (Select TAX_LINK from dbo.group_tax(@varKSRef_Pay)) 
			and YEAR(j.PERIOD_BEGIN) = YEAR(@varKSDate)
			and j.link_empl = dbo.SAL_DED_MONTH.link_empl and j.LINK_VKR = dbo.SAL_DED_MONTH.LINK_VKR
	)

/*Удалить все вычеты и скидки по сотруднику, чтобы затем вновь рассчитать их*/
DELETE FROM dbo.SAL_DED_MONTH
WHERE 
	LINK_EMPL = @varKSlinkEmpl 
	AND LINK_VKR = @varKSLinkVKR 
	AND ISNULL(LINK_EKR,@varKSLinkEKR) = @varKSLinkEKR 
	AND YEAR(DATE_DED) = YEAR(@varKSDate) 
	AND MONTH(DATE_DED) <= MONTH(@varKSDate) 

/*Заново рассчитать годовые скидки*/
INSERT INTO dbo.SAL_DED_MONTH (LINK_EMPL,REF_DED,SUMMA,DATE_DED,LINK_VKR,LINK_EKR,TYPE)
SELECT [LINK_EMPL] = @varKSlinkEmpl,
		 [REF_DED]   = T.REF_PAY,
		 [SUMMA] 	 = ISNULL(T.DED,0) * ISNULL(T.KOEF,1),
		 [DATE_DED]  = dbo.ConvertDMY2Date(1,t.num,year(@varKSDate)),
		 [LINK_VKR]	 = @varKSLinkVKR,
		 [LINK_EKR]	 = @varKSLinkEKR,
		 [TYPE] = 2
FROM @varKSTemp3 T WHERE T.MP_M_VKR <> 0 AND T.DED <> 0 

/* Скидки */

DECLARE @varKSTotTab TABLE
([MONTH] 		[int],
 [EMPL_SUMMA]		[numeric](19, 2), --
 [EMPL_SUMMA_VKR]	[numeric](19, 2), --
 [SUMMA_VKR]		[numeric](19, 2),
 [SUMMA_M]		[numeric](19, 2),
 [SUMMA_M_211]  [numeric](19, 2), --для расчёта коэффициента при предоставлении вычета только по 211 ЭКР
 [SUMMA_M_VKR]		[numeric](19, 2), --для каждого ЭКР, ВКР
 [DED_M_ALL] 		[numeric](19, 2),
 --[DED_M_ALL_211] 	[numeric](19, 2), --для расчёта коэффициента при предоставлении вычета только по 211 ЭКР
 [DED]			[numeric](19, 2),
 [DED_M]		[numeric](19, 2),
 [DED0]			[numeric](19, 2)
 ) 

/* Вычеты делятся между КБК пропорционально с помощью коэффициентов пропорциональности */
INSERT INTO @varKSTotTab([MONTH], [EMPL_SUMMA], [EMPL_SUMMA_VKR], [SUMMA_VKR],[SUMMA_M],[SUMMA_M_211],[SUMMA_M_VKR],[DED_M_ALL],[DED],[DED_M],DED0)
SELECT 	
		M.[NUM], 
		ISNULL(T1.EMPL_SUMMA,0), 
		ISNULL(T1.[EMPL_SUMMA_VKR],0), 
		ISNULL(T1.[SUMMA_VKR],0), 
		ISNULL(T1.[SUMMA_M],0),
		ISNULL(T1.[SUMMA_M_211],0),	 
		ISNULL(T1.[SUMMA_M_VKR],0),
	 	[DED_M_ALL] = ISNULL((SELECT SUM(T2.DED) FROM @varKSTemp3 T2 WHERE T2.NUM=M.[NUM]),0),
		[DED] 		= ISNULL((SELECT SUM(T2.DED * T2.KOEF) FROM @varKSTemp3 T2 WHERE T2.NUM <= M.[NUM]),0),
		[DED_M] 	= ISNULL((SELECT SUM(T2.DED * T2.KOEF) FROM @varKSTemp3 T2 WHERE T2.NUM = M.[NUM]),0),
		[DED0] 		= ISNULL((SELECT SUM(T2.DED) FROM @varKSTemp3 T2 WHERE T2.NUM <= M.[NUM]),0)
FROM  dbo.months M LEFT JOIN @varKSVal T1 on M.num = T1.[MONTH] 
WHERE M.NUM <= @varKSMonth
GROUP BY M.[NUM], T1.[EMPL_SUMMA], T1.[EMPL_SUMMA_VKR], T1.SUMMA_VKR, T1.SUMMA_M_VKR, T1.SUMMA_M, T1.SUMMA_M_211

IF @varKSfl=1 
select [month] as [Месяц],summa_vkr as [Сумма ФЛ с нач года по ВКР], summa_m as [Сумма сотр за месяц], 
	summa_m_vkr as [Сумма за месяц по ВКР], ded_m_all as [Скидки всего], ded as [Скидки всего по ВКР], ded_m as [Скидки за месяц по ВКР]  from @varKSTotTab

DECLARE @varKSTT TABLE
([REF_PAY] 	[int],
 [PREDEL]	[numeric](19, 2),
 [SUMMA]		[numeric](19, 2),
 [MONTHEND]	[int])

--- Вычеты и скидки: Определение достижения предела
INSERT INTO @varKSTT ([REF_PAY],[PREDEL],[SUMMA],[MONTHEND])
SELECT TD.REF_PAY,TD.PREDEL,TD.SUMMA, 
		[MonthEnd] =  (SELECT TOP 1 T1.[MONTH] FROM  @varKSVal2 T1 
 							WHERE (SUMMA+ISNULL(@varKSPred_Mesto_Rab,0) - ISNULL((select sum(ded) from @varKSTemp3 where num<=T1.[MONTH]),0))
							<(CASE WHEN TD.PREDEL = 0 THEN 999999999999 ELSE TD.PREDEL END)
							ORDER BY T1.[MONTH] DESC)
FROM 
	dbo.Salary_deductions(@varKSDate ) as TD where TYPE = 1

DECLARE @varKSTotal TABLE
( link int not null IDENTITY(1,1),
 [REF_PAY] 	[int],
 [MONTH_BEGIN]	[int],
 [MONTH_END]	[int],		
 [SUMMA]	[numeric](19, 2),
[SUMMA_V] numeric(18,2), [SUMMA_D] numeric(18,2), [Ostatok_V] numeric(18,2)-- Для определения факт вычетов
)

--Предоставление стандартных вычетов
--'Всегда,При наличии любого дохода за месяц,При наличии только положительного дохода за месяц'
declare @NDFL_OPT5 tinyint
SET @NDFL_OPT5 =  ISNULL((SELECT top 1 CONVERT(INT,VALUE) FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'NDFL_OPT5')),1)


INSERT INTO @varKSTotal ([REF_PAY],[MONTH_BEGIN],[MONTH_END],[SUMMA],[SUMMA_V],[SUMMA_D])
SELECT 		
	[REF_PAY] 		= TT.REF_PAY, 
	[MONTH_BEGIN]	= M.[NUM],--SDE.MONTH_BEGIN,
	[MONTH_END] 	= M.[NUM],--(CASE WHEN TT.MonthEnd> SDE.MONTH_END THEN SDE.MONTH_END ELSE TT.MonthEnd END),
	[SUMMA] 		= TT.SUMMA,
	[SUMMA_V]		= TT.SUMMA,	-- Для определения факт вычетов
	[SUMMA_D]		= ISNULL(D.[summa_m],0)	-- Для определения факт вычетов
				- ISNULL((select sum(ded) from @varKSTemp3 where num = M.[NUM]),0)
FROM @varKSTT TT,
	(SELECT link_ded, month_begin,month_end FROM DBO.salary_ded_empl(@varKSlinkEmpl,@varKSMonth, @varKSYear)T1 WHERE t1.month_begin<=t1.month_end) SDE ,  --t1.month_end
	dbo.Months M
	left join @varKSVal2 D on M.NUM = D.[month] -- Для определения факт вычетов
--	left join @varKSVal V /*Доходы*/
--			on V.[month] = M.[NUM]
WHERE SDE.LINK_DED =TT.REF_PAY and TT.MonthEnd >= M.[NUM] --TT.MonthEnd >= SDE.month_begin
	and 	@Status in (1 /*Основной*/, 3 /*Внешний совместитель*/)	-->>NEW
	and 	M.[NUM] between SDE.MONTH_BEGIN and SDE.MONTH_END
	and		(@NDFL_OPT5 = 1 or @NDFL_OPT5 = 2 and D.SUMMA_M <> 0 or @NDFL_OPT5 = 3 and D.SUMMA_M > 0)
	AND (D.SUMMA_M <> 0 OR dbo.DateEndOfMonth(@DIS_DATE) >= dbo.DateEndOfMonth(@varKSDate))
order by M.NUM

---Вычеты от взносов в пенсионый фонд
INSERT INTO @varKSTotal ([REF_PAY],[MONTH_BEGIN],[MONTH_END],[SUMMA],[SUMMA_V],[SUMMA_D])
select 
	TA.LINK_DED, MONTH(cj.PERIOD_BEGIN), MONTH(cj.PERIOD_BEGIN), SUM(SUMMA),SUM(SUMMA), (SELECT MAX(A.SUMMA_D) FROM @varKSTotal A WHERE A.MONTH_BEGIN = MONTH(cj.PERIOD_BEGIN))
from 
	dbo.EMPL E inner join dbo.calculate_jurnal cj on e.link = cj.link_empl
	inner join dbo.TAX2_APP TA on TA.LINK_UP = CJ.LINK_PAYS
where 
	year(period_begin) = @varKSYear
	and
	E.LINK = @varKSlinkEmpl	
	and
	@Status in (1 /*Основной*/, 3 /*Внешний совместитель*/) and MONTH(cj.PERIOD_BEGIN) <= Month(@varKSDate) 
	and
	ISNULL(TA.LINK_DED,0) > 0
GROUP BY 
	TA.LINK_DED, MONTH(cj.PERIOD_BEGIN)

/*
Раздение на части сумм вычетов, на которые человек имеет право: фактически предоставленные и остаток непредоставленных вычетов
*/
declare @VychOpt1 int -- ограничивать месячный вычет месячным доходом
declare	@VychOpt2 int  -- месячный вычет давать с нарастающим итогом (компенсировать не предоставленный вычет, если в определенном месяце сотрудник не получал дохода)

if @NDFL_OPT5 > 1 begin
	Set @VychOpt1 = ISNULL((SELECT top 1 CONVERT(INT,VALUE) FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'NDFL_OPT1')),0)
	Set @VychOpt2 = ISNULL((SELECT top 1 CONVERT(INT,VALUE) FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'NDFL_OPT2')),0)
end
else
	Select @VychOpt1 = 0, @VychOpt2 = 0

IF @VychOpt1 = 1 --Если ограничивать месячный вычет месячным доходом
BEGIN

	DECLARE @Cur1 CURSOR, @MES tinyint, @REF_V int, @SUMMA_V numeric(18,2), @SUMMA_D numeric(18,2), @Ostatok_V numeric(18,2), @Ostatok numeric(18,2), @Ostatok_m numeric(18,2), @link int
	Declare @SumVPred numeric(18,2) --Сумма уже предоставленных вычетов в отчетном месяце
	SET @Cur1 = CURSOR FORWARD_ONLY

	FOR select link, MONTH_BEGIN, REF_PAY, SUMMA_V, SUMMA_D, Ostatok_V from @varKSTotal order by link
	
	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @link, @MES, @REF_V, @SUMMA_V, @SUMMA_D, @Ostatok_V
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			Set @Ostatok = ISNULL((Select Sum(Ostatok_V)  from @varKSTotal 
				where ((@VychOpt2 = 1 and MONTH_BEGIN <= @MES) -- ограниченный месячным доходом вычет давать с нарастающим итогом (компенсировать не предоставленный вычет)
					or (@VychOpt2 = 0 and MONTH_BEGIN = @MES)) -- ограниченный месячным доходом вычет давать без нарастающего итога
					and link < @link and REF_PAY = @REF_V) ,0)
				
			Set @Ostatok_m = ISNULL((Select Sum(Ostatok_V)  from @varKSTotal where Ostatok_V > 0 and MONTH_BEGIN = @MES and link < @link),0)
			Set @SUMMA_V = ISNULL((Select Sum(SUMMA_V)  from @varKSTotal where MONTH_BEGIN = @MES and link <= @link),0)
			Set @SumVPred = ISNULL((Select Sum(SUMMA_V)  from @varKSTotal where MONTH_BEGIN = @MES and link < @link),0)
	
			update @varKSTotal
			Set 	SUMMA_V = (case when ISNULL(@SUMMA_V,0) + @Ostatok > ISNULL(SUMMA_D,0) 
					then ISNULL(SUMMA_D,0) - @SumVPred
					else (case when @Ostatok_m = 0 then ISNULL(@SUMMA_V,0) + @Ostatok - @SumVPred else 0 end) 
				end),
				Ostatok_V = (case when ISNULL(@SUMMA_V,0) + @Ostatok > ISNULL(SUMMA_D,0)
							then ISNULL(@SUMMA_V,0) - ISNULL(SUMMA_D,0)
							else  - @Ostatok
						end)
			where link = @link

		END
	
		FETCH NEXT FROM @Cur1 INTO @link, @MES, @REF_V, @SUMMA_V, @SUMMA_D, @Ostatok_V
	END
	
	CLOSE @Cur1
	DEALLOCATE @Cur1

	IF @varKSfl=1 
	select [Вычет] = (select  rtrim(sname) + ' ' + LEFT(rtrim(name),100) from dbo.DICTIONARY_TYP_DEDUCTION where link = REF_PAY),
		month_begin as [Месяц начала], month_end as [Месяц окончания], summa as [Сумма вычета по НК], summa_v as [Сумма вычета факт], Ostatok_V as [Изменение остатка вычетов] from @varKSTotal order by month_begin,  REF_PAY
	
	update @varKSTotal 
	Set summa = summa_v
END
/**/

/* ^^^^^^ Имущественные вычеты - Начало расчета ^^^^^^^^*/

declare @VychOpt9 int -- имущественный вычет предоставлять с даты регистрации уведомсления
Set @VychOpt9 = ISNULL((SELECT top 1 CONVERT(INT,VALUE) FROM dbo.S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'NDFL_OPT9')),0)

declare @SprOtherDed table(LINK_DICTION int, MONTH1 TINYINT, Summa numeric(18,2))

insert into @SprOtherDed
Select LINK_DICTION, MONTH1, SUM(SUM_DED) 
from 
	EMPL E 
	inner join TAX_DEDUCTIONS TD on E.PERS_LINK = TD.LINK_PERSON AND E.DEP_LINK = TD.LINK_DEP
where 
	E.LINK = @varKSlinkEmpl 
	and [YEAR] = @varKSYear 
	AND @Status in (1 /*Основной*/, 3 /*Внешний совместитель*/) 
	and MONTH1 <= Month(@varKSDate) --DATE_REF <= dbo.DateEndOfMonth(@varKSDate)
	AND E.DEP_LINK = @DEP_LINK
Group by 
	LINK_DICTION, MONTH1

IF @varKSfl=1 
	select [Код]= rtrim(SNAME), [Имущественный вычет] = rtrim(name), [Сумма вычета] = ISNULL(OD.summa,0) from @SprOtherDed OD inner join dbo.DICTIONARY_TYP_DEDUCTION  D on D.link = OD.LINK_DICTION

declare @TMP Table ([REF_PAY] int, [MONTH_BEGIN] int, [MONTH_END] int, [SUMMA] numeric(18,2))
Insert into @TMP
Select [REF_PAY], M.NUM, M.NUM, SUM([SUMMA]) 
from dbo.Months M, @varKSTotal T1 
 where M.[NUM] between [MONTH_BEGIN] and [MONTH_END] and [REF_PAY] not in (select LINK_DICTION from @SprOtherDed) 
group by [REF_PAY], M.NUM

DECLARE @REF_PAY int, @MONTH_BEGIN int, @SUMMA numeric(18,2), @Saldo numeric(18,2), @STD_VYCH NUMERIC(18,2), @MONTH1 TINYINT

DECLARE @Cur CURSOR
SET @Cur = CURSOR FORWARD_ONLY
FOR 
	Select M.NUM, LINK_DICTION, [SUMMA], MONTH1 = (CASE WHEN @VychOpt9 = 1 THEN OD.MONTH1 ELSE 1 END) 
	from @SprOtherDed OD, dbo.Months M 
	WHERE M.NUM BETWEEN (CASE WHEN @VychOpt9 = 1 THEN OD.MONTH1 ELSE 1 END) AND @varKSMonth

OPEN @Cur
FETCH NEXT FROM @Cur INTO @MONTH_BEGIN, @REF_PAY, @SUMMA, @MONTH1
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN
		Set @Saldo = ISNULL(@SUMMA,0) - ISNULL((Select Sum(Summa) from @tmp T where T.REF_PAY = @REF_PAY),0)

		SET @STD_VYCH = ISNULL((SELECT SUM(SUMMA) FROM @varKSTotal WHERE [MONTH_BEGIN] < @MONTH1),0)

		INSERT INTO @TMP ([REF_PAY],[MONTH_BEGIN],[MONTH_END],[SUMMA])
		Select --
			@REF_PAY, @MONTH_BEGIN, @MONTH_BEGIN, 
			(Case When @Saldo > (ISNULL(DS.EMPL_SUMMA,0) - ISNULL(DS.DED0,0) 
								- (ISNULL(DS2.EMPL_SUMMA,0) - ISNULL(DS2.DED0,0) - @STD_VYCH)
								- ISNULL((Select SUM(summa) from @TMP where MONTH_BEGIN <=  @MONTH_BEGIN ),0))
				then (ISNULL(DS.EMPL_SUMMA,0) - ISNULL(DS.DED0,0) 
						- (ISNULL(DS2.EMPL_SUMMA,0) - ISNULL(DS2.DED0,0) - @STD_VYCH)
						- ISNULL((Select SUM(summa) from @TMP where MONTH_BEGIN <=  @MONTH_BEGIN ),0))
			else
				@Saldo
			end)
		from
			@varKSTotTab DS
			LEFT JOIN @varKSTotTab DS2 ON DS2.[Month] = @MONTH1-1 
		where
			DS.[Month] = @MONTH_BEGIN
			and
			(ISNULL(DS.EMPL_SUMMA,0) - ISNULL(DS.DED0,0)
				- (ISNULL(DS2.EMPL_SUMMA,0) - ISNULL(DS2.DED0,0) - @STD_VYCH) 
				- ISNULL((Select SUM(summa) from @TMP where MONTH_BEGIN <=  @MONTH_BEGIN ),0)) > 0
			and 
			@Saldo > 0

	END
	FETCH NEXT FROM @Cur INTO @MONTH_BEGIN, @REF_PAY, @SUMMA, @MONTH1
END

CLOSE @Cur
DEALLOCATE @Cur

INSERT INTO @varKSTotal ( [REF_PAY], [MONTH_BEGIN], [MONTH_END], [SUMMA])
Select * from @TMP where [REF_PAY] in (select LINK_DICTION from @SprOtherDed)

/* vvvvvv Имущественные вычеты - Конец расчета vvvvvvv */


IF @varKSfl=1 
select [Вычет] = (select  rtrim(sname) + ' ' + LEFT(rtrim(name),50) from dbo.DICTIONARY_TYP_DEDUCTION where link = REF_PAY),
	month_begin as [Месяц начала], month_end as [Месяц окончания], summa as [Сумма вычета]  from @varKSTotal T1  order by month_begin, REF_PAY


DECLARE @varKSTotal1 TABLE
([KOL]			[int],
 [REF_PAY] 		[int],
 [MONTH_BEGIN]		[int],
 [MONTH_END]		[int],		
 [SUMMA]		[numeric](19, 2))

INSERT INTO @varKSTotal1 ([KOL],[REF_PAY],[MONTH_BEGIN],[MONTH_END],[SUMMA])
SELECT COUNT(*) AS [KOL],REF_PAY,MONTH_BEGIN,MONTH_END,SUMMA
FROM @varKSTotal 
GROUP BY REF_PAY,MONTH_BEGIN,MONTH_END,SUMMA

DECLARE @varKSvych TABLE
([MONTH] 	[int],
 [REF_PAY] 	[int],
 [DEDUCT]	[numeric] (19, 2),
 [COMMENT]  [varchar] (254),
 [KOEF_VKR] [numeric] (18,10),
 [kol] [numeric] (18,2),
 [SPR_SUM]  NUMERIC(18,2)	
)

DECLARE @NDFL_OPT7 int
SET @NDFL_OPT7 = dbo.sa_get_option_by_code('NDFL_OPT7')

DECLARE @Koef table (Mon int, koef NUMERIC(18,10), doh tinyint, koef2 NUMERIC(18,10))
insert into @Koef (Mon, Koef, doh, koef2)
Select 	T2.[Month], 
	CASE WHEN @NDFL_OPT7 = 1 --Вычеты применять только к доходу по 211 ЭКР
	THEN 
		CASE WHEN @varKSLinkEKR = @Link211EKR 
		THEN --Начислять пропорционально КБК
			--CONVERT(NUMERIC(18,10), case when (t2.summa_m_211- t2.ded_m_all) <> 0 then ((v.summa_m_vkr-T2.ded_m)/(t2.summa_m_211- t2.ded_m_all)) else 0 end )
			CONVERT(NUMERIC(18,10), case when t2.summa_m_211 <> 0 then (v.summa_m_vkr/t2.summa_m_211) else 0 end )
		ELSE 
			0 
		END
	ELSE --Начислять пропорционально КБК и ЭКР
		--CONVERT(NUMERIC(18,10), case when (t2.summa_m- t2.ded_m_all) <> 0 then ((t2.summa_m_vkr-T2.ded_m)/(t2.summa_m- t2.ded_m_all)) else 0 end )
		CONVERT(NUMERIC(18,10), case when t2.summa_m <> 0 then (t2.summa_m_vkr/t2.summa_m) else 0 end )
	END,
	(Case when t2.summa_m <> 0 then 1 else 0 end),
	CONVERT(NUMERIC(18,10), case when t2.summa_m <> 0 then (t2.summa_m_vkr/t2.summa_m) else 0 end )	
from 
	@varKSTotTab T2 
	inner join @varKSVal V on T2.[month] = V.[month]

--СПРАВОЧНИК ВИДОВ ИМУЩЕСТВЕННЫХ ВЫЧЕТОВ
DECLARE @DICT_TAX_DEDUCTIONS TABLE (LINK INT)
INSERT INTO @DICT_TAX_DEDUCTIONS (LINK)
SELECT LINK FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE NUMBER = 4

/*Расстановка коэффициентов на вычеты. Если нет дохода, то вычета по коэф. будующего месяца, в котором доход есть*/
INSERT INTO @varKSvych ([MONTH],[REF_PAY],[DEDUCT],[COMMENT],[KOEF_VKR],[KOL], [SPR_SUM])
SELECT [MONTH] = T1.MONTH_BEGIN, T1.REF_PAY,
	[DEDUCT] = 
			CASE WHEN NOT EXISTS (SELECT * FROM @DICT_TAX_DEDUCTIONS D WHERE D.LINK = T1.REF_PAY) THEN	
				CONVERT(NUMERIC(18,10), T1.KOL*T1.SUMMA * 
				case when D.summa_m = 0 then ISNULL((Select top 1 K.Koef from @Koef K where K.Mon >= T1.MONTH_BEGIN and doh <> 0 order by Mon),0)
					else ISNULL((Select top 1 K.Koef from @Koef K where K.Mon = T1.MONTH_BEGIN and K.Koef <> 0 order by Mon),0) end)
			ELSE
				CONVERT(NUMERIC(18,10), T1.KOL*T1.SUMMA * 
				case when D.summa_m = 0 then ISNULL((Select top 1 K.Koef2 from @Koef K where K.Mon >= T1.MONTH_BEGIN and doh <> 0 order by Mon),0)
					else ISNULL((Select top 1 K.Koef2 from @Koef K where K.Mon = T1.MONTH_BEGIN and K.Koef2 <> 0 order by Mon),0) end)
			END,		

	[COMMENT] = 
			CASE WHEN NOT EXISTS (SELECT * FROM @DICT_TAX_DEDUCTIONS D WHERE D.LINK = T1.REF_PAY) THEN	
				'('+RTRIM(LTRIM(STR(T1.KOL)))+'*'+RTRIM(LTRIM(CONVERT(VARCHAR(100),T1.SUMMA)))+ 
				'*'+ rtrim(ltrim(convert(varchar(100), CONVERT(NUMERIC(18,2), case when D.summa_m = 0 then ISNULL((Select top 1 K.Koef from @Koef K where K.Mon >= T1.MONTH_BEGIN and K.Koef <> 0 order by Mon),0)
					else ISNULL((Select top 1 K.Koef from @Koef K where K.Mon = T1.MONTH_BEGIN and doh <> 0 order by Mon),0) end)) )) +')'
			ELSE
				'('+RTRIM(LTRIM(STR(T1.KOL)))+'*'+RTRIM(LTRIM(CONVERT(VARCHAR(100),T1.SUMMA)))+ 
				'*'+ rtrim(ltrim(convert(varchar(100), CONVERT(NUMERIC(18,2), case when D.summa_m = 0 then ISNULL((Select top 1 K.Koef2 from @Koef K where K.Mon >= T1.MONTH_BEGIN and K.Koef2 <> 0 order by Mon),0)
					else ISNULL((Select top 1 K.Koef2 from @Koef K where K.Mon = T1.MONTH_BEGIN and doh <> 0 order by Mon),0) end)) )) +')'
			END,

	[KOEF_VKR] =
			CASE WHEN NOT EXISTS (SELECT * FROM @DICT_TAX_DEDUCTIONS D WHERE D.LINK = T1.REF_PAY) THEN
				 CONVERT(NUMERIC(18,10), case when D.summa_m = 0 then ISNULL((Select top 1 K.Koef from @Koef K where K.Mon >= T1.MONTH_BEGIN and K.Koef <> 0 order by Mon),0)
					else ISNULL((Select top 1 K.Koef from @Koef K where K.Mon = T1.MONTH_BEGIN and doh <> 0 order by Mon),0) end )
			ELSE
				 CONVERT(NUMERIC(18,10), case when D.summa_m = 0 then ISNULL((Select top 1 K.Koef2 from @Koef K where K.Mon >= T1.MONTH_BEGIN and K.Koef2 <> 0 order by Mon),0)
					else ISNULL((Select top 1 K.Koef2 from @Koef K where K.Mon = T1.MONTH_BEGIN and doh <> 0 order by Mon),0) end )				
			END,		
	T1.KOL,
	T1.KOL*T1.SUMMA
FROM @varKSTotal1 t1 left join @varKSTotTab D on T1.MONTH_BEGIN = D.[Month]--, @varKSTotTab T2 WHERE T2.[MONTH] BETWEEN T1.MONTH_BEGIN AND T1.MONTH_END 
ORDER BY 1

INSERT INTO dbo.SAL_DED_MONTH (LINK_EMPL,REF_DED,SUMMA,DATE_DED,LINK_VKR,LINK_EKR,TYPE, KOEF_VKR, KOL )
SELECT 	[LINK_EMPL] = @varKSlinkEmpl,
			[REF_DED] 	= T.REF_PAY,
			[SUMMA] 	= T.DEDUCT,
			[DATE_DED] 	= dbo.ConvertDMY2Date(1,t.[month],year(@varKSDate)),
			[LINK_VKR]	= @varKSLinkVKR,
			[LINK_EKR]	= @varKSLinkEKR,
			[TYPE] 		= 1, --convert(NUMERIC(3,0),B.VALUE)
			[KOEF_VKR],
			[KOL]
FROM @varKSvych T WHERE T.DEDUCT <> 0 

--========================================================================================
--Блок проверки и коррестировки ошибки, связанной с погрешностья округления разбитых по источникам вычетов
SELECT S.REF_DED, MONTH(DATE_DED) AS MN, V.SPR_SUM - SUM(SUMMA) AS SUMMA
INTO #CORRECT
FROM dbo.SAL_DED_MONTH S INNER JOIN @varKSvych V ON V.[MONTH] = MONTH(S.DATE_DED) AND S.REF_DED = V.REF_PAY
WHERE YEAR(DATE_DED) = year(@varKSDate) AND LINK_EMPL = @varKSlinkEmpl
GROUP BY S.REF_DED, MONTH(DATE_DED), V.SPR_SUM
HAVING ABS(V.SPR_SUM - SUM(SUMMA)) BETWEEN 0.01 AND 0.02

IF EXISTS(SELECT * FROM #CORRECT) BEGIN

	UPDATE V
	SET V.DEDUCT = ISNULL(V.DEDUCT,0) + ISNULL(C.SUMMA,0)
	FROM @varKSvych V INNER JOIN #CORRECT C ON V.[MONTH] = C.MN AND C.REF_DED = V.REF_PAY

	DELETE FROM dbo.SAL_DED_MONTH 
	WHERE YEAR(DATE_DED) = year(@varKSDate) AND LINK_EMPL = @varKSlinkEmpl AND [LINK_VKR] = @varKSLinkVKR AND [LINK_EKR] = @varKSLinkEKR
		AND REF_DED IN (SELECT REF_PAY FROM @varKSvych)

	INSERT INTO dbo.SAL_DED_MONTH (LINK_EMPL,REF_DED,SUMMA,DATE_DED,LINK_VKR,LINK_EKR,TYPE, KOEF_VKR, KOL )
	SELECT 	[LINK_EMPL] = @varKSlinkEmpl,
				[REF_DED] 	= T.REF_PAY,
				[SUMMA] 	= T.DEDUCT,
				[DATE_DED] 	= dbo.ConvertDMY2Date(1,t.[month],year(@varKSDate)),
				[LINK_VKR]	= @varKSLinkVKR,
				[LINK_EKR]	= @varKSLinkEKR,
				[TYPE] 		= 1, --convert(NUMERIC(3,0),B.VALUE)
				[KOEF_VKR],
				[KOL]
	FROM @varKSvych T WHERE T.DEDUCT <> 0 

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

DECLARE @varKSTota TABLE
([MONTH] 		[int],
 [PERS_SUMMA_VKR]	[numeric](19, 2),
 [SUMMA_VKR]	[numeric](19, 2),
 [SUMMA_M]		[numeric](19, 2),
 [SUMMA_M_VKR]	[numeric](19, 2),
 [DED_M_ALL] 	[numeric](19, 2),
 [DED]			[numeric](19, 2),
 [DED_M]			[numeric](19, 2),
 [VYCH]			[numeric](19, 2),
 [VYCH_M]		[numeric](19, 2),
 [DOHOD_ALL]	[numeric](19, 2),
 [VICHET_ALL]	[numeric](19, 2)
 ) 

INSERT INTO @varKSTota([MONTH], [PERS_SUMMA_VKR], [SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR],[DED_M_ALL],[DED],[DED_M],[VYCH],[VYCH_M],[DOHOD_ALL],[VICHET_ALL])
SELECT T1.[MONTH],T1. [SUMMA_VKR], T1.[EMPL_SUMMA_VKR],T1.[SUMMA_M],T1.[SUMMA_M_VKR],T1.[DED_M_ALL],T1.[DED],T1.[DED_M],
		[VYCH]	=ISNULL((SELECT SUM(V.DEDUCT) FROM @varKSvych v WHERE V.[MONTH]<= T1.[MONTH]),0),
		[VYCH_M] =ISNULL((SELECT SUM(V.DEDUCT) FROM @varKSvych v WHERE V.[MONTH] = T1.[MONTH]),0),
		[DOHOD_ALL] = T1.[EMPL_SUMMA],
		[VICHET_ALL] = ISNULL((SELECT SUM(V.SPR_SUM) FROM @varKSvych v WHERE V.[MONTH]<= T1.[MONTH]),0)
FROM @varKSTotTab T1

IF @varKSfl=1 
	select [month] as [Месяц],pers_summa_vkr as [Сумма ФЛ с нач года по ВКР], summa_vkr as [Сумма сотр с нач года по ВКР], summa_m as [Сумма сотр за месяц], 
	summa_m_vkr as [Сумма сотр за месяц по ВКР], ded_m_all as [Скидки всего], ded as [Скидки всего по ВКР], ded_m as [Скидки за месяц по ВКР], 
	vych as [Вычеты всего], vych_m  as [Вычеты за месяц] from @varKSTota

----
declare @varKSSumDed numeric(15,2), @varKSRange  numeric(15,2), @varKSResid int, @varKSStrCom varchar(1000)

SET @varKSSumDed = ISNULL(
	(SELECT sum(summa) 
	FROM
		dbo.PAYS P INNER JOIN dbo.CALCULATE_JURNAL SJ ON P.LINK = SJ.LINK_PAYS
	WHERE
		SJ.LINK_PAYS = @varKSRef_Pay
		AND YEAR(SJ.PERIOD_BEGIN) = @varKSYear
		AND MONTH(SJ.PERIOD_BEGIN) <=@varKSMonth 
		AND SJ.LINK_EMPL = @varKSlinkEmpl 
		AND SJ.LINK_VKR = @varKSLinkVKR
		AND SJ.LINK_DEP = @DEP_LINK 
		AND ISNULL(SJ.LINK_EKR,P.LINK_EKR) = @varKSLinkEKR)
	,0)	
	
SET @varKSSumDed = @varKSSumDed + ISNULL( (SELECT SUM(SR.NDFL) FROM dbo.SAL_REMAIN SR WHERE SR.LINK_EMPL = @varKSlinkEmpl AND SR.YEAR_SAL = @varKSYear AND SR.LINK_VKR = @varKSLinkVKR AND SR.LINK_EKR = @varKSLinkEKR), 0)

set @varKSRange =  dbo.SalaryGetNDFLRange (@varKSlinkEmpl,@varKSDate)
set @varKSResid = dbo.GetEmplResident(@varKSlinkEmpl)

IF @varKSfl=1 
	select [Удержано с нач года] = @varKSSumDed, [Ставка налога] = @varKSRange, [Статус] = (case when @varKSResid = 1  then 'Резидент' else 'Не резидент' end)


set @varKSStrCom = ''
DECLARE @varKSCurs CURSOR,
		  @varKSCurCOMMENT varchar(255)

SET @varKSCurs = CURSOR FORWARD_ONLY
FOR SELECT COMMENT FROM @varKSvych WHERE DEDUCT <> 0 and [month]=@varKSMonth
OPEN @varKSCurs
FETCH NEXT FROM @varKSCurs INTO @varKSCurCOMMENT
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @varKSStrCom = @varKSStrCom + ' ' + isnull(@varKSCurCOMMENT,'0')+ ' +'
	FETCH NEXT FROM @varKSCurs INTO @varKSCurCOMMENT
END 
CLOSE @varKSCurs
DEALLOCATE @varKSCurs
IF LEN(@varKSStrCom) > 2
	SET @varKSStrCom = LEFT(@varKSStrCom,LEN(@varKSStrCom)-2) 


IF @varKSfl=1 
BEGIN	
	PRINT 'Расчет налога с общего дохода по КБК'
	
	SELECT T.*,
	[sum_ded]=  isnull(@varKSSumDed,0),
	[summa] = 	case when DOHOD_ALL > VICHET_ALL THEN
					convert(numeric(18,2),(summa_vkr -ded - (case when @varKSResid = 1 then vych else 0 end))*@varKSRange/100)
				ELSE
					0
				END,
	[comment] = @varKSStrCom
	FROM @varKSTota T
	WHERE [MONTH] = @varKSMonth
	
END

/*Вычеты, скидки и налог пропорционально доли больничных за счет ФСС/зарплате в общем доходе работника*/
IF @varKSfl<>1 
SELECT 
	[MONTH],
	PERS_SUMMA_VKR= convert(numeric(18,2), [PERS_SUMMA_VKR]),
	SUMMA_VKR= convert(numeric(18,2), [SUMMA_VKR]),
	SUMMA_M= convert(numeric(18,2), [SUMMA_M]),
	SUMMA_M_VKR= convert(numeric(18,2), [SUMMA_M_VKR]),
	DED_M_ALL= convert(numeric(18,2), [DED_M_ALL]),
	DED= convert(numeric(18,2),[DED]),
	DED_M= convert(numeric(18,2),[DED_M]),
	VYCH= convert(numeric(18,2), [VYCH]),
	VYCH_M= convert(numeric(18,2), [VYCH_M]),
	[sum_ded]=  convert(numeric(18,0), isnull(@varKSSumDed,0)), 
	[summa] = 	case when convert(numeric(18,0),(summa_vkr -ded - (case when @varKSResid = 1 then vych else 0 end))*@varKSRange/100) > 0
			then 
				case when DOHOD_ALL > VICHET_ALL THEN
					convert(numeric(18,0),(summa_vkr -ded - (case when @varKSResid = 1 then vych else 0 end))*@varKSRange/100)
				ELSE
					0
				END					
			else 
				CASE WHEN @NDFL_OPT8 = 0 
				THEN 
					0
				ELSE
					convert(numeric(18,0),(summa_vkr -ded - (case when @varKSResid = 1 then vych else 0 end))*@varKSRange/100)
				END
			end,
	[comment] = Case when len(rtrim(ltrim(@varKSStrCom))) > 0 then '{' + RTRIM(LTRIM(@varKSStrCom)) + '}' else '' end,
	[RANGE] = @varKSRange/100
FROM @varKSTota T
WHERE [MONTH] = @varKSMonth



GO


GRANT EXECUTE ON dbo.[SD_U_NDFL_FILL] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

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

CREATE    


PROCEDURE dbo.X_SAVE_DOCUMENTS_PAY_ADD
	@varKSpLINK		int	OUTPUT,
	@varKSpDOH_LINK       INT = null,
	@varKSpSGU_LINK       INT = null,
	@varKSpOKATO          VARCHAR(11) = null,
	@varKSpP_REASON       VARCHAR(2) = null,
	@varKSpPERIOD         VARCHAR(10) = null,
	@varKSpTREBNUM        VARCHAR(30) = null,
	@varKSpTREBDATE       DATETIME = null,
	@varKSpZERODATE       BIT = null,
	@varKSpP_TYPE         VARCHAR(2) = null,
	@varKSpSTATUS         VARCHAR(2) = null,
	@cUinCode			  varchar(20) = ''
AS

SET @cUinCode = ISNULL(@cUinCode,'')

SET LOCK_TIMEOUT 30000
SET IMPLICIT_TRANSACTIONS ON
DECLARE 	@varKSstrVALUE	varchar(7000),
		@varKSEventText	varchar(254),
		@varKSERROR		int,
		@varKSRowCount	int,
		@varKStrancount	int
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	
	IF exists (select * from FINANSE_PAYS where link = @varKSpLINK)
		UPDATE FINANSE_PAYS
			SET Link_Dohod = @varKSpDOH_LINK,
			Link_SGU = @varKSpSGU_LINK,
			OKATO = @varKSpOKATO,
			P_REASON = @varKSpP_REASON,
			Nal_PERIOD = @varKSpPERIOD,
			TREBNUM = @varKSpTREBNUM,
			TREBDATE = @varKSpTREBDATE,
			ZERODATE = @varKSpZERODATE,
			P_TYPE = @varKSpP_TYPE,
			STATUS = @varKSpSTATUS,
			UIN_CODE = @cUinCode
		WHERE Link = @varKSpLINK
	ELSE 
	BEGIN
		ROLLBACK
		RETURN 2
	END
	SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
	IF @varKSERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
	IF @varKSRowCount = 0
	BEGIN
		ROLLBACK
		RETURN 2
	END

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

GO

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

CREATE PROCEDURE dbo.SA_SZV_K_PACHKA_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 = 'Пачка №: ' + RTRIM(LTRIM(convert(varchar(10),Numer))) + ' от ' + CONVERT(VARCHAR(10),Date,104) FROM dbo.SA_SZV_K_PACHKA 
			WITH (UPDLOCK) WHERE LINK = @varKSintLINK
	IF @@RowCount = 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 2
	END
	DELETE FROM dbo.SZV_K_PACHKA WHERE LINK = @varKSintLINK
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
IF @@TRANCOUNT > @varKStrancount
	BEGIN
		SELECT @varKSObjectLink = LINK FROM S_OBJECTS WHERE CODE = 'SA_SZV_K_PACHKA'
		EXECUTE WF_GENERATEEVENT 'Удаление из справочника', @varKSEventText, @varKSObjectLink, 'SA_SZV_K_PACHKA', @varKSintLINK

		COMMIT TRAN
	END
RETURN 0


GO


GRANT EXECUTE ON dbo.[SA_SZV_K_PACHKA_DELETE] TO PUBLIC

GO


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

GO

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

SET NOCOUNT ON

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @CUR_EPML
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			
			SET @Cur2 = CURSOR FORWARD_ONLY
			FOR SELECT m, y, DATE_BEGIN FROM dbo.months_ex(@DATE_BEGIN_RP, @DATE_END_RP) 
			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 

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

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

	--
	Select 
		PERIOD = dbo.ConvertDMY2Date(31,12,YEAR(MIN(PERIOD))), PERIOD1 = YEAR(PERIOD), CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, 
		SUMMA = SUM( CASE WHEN WAY_CALC = 6 AND (DATEDIFF(MONTH,DATE1, DATE2) + 1) <> 0 AND @UCHET_PREM = 1 THEN 
					CONVERT(NUMERIC(18,2), SUMMA * 
						(DATEDIFF(MONTH,CASE WHEN DATE1 <= @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 @WTIME1 TABLE(M INT, Y INT, [DAYS] NUMERIC(18,2))
DECLARE @WTIME TABLE(Y INT, [DAYS] NUMERIC(18,2))

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

	UPDATE @TABLE2 SET SUMMA_PR = 0, HOURS_NORM = 0

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	----
	UPDATE @PERIODY
	SET 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

SET @I = 0

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

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

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

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

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

IF @OPER = 1 
	exec dbo.SD_N_BOL_PROV @LINK_DOC

SET NOCOUNT OFF


GO


GRANT EXECUTE ON dbo.[SA_N_BOL_FILL3] TO PUBLIC

GO


GO
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,
	@ACC_ESN varchar(6) = '',
	@LINK_LACC int = NULL,
	@USED TINYINT = 1,
	@LINK_CH_SFIN INT,
	@DATE_CHANGE DATETIME = NULL
AS
DECLARE @varKSERROR	tinyint,
	@varKStrancount	int, 
	@varKSRowCount int

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



IF @LINK_LACC = 0
	SET @LINK_LACC = NULL

IF @ACC_ESN IS NULL 
	SET @ACC_ESN = '' 

IF @CODE IS NULL OR @CODE = '' OR @NAME IS NULL OR @NAME = ''
BEGIN
	ROLLBACK
	RETURN 5
END

/*exec SA_SFIN_SAVE 37,'021.0101.0300000.006','Яранский райфо',1253,1,
						NULL,NULL,NULL,'перенесено из справочника КБК',0,'401.20',67771,NULL
						*/

IF EXISTS (SELECT * FROM dbo.SAL_SFIN WHERE LINK <> @LINK AND CODE = @CODE AND USED = @USED) BEGIN
	raiserror('Уже есть источник финансирования с таким кодом',11,1)	
	ROLLBACK
	RETURN 0
END

SET @SOURCE = COALESCE(@SOURCE,1)

IF @LINK is null OR @LINK = 0
BEGIN


	IF EXISTS (SELECT * FROM dbo.SAL_SFIN WHERE (RTRIM(LTRIM([name])) = @name OR RTRIM(LTRIM([code])) = @code) and  source = @SOURCE)
	BEGIN
		ROLLBACK
		RETURN 8
	END	

	INSERT INTO dbo.SAL_SFIN WITH (ROWLOCK) (CODE,[NAME],KBK,SOURCE,USER_ACC,DOP_KL,KAU,COMMENT,ENVD, ACC_ESN, LINK_LACC, USED, LINK_CH_SFIN,DATE_CHANGE)
		VALUES (@CODE,@NAME,@LINK_KBK,@SOURCE,@USER_ACC,@LINK_DOP_KL,@LINK_KAU,@COMMENT,@ENVD, @ACC_ESN, @LINK_LACC, @USED, @LINK_CH_SFIN,@DATE_CHANGE)

	SELECT @varKSERROR = @@ERROR, @LINK = @@IDENTITY
	IF @varKSERROR <> 0
	BEGIN

		ROLLBACK
		RETURN 7
	END
END

ELSE
BEGIN
	UPDATE dbo.SAL_SFIN SET CODE=@CODE, [NAME]=@NAME, KBK=@LINK_KBK, [SOURCE]=@SOURCE, USER_ACC=@USER_ACC, 
		DOP_KL=@LINK_DOP_KL, KAU=@LINK_KAU, COMMENT=@COMMENT, ENVD=@ENVD , ACC_ESN = @ACC_ESN, 
		LINK_LACC = @LINK_LACC, USED = @USED, LINK_CH_SFIN = @LINK_CH_SFIN, DATE_CHANGE = @DATE_CHANGE
	WHERE link=@LINK

	SELECT @varKSERROR = @@ERROR 
	IF @varKSERROR <> 0
	BEGIN

		ROLLBACK
		RETURN 7
	END
	IF @varKSRowCount = 0
	BEGIN

		ROLLBACK
		RETURN 2
	END
END

declare @ObjectLink int, @EventText varchar(254)
SELECT @ObjectLink = link FROM s_objects WHERE code='SALARY_SRC_FIN'
SET @EventText = 'Источники финансирования' +  RTRIM(@Name)
EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @EventText, @ObjectLink, 'SALARY_SRC_FIN', @LINK

IF @varKSERROR <> 0
	RETURN @varKSERROR

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0






GO


GRANT EXECUTE ON dbo.[SA_SFIN_SAVE] TO PUBLIC

GO



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

GO

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

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output

	SET @DEP_LINK = COALESCE(@LINK_DEP,@DEP_LINK)

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

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

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


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

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

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

IF @MIN_PACHKA_ISHOD = @MIN_PACHKA_KORR

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

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

CLOSE @Cur
DEALLOCATE @Cur

END 

UPDATE t
	SET  FNAME=  'PFR-700-Y-' + CONVERT(VARCHAR(4),[year]) + '-ORG-' + LTRIM(RTRIM(dep_PFNUM)) + '-DCK-' + REPLACE(str(NGROUP,5),' ','0') + '-DPT-000000-DCK-00000.XML'	
	from #SZV_ALL t  WHERE TYPE <> 1

----------------------------
SELECT * INTO #SZV_SUM FROM
(SELECT 
	RN = ROW_NUMBER() OVER (PARTITION BY LINK_FACE, CODE, T_DOG, [TYPE] ORDER BY T_DOG),
	CODE,
	LINK_FACE,
	[PFNUMBER],
	T_DOG,
	INC_M1,
	B_BEF_M1,
	B_AFT_M1,
	INC_M2,
	B_BEF_M2,
	B_AFT_M2,
	INC_M3,
	B_BEF_M3,
	B_AFT_M3,		
	per,
	[year],
	[TYPE],
	per_edt,
	year_edt,
	INSUR	
FROM 
	#SZV_ALL 
) T WHERE RN = 1	

-----------
DECLARE @PREDEL NUMERIC(18,2)
SET @PREDEL = ISNULL((SELECT MIN(PREDEL) FROM dbo.DICTIONARY_RANGE_PF WHERE WAY_CALC = 6 AND TARIF = 1 AND [DATE] >= dbo.ConvertDMY2Date(1,1,YEAR(@dDate1))),0)
-----------
SELECT 
	LINK_FACE, [PFNUMBER], CODE, per, [year], [TYPE], per_edt, year_edt, INSUR = SUM(INSUR)
INTO 
	#SZV_PC 		
FROM 
	(
	SELECT 
		A.LINK_FACE, A.[PFNUMBER], A.CODE, A.T_DOG, A.per, A.[year], A.[TYPE], A.per_edt, A.year_edt, 
		INSUR = CASE WHEN MIN(B_AFT_M1) + MIN(B_AFT_M2) + MIN(B_AFT_M3) <> 0 THEN
					MIN(B_BEF_M1 * PERCENT1 / 100) + MIN(B_BEF_M2 * PERCENT1 / 100) + MIN(B_BEF_M3 * PERCENT1 / 100)
				ELSE
					MIN(INSUR)
				END				
	FROM 
		#SZV_ALL A INNER JOIN dbo.SA_PFR_KATEG B ON A.CODE = B.CODE AND [year] BETWEEN YBEG AND YEND
			INNER JOIN 
			(
				SELECT 
					TARIF, PERCENT1
				FROM 
					dbo.DICTIONARY_RANGE_PF D
				WHERE
					WAY_CALC = 6 AND PREDEL = @PREDEL
					AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE_PF D1 WHERE D1.TARIF = D.TARIF AND ISNULL(D1.SPECO,0) = ISNULL(D.SPECO,0) AND WAY_CALC = 6 AND DATE < @dDate1 ORDER BY [DATE] DESC) 
			) C ON C.TARIF = B.LINK2 
	GROUP BY
		A.LINK_FACE, A.[PFNUMBER], A.CODE, A.T_DOG, A.per, A.[year], A.[TYPE], A.per_edt, A.year_edt
	) T
GROUP BY
	LINK_FACE, [PFNUMBER], CODE, per, [year], [TYPE], per_edt, year_edt

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

	IF @REP = 0 
	BEGIN 
		SELECT
			CODE = CONVERT(VARCHAR(14), [PFNUMBER]),
			COL1 = CONVERT(VARCHAR(14),[PFNUMBER]),
			COL2 = CONVERT(varchar(100),[FM]),
			COL3 = CONVERT(varchar(100),[IM]),
			COL4 = CONVERT(varchar(100),[OT]),
			COL5 = CONVERT(varchar(14),[PFNUMBER]),
			COL6 = [TYPE],
			COL7 = [NGROUP],
			COL8 = [FNAME],
			COL9 = CONVERT(VARCHAR(10), DATE_DOC, 104)
		FROM
			#SZV_ALL
		GROUP BY [TYPE],[T_DOG],[FM],[IM],[OT],[PFNUMBER], [NGROUP], [FNAME],DATE_DOC
		ORDER BY
			[TYPE],[T_DOG],[FM],[IM],[OT]
		
	END

	IF @REP = 1 
	BEGIN 	

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

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

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


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

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

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

			--Заготовка для #SALARY_SUM2
			CREATE TABLE #SALARY_SUM_DATA (PERS_LINK INT,t_dog TINYINT, PERIOD_BEGIN DATETIME, SUMMA_ALL NUMERIC(18,2), SUMMA_NO NUMERIC(18,2), SUMMA_ALL_I NUMERIC(18,2), SUMMA_NO_I NUMERIC(18,2), SUMMA_ALL_E NUMERIC(18,2), SUMMA_NO_E NUMERIC(18,2), INV TINYINT 
					, SUMMA_NO_D1 NUMERIC(18,2), SUMMA_NO_D2 NUMERIC(18,2),    
				SUM_NO_D1_O4 NUMERIC(18,2) ,SUM_NO_D1_B34 NUMERIC(18,2) ,SUM_NO_D1_B33 NUMERIC(18,2),SUM_NO_D1_B32 NUMERIC(18,2), SUM_NO_D1_B31 NUMERIC(18,2),
					SUM_NO_D2_O4 NUMERIC(18,2) ,SUM_NO_D2_B34 NUMERIC(18,2) ,SUM_NO_D2_B33 NUMERIC(18,2),SUM_NO_D2_B32 NUMERIC(18,2), SUM_NO_D2_B31 NUMERIC(18,2) 
					)

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

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

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

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

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

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

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


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

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

		--Данные о начисленной зарплате
		SELECT 
			PERS_LINK,
			T_DOG = MIN(T_DOG),
			SUMMA_ALL = SUM(SUMMA_ALL), SUMMA_NO = SUM(SUMMA_NO), 
			SUMMA_ALL_I = SUM(SUMMA_ALL_I), SUMMA_NO_I = SUM(SUMMA_NO_I),
			SUMMA_ALL_E = SUM(SUMMA_ALL_E), SUMMA_NO_E = SUM(SUMMA_NO_E),
			SUMMA_ALL_DO_I = (CASE WHEN SUM(SUMMA_ALL_I) > @PREDEL THEN  @PREDEL ELSE (SUM(SUMMA_ALL_I) - SUM(SUMMA_NO_I)) END ),
			SUMMA_ALL_DO = (CASE WHEN SUM(SUMMA_ALL) > @PREDEL THEN  @PREDEL ELSE (SUM(SUMMA_ALL) - SUM(SUMMA_NO)) END ),
			SUMMA_ALL_AFTER = (CASE WHEN SUM(SUMMA_ALL - SUMMA_ALL_I - SUMMA_NO - SUMMA_NO_I)  > @PREDEL THEN  SUM(SUMMA_ALL) - @PREDEL ELSE 0 END ),
			SUMMA_ALL_AFTER_I = (CASE WHEN SUM(SUMMA_ALL_I) > @PREDEL THEN  SUM(SUMMA_ALL) - @PREDEL ELSE 0 END )
			,BASE_DOG = SUM(CASE WHEN T_DOG = 2 THEN SUMMA_ALL - SUMMA_NO ELSE 0 END)
		INTO #SALARY_SUM2
		FROM #SALARY_SUM_DATA s 
		GROUP BY
			PERS_LINK

-----------<<<<<<<<</*СВЕДЕНИЯ ЗА ПЕРИОД , ПО КОРРЕКТИРУЮЩИМ*/
		
		DECLARE @nYEAR1_K INT, @nMONTH_1_K INT, @nMONTH_2_K INT, @nMONTH_3_K INT	
		select 
   		@nYEAR1_K = YEAR_EDT,
   		@nMONTH_1_K = /*case when YEAR_EDT  between '2011' and '2013' then (*/case  PER_EDT when 1 then  1 when 2 then  4 when 3 then  7 when 4 then  10 else 10 end/*)
					when  YEAR_EDT >= '2014'  then (case  PER_EDT when 3 then  1 when 6 then  4 when 9 then  7 else  10 end)
					else null end */
		from #SZV_ALL	
		where [TYPE] = 2
		and YEAR_EDT >=2014
							 
		select @nMONTH_2_K = @nMONTH_1_K+1,
				@nMONTH_3_K = @nMONTH_1_K +2	

		DECLARE @BYearDate_K	datetime , @EndYear_K datetime
		SET @BYearDate_K = dbo.DateBeginOfYear (@nYEAR1_K+'0101')
		Set @EndYear_K = dbo.DateEndOfYear(@BYearDate_K)

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

			SELECT  PERS_LINK, MONTH_BASE, SUMMA_BASE = SUM(SUMMA_BASE)
			INTO #DGH_FAKT_BASE1_K
			FROM #DGH_FAKT_BASE_K
			GROUP BY PERS_LINK, MONTH_BASE


			-- Журнал операций 
			CREATE TABLE #CALCULATE_JURNAL_K (LINK_PAYS INT, PERIOD_BEGIN DATETIME, LINK_DOC INT, PERS_LINK INT, LINK_VKR INT, LINK_EKR INT, LINK_EMPL INT, SUMMA NUMERIC(18,2), WAY_CALC TINYINT , SPECO int)
			INSERT INTO #CALCULATE_JURNAL_K (LINK_PAYS, PERIOD_BEGIN, LINK_DOC, PERS_LINK, LINK_VKR, LINK_EKR, LINK_EMPL, SUMMA,way_calc , SPECO)
			SELECT CJ.LINK_PAYS, CJ.PERIOD_BEGIN, CJ.LINK_DOC, CJ.PERS_LINK, CJ.LINK_VKR, cj.LINK_EKR, CJ.LINK_EMPL, SUMMA = SUM(CJ.SUMMA), p.way_calc , SPECO
			FROM dbo.CALCULATE_JURNAL CJ INNER JOIN dbo.PAYS P ON  CJ.LINK_PAYS = p.link
			WHERE
				Year(period_begin) = @nYEAR1_K 
				and Month(period_begin) <= @nMONTH_3_K
				and CJ.LINK_DEP = @DEP_LINK
			GROUP BY
				cj.LINK_PAYS, cj.PERIOD_BEGIN, cj.LINK_DOC, cj.PERS_LINK, cj.LINK_VKR, cj.LINK_EKR, cj.LINK_EMPL, P.WAY_CALC,cj.SPECO
						
						
			------	у кого была инвалидность в заданном периоде
			SELECT DISTINCT PERS_LINK 
			INTO #PERS_INV_K
			FROM dbo.PERS_INVALID I
			WHERE COALESCE(I.DATE_BEGIN,@BYearDate_K) <= @EndYear_K AND COALESCE(I.DATE_END,@EndYear_K) >= @BYearDate_K

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

			--Заготовка для #SALARY_SUM2
			CREATE TABLE #SALARY_SUM_DATA_K (PERS_LINK INT,t_dog TINYINT, PERIOD_BEGIN DATETIME, SUMMA_ALL NUMERIC(18,2), SUMMA_NO NUMERIC(18,2), SUMMA_ALL_I NUMERIC(18,2), SUMMA_NO_I NUMERIC(18,2), SUMMA_ALL_E NUMERIC(18,2), SUMMA_NO_E NUMERIC(18,2), INV TINYINT 
					, SUMMA_NO_D1 NUMERIC(18,2), SUMMA_NO_D2 NUMERIC(18,2),    
				SUM_NO_D1_O4 NUMERIC(18,2) ,SUM_NO_D1_B34 NUMERIC(18,2) ,SUM_NO_D1_B33 NUMERIC(18,2),SUM_NO_D1_B32 NUMERIC(18,2), SUM_NO_D1_B31 NUMERIC(18,2),
					SUM_NO_D2_O4 NUMERIC(18,2) ,SUM_NO_D2_B34 NUMERIC(18,2) ,SUM_NO_D2_B33 NUMERIC(18,2),SUM_NO_D2_B32 NUMERIC(18,2), SUM_NO_D2_B31 NUMERIC(18,2) 
					)

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

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

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

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

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

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

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


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

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

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


		DROP TABLE #SALARY_SUM_DATA	
		DROP TABLE #DGH_FAKT_BASE
		DROP TABLE #DGH_FAKT_BASE1
		DROP TABLE #PERS_INV
		DROP TABLE #CALCULATE_JURNAL
		DROP TABLE #EMPL_DT		

		DROP TABLE #SALARY_SUM_DATA_K	
		DROP TABLE #DGH_FAKT_BASE_K
		DROP TABLE #DGH_FAKT_BASE1_K
		DROP TABLE #PERS_INV_K
		DROP TABLE #CALCULATE_JURNAL_K
		DROP TABLE #EMPL_DT_K				

		
		/*Корректирующие сведения по физ лицам для печати раздела 6.6*/
		SELECT year_edt = p.YEAR_EDT, 
				PER_EDT = p.PER_EDT, 
				link_dep = p.link_dep,
				link_pers = s.link_pers,
				Link_kateg = S.Link_kateg,
				pachka = s.pachka
		INTO #tmp_pers_r1
		FROM 	dbo.SA_SZV4_PACHKA P 
				INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up 															
		where
			P.link in (select link from #DOCS WHERE vid_kor = 2)
			and P.proverka = 1
			and P.vid_kor > 1
			and p.link_dep = @DEP_LINK


		CREATE TABLE #tmp_pers_kor_sum_R1 (link INT  , [date] DATETIME, YEAR_degin INT , per INT , vid_kor int, link_dep INT , proverka INT  , CODE VARCHAR(5), link_pers INT , 
										sum_doh NUMERIC(18,2), sum_str NUMERIC(18,2), sum_nak NUMERIC(18,2),sum_dop NUMERIC(18,2) , pachka int) 
	
		DECLARE @Cur_R1 CURSOR, @link_R1 int ,@LINK_pers_R1 INT, @year_edt_R1 INT , @per_edt_R1 INT , @Link_kateg_R1 INT ,@pachka_R1 int
		SET @Cur_R1 = CURSOR FORWARD_ONLY

		FOR SELECT LINK_pers, year_edt, per_edt, Link_kateg ,pachka FROM #tmp_pers_r1 ORDER by link_pers

		OPEN @Cur_R1
		FETCH NEXT FROM @Cur_R1 INTO @LINK_pers_R1, @year_edt_R1, @per_edt_R1 , @link_kateg_R1, @pachka_R1
		WHILE (@@fetch_status <> -1)
		BEGIN

			IF (@@fetch_status <> -2)
			BEGIN
				
				
					SET @link_R1 = 0
					
					SELECT @link_R1 =max(pp.link)
					FROM SA_SZV4_PACHKA pp 
					INNER JOIN dbo.SZV4_SVEDENIA Ss ON ss.link_up = pp.link  
					WHERE  pp.proverka = 1 AND pp.vid_kor = 1 
										  AND pp.link_dep = @DEP_LINK 
										  AND pp.year_begin =@year_edt_R1  
										  AND pp.PER =@per_edt_R1 
										  AND @LINK_pers_R1 = ss.link_pers
										  AND @link_kateg_R1 = ss.link_kateg  
										  AND pp.date = (SELECT MAX(p1.[date]) FROM SA_SZV4_PACHKA p1 
																INNER JOIN dbo.SZV4_SVEDENIA S1 ON s1.link_up = p1.link  
																WHERE  pp.proverka = 1 AND p1.vid_kor = 1 
																					  AND p1.link_dep = @DEP_LINK 
																					  AND p1.year_begin =@year_edt_R1  
																					  AND p1.PER =@per_edt_R1 
																					  AND @LINK_pers_R1 = s1.link_pers
																					  AND @link_kateg_R1 = s1.link_kateg )
					
					INSERT INTO #tmp_pers_kor_sum_R1  (link, [date], YEAR_degin, per, vid_kor, link_dep, proverka , CODE, link_pers, 
										sum_doh, sum_str, sum_nak,sum_dop, pachka) 
					SELECT pp.link, pp.[date], pp.YEAR_begin, pp.per, pp.vid_kor, pp.link_dep, pp.proverka, CODE = k.code, ss.link_pers, 
										ss.sum_doh, ss.sum_str, ss.sum_nak,ss.sum_dop , pachka = @pachka_R1
					FROM SA_SZV4_PACHKA pp 
					INNER JOIN dbo.SZV4_SVEDENIA Ss ON ss.link_up = pp.link  
					INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = ss.LINK_KATEG AND pp.YEAR_begin BETWEEN YBEG AND YEND		
					WHERE pp.link = @link_R1 and pp.proverka = 1 
										 AND pp.vid_kor = 1 
										 AND pp.link_dep = @DEP_LINK 
										 AND pp.year_begin =@year_edt_R1  
										 AND pp.PER =@per_edt_R1 
										 AND ss.link_pers = @LINK_pers_R1
										 AND ss.link_kateg = @link_kateg_R1
										  

			END

			FETCH NEXT FROM @Cur_R1 INTO @LINK_pers_R1, @year_edt_R1, @per_edt_R1, @link_kateg_R1, @pachka_R1
		END

		CLOSE @Cur_R1
		DEALLOCATE @Cur_R1


		/******************* ИСХОДНЫЕ СВЕДЕНИЯ ********************/
							   
		DECLARE @Cur1 CURSOR, @CODE varchar(4), @TYPE tinyint , @T_DOG tinyint, @PFNUMBER VARCHAR (14) , @FM VARCHAR(100),@IM VARCHAR(100),@OT VARCHAR(100),
		@pf_num1 VARCHAR(14) , @CODE_old VARCHAR(4), @TYPE_OLD TINYINT, @nom_pp INT, @DATE DATETIME
		set @pf_num1 = ''
		set @CODE_old = '' 
		set @TYPE_OLD = 0
		set @nom_pp = 1

		SET @Cur1 = CURSOR FORWARD_ONLY
		FOR SELECT  [CODE],[TYPE],[PFNUMBER], [FM],[IM],[OT], MIN(DATE_BEGIN) AS DATE_BEGIN  
			FROM #SZV_ALL where [TYPE] = 1 --AND LINK_FACE = 565 
			GROUP BY [FM],[IM],[OT],[PFNUMBER],[TYPE],CODE
			ORDER BY [FM],[IM],[OT],[PFNUMBER],DATE_BEGIN
		OPEN @Cur1
		FETCH NEXT FROM @Cur1 INTO  @CODE,@TYPE/*,@T_DOG*/,@PFNUMBER,@FM,@IM,@OT, @DATE
		WHILE (@@fetch_status <> -1)
		BEGIN

			IF (@@fetch_status <> -2)
			BEGIN
				--- Заполнение информации по первому коду категории сотрудника (нр , оои, пнэд)
				IF (/*@T_DOG = 1 and */ @PFNUMBER <> @pf_num1 ) 
				BEGIN
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE =  @nom_pp,
						   COL1 =  @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0),	
						   COL3 = CONVERT(VARCHAR(100), 'Всего с начала расчетного периода, в том числе за последние три месяца отчетного периода:'),
						   COL4 = CONVERT(VARCHAR(4),'400'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = CASE WHEN @CODE = 'ООИ' THEN ISNULL(SS.SUMMA_ALL_I,0) ELSE ISNULL(SS.SUMMA_ALL - SS.SUMMA_ALL_I,0) END,
						   COL7 = 
								CASE WHEN @CODE = 'ООИ' THEN
										(CASE WHEN
											(ISNULL(SS.SUMMA_ALL_I - SS.SUMMA_NO_I,0) 
											- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face) ,0) ))
											) > @PREDEL 
										THEN @PREDEL
										ELSE 
											(ISNULL(SS.SUMMA_ALL_I - SS.SUMMA_NO_I,0) 
											- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face) ,0) ))
											)
										END)	
									ELSE
										(CASE WHEN 
											( ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0) - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
											- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))
											) > @PREDEL 
										THEN @PREDEL
										ELSE 
											( ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0) - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
											- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))
											) 
										END) 
								 END,
						   COL8 = ISNULL(SS.BASE_DOG,0),
						   COL9 = CASE WHEN @CODE = 'ООИ' THEN
										(CASE WHEN
											(ISNULL(SS.SUMMA_ALL_I,0) - ISNULL(SS.SUMMA_NO_I,0) 
											- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face) ,0) ))
											) > @PREDEL 
										THEN 
											(ISNULL(SS.SUMMA_ALL_I,0) - ISNULL(SS.SUMMA_NO_I,0) 
											- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face) ,0) ))
											) - @PREDEL 
										ELSE 
											0
										END)	
									ELSE
										(CASE WHEN 
											(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0) - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
											- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))
											) > @PREDEL
										THEN 
											(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0) - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
											- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))
											) - @PREDEL
										ELSE 
											0
										END) 
								 END,
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = ISNULL(CONVERT(VARCHAR(1),[per_edt]), ''), 
						   COL14 = ISNULL(CONVERT(VARCHAR(4),[year_edt]), ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT), 
						   COL44 = isnull([INSUR],0)
					FROM #SZV_PC s LEFT JOIN #SALARY_SUM2 ss ON ss.pers_link = s.link_face
					WHERE 
						code = @CODE and [TYPE] = @TYPE AND PFNUMBER = @PFNUMBER
					
					select row_number() over (order by PER_EDT) as ID , 
							[PER_EDT] as k_PER_EDT, 
							YEAR_EDT as k_YEAR_EDT, 
							INSUR - (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum_r1 WHERE CODE = 'НР' AND LINK_pers = s.link_face  )  as k_INSUR, 
							GAIN - (SELECT SUM(SUM_NAK) FROM #tmp_pers_kor_sum_r1 WHERE CODE = 'НР' AND LINK_pers = s.link_face  ) as k_GAIN, 
							PFNUMBER as k_PFNUMBER , 
							FM as k_FM 
					INTO #TMP01
					from  #SZV_ALL s
					WHERE  [TYPE] = 2 AND id_ex =1 and FM = @FM AND PFNUMBER = @PFNUMBER
			
					UPDATE #TMP1
					SET COL19 = (SELECT TOP 1 k_PER_EDT FROM #TMP01 where ID=1),
						COL20 = (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=1),
						COL21 = (CASE WHEN (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=1) >= '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=1)  ELSE 0 END ),
						COL22 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=1) < '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=1) ELSE 0 END ),
						COL23 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=1) < '2014' THEN (SELECT TOP 1 k_GAIN FROM #TMP01 where ID=1) ELSE 0 END ), 
						COL24 = (SELECT TOP 1 k_PER_EDT FROM #TMP01 where ID=2),
					    COL25 = (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=2), 
					    COL26 = (CASE WHEN (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=2) >= '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=2)  ELSE 0 END ), 
					    COL27 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=2) < '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=2) ELSE 0 END ), 
					    COL28 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=2) < '2014' THEN (SELECT TOP 1 k_GAIN FROM #TMP01 where ID=2) ELSE 0 END ),
					    COL29 = (SELECT TOP 1 k_PER_EDT FROM #TMP01 where ID=3),
					    COL30 = (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=3), 
					    COL31 = (CASE WHEN (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=3) >= '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=3)  ELSE 0 END ), 
					    COL32 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=3) < '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=3) ELSE 0 END ), 
					    COL33 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=3) < '2014' THEN (SELECT TOP 1 k_GAIN FROM #TMP01 where ID=3) ELSE 0 END ),
					    COL34 = (SELECT TOP 1 k_PER_EDT FROM #TMP01 where ID=4),
					    COL35 = (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=4), 
					    COL36 = (CASE WHEN (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=4) >= '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=4)  ELSE 0 END ), 
					    COL37 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=4) < '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=4) ELSE 0 END ), 
					    COL38 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=4) < '2014' THEN (SELECT TOP 1 k_GAIN FROM #TMP01 where ID=4) ELSE 0 END ),
					    COL39 = (SELECT TOP 1 k_PER_EDT FROM #TMP01 where ID=5),
					    COL40 = (SELECT TOP 1 k_YEAR_EDT FROM #TMP01 where ID=5), 
					    COL41 = (CASE WHEN (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=5) >= '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=5)  ELSE 0 END ), 
					    COL42 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=5) < '2014' THEN (SELECT TOP 1 k_INSUR FROM #TMP01 where ID=5) ELSE 0 END ), 
					    COL43 = (case when (select TOP 1 k_YEAR_EDT FROM #TMP01 where ID=5) < '2014' THEN (SELECT TOP 1 k_GAIN FROM #TMP01 where ID=5) ELSE 0 END )--,
					FROM #TMP1
					WHERE #TMP1.COL5 = @CODE 
						AND #TMP1.COL12 = ISNULL((case WHEN @TYPE = 1 then 'Исходная' when @TYPE = 2 then 'Корректирующая' else 'Отменяющая'end), '') 
						AND #TMP1.COL2 = @PFNUMBER and #TMP1.COL16 = @FM and #TMP1.COL17 = @IM and #TMP1.COL18 = @OT

					drop table #TMP01

					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14,COL15, COL16,COL17, COL18 , COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,
						   COL2 = ISNULL([PFNUMBER],0),	
						   COL3 = CONVERT(VARCHAR(100), '1 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'401'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = SUM([INC_M1]),
						   COL7 = SUM([B_BEF_M1]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M1] ELSE 0 END),
						   COL9 = SUM([B_AFT_M1]),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year],''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end), ''), 
						   COL13 = ISNULL(CONVERT(VARCHAR(1),[per_edt]), ''), 
						   COL14 = ISNULL(CONVERT(VARCHAR(4),[year_edt]), ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_SUM WHERE code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0),	
						   COL3 = CONVERT(VARCHAR(100), '2 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'402'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = SUM([INC_M2]),
						   COL7 = SUM([B_BEF_M2]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M2] ELSE 0 END),
						   COL9 = SUM([B_AFT_M2]),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end ), ''), 
						   COL13 = ISNULL(CONVERT(VARCHAR(1),[per_edt]), ''), 
						   COL14 = ISNULL(CONVERT(VARCHAR(4),[year_edt]), ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_SUM WHERE code = @CODE and [TYPE] = @TYPE AND PFNUMBER = @PFNUMBER
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0),	
						   COL3 = CONVERT(VARCHAR(100), '3 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'403'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = SUM([INC_M3]),
						   COL7 = SUM([B_BEF_M3]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M3] ELSE 0 END),
						   COL9 = SUM([B_AFT_M3]),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end ), ''), 
						   COL13 = ISNULL(CONVERT(VARCHAR(1),[per_edt]), ''), 
						   COL14 = ISNULL(CONVERT(VARCHAR(4),[year_edt]), ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_SUM WHERE code = @CODE and [TYPE] = @TYPE AND PFNUMBER = @PFNUMBER
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]
					
					set @nom_pp = @nom_pp + 1
				END
		
				--- Заполнение информации по следующему коду категории сотрудника (если за расчетный период у сотрудника была не одна категория)
				IF /*@T_DOG = 1 and*/  @PFNUMBER = @pf_num1 and @CODE <> @CODE_old	and  @TYPE = @TYPE_OLD
				BEGIN 

					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0), 
						   COL3 = CONVERT(VARCHAR(100), 'Всего с начала расчетного периода, в том числе за последние три месяца отчетного периода:'),
						   COL4 = CONVERT(VARCHAR(4),'410'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = CASE WHEN @CODE = 'ООИ' then ISNULL(SS.SUMMA_ALL_I,0) ELSE ISNULL(SS.SUMMA_ALL- SS.SUMMA_ALL_I,0) end,
						   COL7 = 
								CASE WHEN @CODE = 'ООИ' THEN
									--база по ООИ
									(ISNULL(SS.SUMMA_ALL_I - SS.SUMMA_NO_I,0) 
									- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face) ,0) ))
									)
								ELSE
									--база по НР
									( (ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0)) - (ISNULL(SS.SUMMA_NO,0) -  ISNULL(SS.SUMMA_NO_I,0))
									- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))
									)
								END
								- --сумма превышения
								CASE WHEN 
									(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_NO,0) 
									- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND ref_phys_pers = s.link_face) ,0) ))
									) > @PREDEL
								THEN
									(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_NO,0) 
									- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND ref_phys_pers = s.link_face) ,0) ))
									) - @PREDEL
								ELSE
									0
								END,	
														
						   COL8 = ISNULL(SS.BASE_DOG,0),

						   COL9 = 
								--сумма превышения
								CASE WHEN 
									(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_NO,0) 
									- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND ref_phys_pers = s.link_face) ,0) ))
									) > @PREDEL
								THEN
									(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_NO,0) 
									- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND ref_phys_pers = s.link_face) ,0) ))
									) - @PREDEL
								ELSE
									0
								END,
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = ISNULL([per_edt], ''), 
						   COL14 = ISNULL([year_edt], ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   COL44 =  isnull([INSUR],0)
					FROM 
						#SZV_PC s LEFT JOIN #SALARY_SUM2 ss ON ss.pers_link = s.link_face
					WHERE 
						code = @CODE and [TYPE] = @TYPE AND PFNUMBER = @PFNUMBER
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0),
						   COL3 = CONVERT(VARCHAR(100), '1 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'411'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = SUM([INC_M1]),
						   COL7 = SUM([B_BEF_M1]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M1] ELSE 0 END),
						   COL9 = SUM([B_AFT_M1]),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end), ''), 
						   COL13 = ISNULL([per_edt], ''), 
						   COL14 = ISNULL([year_edt], ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
						   
					FROM #SZV_SUM WHERE code = @CODE and [TYPE] = @TYPE AND PFNUMBER = @PFNUMBER
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0), 
						   COL3 = CONVERT(VARCHAR(100), '2 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'412'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = SUM([INC_M2]),
						   COL7 = SUM([B_BEF_M2]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M2] ELSE 0 END),
						   COL9 = SUM([B_AFT_M2]),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end ), ''), 
						   COL13 = ISNULL([per_edt], ''), 
						   COL14 = ISNULL([year_edt], ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_SUM WHERE code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0), 
						   COL3 = CONVERT(VARCHAR(100), '3 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'413'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = SUM([INC_M3]),
						   COL7 = SUM([B_BEF_M3]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M3] ELSE 0 END),
						   COL9 = SUM([B_AFT_M3]),
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая' end ), ''), 
						   COL13 = ISNULL([per_edt], ''), 
						   COL14 = ISNULL([year_edt], ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM #SZV_SUM WHERE code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]
					
					set @nom_pp = @nom_pp + 1
				END						

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

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

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

		CLOSE @Cur1
		DEALLOCATE @Cur1

		/*****************************************************/
		-- Собираем информацию по Кореектирующим/Отменяющим
		/*****************************************************/
		DECLARE @Cur2 CURSOR
		set @pf_num1 = ''
		set @CODE_old = '' 
		set @TYPE_OLD = 0
		set @nom_pp = (SELECT MAX(CODE) FROM #TMP1 WHERE COL12= 'Исходная') + 1 
		
		SET @Cur2 = CURSOR FORWARD_ONLY
		FOR SELECT  [CODE],[TYPE]/*,[T_DOG]*/,[PFNUMBER], [FM],[IM],[OT]  FROM #SZV_ALL where /*T_DOG = 1 and*/ [TYPE] != 1 AND YEAR_EDT >=2014 GROUP BY [FM],[IM],[OT],[PFNUMBER],[TYPE],CODE/*, [T_DOG]*/ ORDER BY [FM],[IM],[OT],[PFNUMBER],[TYPE],CODE/*, [T_DOG]*/
		OPEN @Cur2
		FETCH NEXT FROM @Cur2 INTO  @CODE,@TYPE/*,@T_DOG*/,@PFNUMBER,@FM,@IM,@OT
		WHILE (@@fetch_status <> -1)
		BEGIN

			IF (@@fetch_status <> -2)
			BEGIN
				--- Заполнение информации по первому коду категории сотрудника (нр , оои, пнэд)
				IF (/*@T_DOG = 1 and */ @PFNUMBER <> @pf_num1 ) 
				BEGIN
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE =  @nom_pp,
						   COL1 =  @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0),	
						   COL3 = CONVERT(VARCHAR(100), 'Всего с начала расчетного периода, в том числе за последние три месяца отчетного периода:'),
						   COL4 = CONVERT(VARCHAR(4),'400'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = CASE WHEN @CODE = 'ООИ' THEN ISNULL(SS.SUMMA_ALL_I,0) ELSE ISNULL(SS.SUMMA_ALL - SS.SUMMA_ALL_I,0) END,
						   COL7 = 
								CASE WHEN @CODE = 'ООИ' THEN
										(CASE WHEN
											(ISNULL(SS.SUMMA_ALL_I - SS.SUMMA_NO_I,0) 
											- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face) ,0) ))
											) > @PREDEL_K 
										THEN @PREDEL_K
										ELSE 
											(ISNULL(SS.SUMMA_ALL_I - SS.SUMMA_NO_I,0) 
											- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face) ,0) ))
											)
										END)	
									ELSE
										(CASE WHEN 
											( ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0) - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
											- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))
											) > @PREDEL_K 
										THEN @PREDEL_K
										ELSE 
											( ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0) - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
											- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))
											) 
										END) 
								 END,								 

						   COL8 = ISNULL(SS.BASE_DOG,0),

						   COL9 = CASE WHEN @CODE = 'ООИ' THEN
										(CASE WHEN
											(ISNULL(SS.SUMMA_ALL_I,0) - ISNULL(SS.SUMMA_NO_I,0) 
											- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face) ,0) ))
											) > @PREDEL_K 
										THEN 
											(ISNULL(SS.SUMMA_ALL_I,0) - ISNULL(SS.SUMMA_NO_I,0) 
											- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face) ,0) ))
											) - @PREDEL_K 
										ELSE 
											0
										END)	
									ELSE
										(CASE WHEN 
											(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0) - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
											- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))
											) > @PREDEL_K
										THEN 
											(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0) - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
											- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))
											) - @PREDEL_K
										ELSE 
											0
										END) 
								 END,
																			
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = ISNULL(CONVERT(VARCHAR(1),[per_edt]), ''), 
						   COL14 = ISNULL(CONVERT(VARCHAR(4),[year_edt]), ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   COL44 = isnull([INSUR],0)
					FROM 
						#SZV_PC s LEFT JOIN #SALARY_SUM2_K ss ON ss.pers_link = s.link_face
					WHERE 
						code = @CODE and [TYPE] = @TYPE AND PFNUMBER = @PFNUMBER

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

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

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

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

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

		
	drop table #SALARY_SUM2_K
	drop table #SPR_ESN1_K			
	drop table #SPR_ESN1
	drop table #SALARY_SUM2
	drop table #TMP1

	END  
	IF @REP = 2 
	BEGIN 	
		/*Информация по раздеру 6.6 Информация о корректирующих сведениях*/
		/*К Исходным  заполняется в формах  с типом сведений «исходная» в случае, если в последние три месяца отчетного периода плательщиком страховых взносов 
		* корректируются данные, представленные в предыдущие отчетные периоды.При наличии данных в подразделе 6.6 дополнительно, 
		* в обязательном порядке предоставляются корректирующие (отменяющие)  разделы 6 и (или)  формы СЗВ-6-1, и (или) СЗВ-6-2, и (или) СЗВ-6-4.
		*/
		/*Заполняются в исходных , если есть по ним корректирующие */
	
		--- Обьявляем даты корректирующих сведений
			DECLARE @BYDateK	datetime , @nYEAR_K INT, @nMON1 INT, @nMON2 INT, @nMON3 INT
	

			select top 1 
			@BYDateK = (convert(varchar(4),YEAR_EDT)+'0101'),
			@nYEAR_K = YEAR_EDT,
			@nMON1 = (case  PER_EDT when 1 then  1 when 2 then  4 when 3 then  7 when 4 then  10 else 10 end)
			from #SZV_ALL WHERE [TYPE] = 2
			
			SELECT  @nMON2 = @nMON1 +1 , 	
					@nMON3 = @nMON1 +2 	

----------<<<<<<<<< #SPR_ESN для определения скидочной части (кусок ИЗ РСВ)

		/*Корректирующие сведения по физ лицам*/
		SELECT year_edt = p.YEAR_EDT, 
				PER_EDT = p.PER_EDT, 
				link_dep = p.link_dep,
				link_pers = s.link_pers,
				Link_kateg = S.Link_kateg,
				pachka = s.pachka
		INTO #tmp_pers
		FROM 	dbo.SA_SZV4_PACHKA P 
				INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up 															
		where
			P.link in (select link from #DOCS WHERE vid_kor = 2)
			and P.proverka = 1
			and P.vid_kor > 1
			and p.link_dep = @DEP_LINK


		CREATE TABLE #tmp_pers_kor_sum (link INT  , [date] DATETIME, YEAR_degin INT , per INT , vid_kor int, link_dep INT , proverka INT  , CODE VARCHAR(5), link_pers INT , 
										sum_doh NUMERIC(18,2), sum_str NUMERIC(18,2), sum_nak NUMERIC(18,2),sum_dop NUMERIC(18,2) , pachka int) 
	
		DECLARE @Cur_R2 CURSOR, @link int ,@LINK_pers INT, @year_edt INT , @per_edt INT , @Link_kateg INT ,@pachka int
		SET @Cur_R2 = CURSOR FORWARD_ONLY

		FOR SELECT LINK_pers, year_edt, per_edt, Link_kateg ,pachka FROM #tmp_pers ORDER by link_pers

		OPEN @Cur_R2
		FETCH NEXT FROM @Cur_R2 INTO @LINK_pers, @year_edt, @per_edt , @link_kateg, @pachka
		WHILE (@@fetch_status <> -1)
		BEGIN

			IF (@@fetch_status <> -2)
			BEGIN
				
				
					SET @link = 0
					
					SELECT @link =max(pp.link)
					FROM SA_SZV4_PACHKA pp 
					INNER JOIN dbo.SZV4_SVEDENIA Ss ON ss.link_up = pp.link  
					WHERE  pp.proverka = 1 AND pp.vid_kor = 1 
										  AND pp.link_dep = @DEP_LINK 
										  AND pp.year_begin =@year_edt  
										  AND pp.PER =@per_edt 
										  AND @LINK_pers = ss.link_pers
										  AND @link_kateg = ss.link_kateg  
										  AND pp.date = (SELECT MAX(p1.[date]) FROM SA_SZV4_PACHKA p1 
																INNER JOIN dbo.SZV4_SVEDENIA S1 ON s1.link_up = p1.link  
																WHERE  pp.proverka = 1 AND p1.vid_kor = 1 
																					  AND p1.link_dep = @DEP_LINK 
																					  AND p1.year_begin =@year_edt  
																					  AND p1.PER =@per_edt 
																					  AND @LINK_pers = s1.link_pers
																					  AND @link_kateg = s1.link_kateg )
					
					INSERT INTO #tmp_pers_kor_sum (link, [date], YEAR_degin, per, vid_kor, link_dep, proverka , CODE, link_pers, 
										sum_doh, sum_str, sum_nak,sum_dop, pachka) 
					SELECT pp.link, pp.[date], pp.YEAR_begin, pp.per, pp.vid_kor, pp.link_dep, pp.proverka, CODE = k.code, ss.link_pers, 
										ss.sum_doh, ss.sum_str, ss.sum_nak,ss.sum_dop , pachka = @pachka
					FROM SA_SZV4_PACHKA pp 
					INNER JOIN dbo.SZV4_SVEDENIA Ss ON ss.link_up = pp.link  
					INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = ss.LINK_KATEG AND pp.YEAR_begin BETWEEN YBEG AND YEND		
					WHERE pp.link = @link and pp.proverka = 1 
										 AND pp.vid_kor = 1 
										 AND pp.link_dep = @DEP_LINK 
										 AND pp.year_begin =@year_edt  
										 AND pp.PER =@per_edt 
										 AND ss.link_pers = @LINK_pers
										 AND ss.link_kateg = @link_kateg
										  

			END

			FETCH NEXT FROM @Cur_R2 INTO @LINK_pers, @year_edt, @per_edt, @link_kateg, @pachka
		END

		CLOSE @Cur_R2
		DEALLOCATE @Cur_R2


---------->>>>>>>>>>
		create table #TMP2(CODE int identity(1,1) ,col1 int,   COL2 tinyint, COL3 varchar(4), COL4 numeric(18,2), COL5 numeric(18,2), COL6 numeric(18,2), COL7 VARCHAR(14), COL8 INT)

		INSERT INTO #TMP2 (COL2, COL3, COL4, COL5, COL6, COL7)
		SELECT 
			   COL2 = /*case when YEAR_EDT between '2011' and '2013'  then (case*/ [PER_EDT]/* when 1 then 1 when 2 then 2 when 3 then 3 when 4 then 4 else 0 end)
							when YEAR_EDT = '2014' then (case [PER_EDT] when 1 then 3 when 2 then 6 when 3 then 9 when 4 then 0 else null end) end */, 
			   COL3 = CONVERT(VARCHAR(4),YEAR_EDT),
			   COL4 = (CASE WHEN YEAR_EDT = '2014' THEN INSUR - (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum WHERE CODE = 'НР' AND LINK_pers = s.link_face  )  ELSE 0 END ),
			   COL5 = (CASE WHEN YEAR_EDT < '2014' THEN INSUR - (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum WHERE CODE = 'НР' AND LINK_pers = s.link_face  )  ELSE 0 END ),
			   COL6 = (CASE WHEN YEAR_EDT < '2014' THEN GAIN - (SELECT SUM(SUM_NAK) FROM #tmp_pers_kor_sum WHERE CODE = 'НР' AND LINK_pers = s.link_face  )   ELSE 0 END ),
			   COL7 = CONVERT(VARCHAR(14),PFNUMBER)
		FROM #SZV_ALL s WHERE  [TYPE] = 2 AND id_ex =1 
		GROUP BY link_face, YEAR_EDT,  [PER_EDT] , INSUR , GAIN ,[FM],[IM],[OT], PFNUMBER 
		ORDER BY [FM],[IM],[OT],[PFNUMBER]
		
		UPDATE #TMP2 
			SET col1 = CODE , COL8 = CODE 

		
		SELECT * FROM #TMP2 ORDER BY CODE


		drop table #tmp_pers
		drop table #tmp_pers_kor_sum
		--DROP TABLE #SPR_ESN_K
		drop table #TMP2
		--GROUP BY [TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[per_edt],[year_edt]	
	

	
	END	
		
	IF @REP = 3 
	BEGIN 	
		/*Информация по раздеру 6.7 Сведения о сумме выплат и иных вознаграждений в пользу физического лица, занятого на соответствующих видах работ, 
		* с которых начислены страховые взносы по дополнительному тарифу для отдельных категорий плательщиков страховых взносов, указанных в частях 1, 2 и 2.1 статьи 58.3 
		* Федерального закона от 24 июля 2009 г. № 212-ФЗ */

	/*****************************************************/
	-- Собираем информацию по Исходным пачками
	/*****************************************************/

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

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

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

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


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

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



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


		
		DECLARE @Cur3 CURSOR, @CODE1 varchar(4), @TYPE1 tinyint , @PFNUMBER1 VARCHAR (14) , @FM1 VARCHAR(100),@IM1 VARCHAR(100),@OT1 VARCHAR(100),
		@pf_num11 VARCHAR(14) ,@TYPE_OLD1 TINYINT, @nom_pp1 INT, @OSOB_SPO VARCHAR(4), @OSOB_SPO_old VARCHAR(4),
		@DateM1B DATETIME, @DateM2B DATETIME, @DateM3B DATETIME, @DateM1E DATETIME, @dateM2E DATETIME, @dateM3E DATETIME
		set @pf_num11 = ''
		set @OSOB_SPO_old = NULL 
		set @TYPE_OLD1 = 0
		set @nom_pp1 = 1
		
		SELECT @DateM1B = @dDate1,
			   @DateM2B =  dbo.ConvertDMY2Date(1,month(@dDate1)+1,YEAR(@dDate1)), 	
			   @DateM3B =  dbo.ConvertDMY2Date(1,month(@dDate1)+2,YEAR(@dDate1)), 
			   @DateM1E =  dbo.DateEndOfMonth(@DateM1B),
			   @DateM2E =  dbo.DateEndOfMonth(@DateM2B), 	
			   @DateM3E =  @dDate2

		SET @Cur3 = CURSOR FORWARD_ONLY
		FOR SELECT  [CODE],[TYPE],[PFNUMBER], [FM],[IM],[OT], [OSOB_SPO]  FROM #SZV_ALL where /*T_DOG = 1 and*/ [TYPE] = 1  GROUP BY [FM],[IM],[OT],[PFNUMBER],[TYPE],CODE, [OSOB_SPO] ORDER BY [FM],[IM],[OT],[PFNUMBER],[TYPE],CODE, [OSOB_SPO]
		OPEN @Cur3
		FETCH NEXT FROM @Cur3 INTO  @CODE1,@TYPE1,@PFNUMBER1,@FM1,@IM1,@OT1, @OSOB_SPO
		WHILE (@@fetch_status <> -1)
		BEGIN

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

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




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

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

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

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

					drop table #TMP03				

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

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

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

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

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

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

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


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

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

					drop table #TMP04	


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

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

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

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

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

		UPDATE #TMP4 
			SET col1 = CODE , COL11 = CODE 

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

END

GO


GRANT EXECUTE ON dbo.[RSA_RSV_1_PERS_UCH_SZV] TO PUBLIC

GO




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

GO


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

SET NOCOUNT ON

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @CUR_EPML
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			
			SET @Cur2 = CURSOR FORWARD_ONLY
			FOR SELECT m, y, DATE_BEGIN FROM dbo.months_ex(@DATE_BEGIN_RP, @DATE_END_RP) 
			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')

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

	--
	Select 
		PERIOD = dbo.ConvertDMY2Date(31,12,YEAR(MIN(PERIOD))), PERIOD1 = YEAR(PERIOD), CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, 
		SUMMA = SUM( CASE WHEN WAY_CALC = 6 AND (DATEDIFF(MONTH,DATE1, DATE2) + 1) <> 0 AND @UCHET_PREM = 1 THEN 
					CONVERT(NUMERIC(18,2), SUMMA * 
						(DATEDIFF(MONTH,CASE WHEN DATE1 <= @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, @DATE_BEGIN

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	----
	UPDATE @PERIODY
	SET 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

SET @I = 0

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

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

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

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

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

IF @OPER = 1 
	exec dbo.SD_N_BOL_PROV @LINK_DOC

SET NOCOUNT OFF

GO


GRANT EXECUTE ON dbo.[SA_N_BOL_FILL2] TO PUBLIC

GO

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

GO


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

SET NOCOUNT ON

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		SET @TYP_PERIOD = 1

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

	END

	---
	IF @TYP_PERIOD = 1

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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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


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

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

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

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

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

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

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

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

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

SET @I = 0
UPDATE dbo.SDOC_ADIS_TABLE1  

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

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

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

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

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

IF @OPER = 1 
	exec dbo.SD_N_BOL_PROV @LINK_DOC

SET NOCOUNT OFF

GO


GRANT EXECUTE ON dbo.[SA_N_BOL_FILL1] TO PUBLIC

GO

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

GO

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

SET NOCOUNT ON

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

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

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

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

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

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

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

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

END


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

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

END

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

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

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

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

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

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

---

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

			CLOSE @Cur2
			DEALLOCATE @Cur2				

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

		FETCH NEXT FROM @Cur1 INTO @NEXT_DATE
	END

	CLOSE @Cur1
	DEALLOCATE @Cur1

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

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

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

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

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

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

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

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

/***************************************************************************************/
DECLARE @DEFAULT_KBK INT
SET @DEFAULT_KBK = (Select TOP 1 KBK.LINK_KBK FROM dbo.KU_EmplStafKBK(default) KBK WHERE KBK.LINK_EMPL = @LINK_EMPL)
SET @DEFAULT_KBK = ISNULL((SELECT CH.NEW_LINK FROM dbo.SAL_SFIN_CHANGES(@DATE_BEGIN) CH WHERE CH.LINK = @DEFAULT_KBK),@DEFAULT_KBK)
	
--
IF @RECALC = 0  --- Расчет сумм по видам начислений
BEGIN

	--- Промежуточная база расчета
	CREATE TABLE #BASE1 (
		PERIOD DATETIME,
		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 #BASE1 (PERIOD, NADB, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, SUM0, KOEF, CV, LINK_VKR, DATE1, DATE2)
	exec dbo.SD_BASE_SUM_PAY_DIF_PERIODS @LINK_PAYS, @LINK_EMPL, @DATE_BEGIN_RP, @DATE_END_RP, @OBJ_CODE, @DATE_BEGIN, @DATE_END_RP

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

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

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

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

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

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

	IF @INDEX2 > 1 BEGIN

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	exec (@SCRIPT)

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

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

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

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

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

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

	END

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

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

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

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

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

END	--IF @RECALC < = 1

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

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

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

	END

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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



GO


GRANT EXECUTE ON dbo.[SA_N_VAC_FILL1] TO PUBLIC

GO

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

GO

/*

 DECLARE @Res float
SET @Res = 0
 exec [dbo].RSA_RSV_1_14_PFR_PREPARE @Res output, '', '20140101', '20140331', 3, 0, 2494
 select @Res 	
 
 --SELECT * FROM REPORT_SAVED_FORMS ORDER BY Link_Saved_Form

*/

CREATE PROCEDURE dbo.RSA_RSV_1_14_PFR_PREPARE 
	@Res float output, @varcStr varchar(250), @vardBegin datetime = '20050101', @vardEnd datetime = '20051231', @variCol int, @variRow int, @variLSF int
AS 

DECLARE @OUT_VAL NUMERIC(20), @START_DATE DATETIME, @END_DATE DATETIME, @DEP_LINK INT, @TFOMS_KT int

DECLARE --Для выравнивания погрешности
	@C3S NUMERIC(18,6), @C4S NUMERIC(18,6), @C5S NUMERIC(18,6), @C6S NUMERIC(18,6),
	@C3N NUMERIC(18,6), @C4N NUMERIC(18,6), @C5N NUMERIC(18,6), @C6N NUMERIC(18,6),
	@C3SS NUMERIC(18,6), @C4SS NUMERIC(18,6), @C5SS NUMERIC(18,6), @C6SS NUMERIC(18,6),
	@C3NS NUMERIC(18,6), @C4NS NUMERIC(18,6), @C5NS NUMERIC(18,6), @C6NS NUMERIC(18,6)	

select @DEP_LINK = Link_Organization from report_saved_forms where link_saved_form =  @variLSF

set @TFOMS_KT = (select  (case when TFOMS_KT = '' then '01' else TFOMS_KT end)  from dictionary_department where link = @DEP_LINK)

set @res = 0
SELECT @START_DATE = @vardBegin, @END_DATE = @vardEnd

DECLARE @BYearDate	datetime
SET @BYearDate = dbo.DateBeginOfYear (@START_DATE)

DECLARE @nYEAR INT, @nMONTH1 INT, @nMONTH2 INT, @nMONTH3 INT

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

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

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

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


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


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

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

DECLARE @C1_PERIOD_BEG DATETIME, @C1_PERIOD_END DATETIME

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


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



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

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


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

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

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

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

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


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

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


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

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

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

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


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

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

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


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

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




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

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

--
DROP TABLE #SALARY_SUM_DATA	

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

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

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

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

	IF (@@fetch_status <> -2)
	BEGIN

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

	END

	FETCH NEXT FROM @Cur1 INTO @LINK_ACC
END

CLOSE @Cur1
DEALLOCATE @Cur1

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

DECLARE @Cur2 CURSOR
SET @Cur2 = CURSOR FORWARD_ONLY

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

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

	IF (@@fetch_status <> -2)
	BEGIN

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

	END

	FETCH NEXT FROM @Cur2 INTO @LINK_ACC
END

CLOSE @Cur2
DEALLOCATE @Cur2

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

DECLARE @Cur3 CURSOR
SET @Cur3 = CURSOR FORWARD_ONLY

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

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

	IF (@@fetch_status <> -2)
	BEGIN

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

	END

	FETCH NEXT FROM @Cur3 INTO @LINK_ACC
END

CLOSE @Cur3
DEALLOCATE @Cur3

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

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

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

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

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

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

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

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

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

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



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


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

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

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

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

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

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

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


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

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

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


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





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

-----


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

SELECT @LIMIT = MAX(S.PREDEL)
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3
WHERE 
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3 AND [DATE] < @END_DATE ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
	
SET @LIMIT = ISNULL(@LIMIT,0)

--  тариф, применяемый  свыше установленного предела величины базы (%)

-- по наемным рабочим
-- так как с 2014 года процент ставок одинаковый  для всех возрастов , берем процент  по возрасту "с 1967"
DECLARE 
	@PERCENT NUMERIC(18,2),
	-- накопительной части с 2014 года нет
	-- @PERCENT_N NUMERIC(18,2)  -- 
	@PERCENT_OMS NUMERIC(18,2), @IPERCENT_OMS NUMERIC(18,2) 
	
SELECT 
	@PERCENT = S.PERCENT3
FROM 
	dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 
WHERE
	predel = @LIMIT
	and tarif =1
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 AND [DATE] < @END_DATE where 	s1.predel = @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT3 > 0
	
SET @PERCENT = ISNULL(@PERCENT,0)	

--
SELECT @PERCENT_OMS = S.PERCENT1
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3
WHERE
	predel = @LIMIT
	and tarif =1
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3 AND [DATE] < @END_DATE where 	s1.predel = @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0

--
SELECT @IPERCENT_OMS = S.PERCENT1
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3
WHERE
	predel = @LIMIT
	and tarif =3
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 3 AND [DATE] < @END_DATE where 	s1.predel = @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0	

SET @PERCENT_OMS = ISNULL(@PERCENT_OMS,0)	
SET @IPERCENT_OMS = ISNULL(@IPERCENT_OMS,0)

-- по инвалидам
   --- страховая часть 
DECLARE @IPERCENT NUMERIC(28,2)
SELECT @IPERCENT = S.PERCENT3
FROM 
	dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 
WHERE
	predel = @LIMIT
	and tarif = 3
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 AND [DATE] < @END_DATE where 	s1.predel = @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
SET @IPERCENT = ISNULL(@IPERCENT,0)

	
   --- накопительная часть  с 2014 года отсутствует 
/*   */
-----

SELECT MON = 1, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1 FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 2, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 2 AND @nMONTH3 >= 3 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 3, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 3 AND @nMONTH3 >= 3 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 4, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 4 AND @nMONTH3 >= 6 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 5, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 5 AND @nMONTH3 >= 6 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 6, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 6 AND @nMONTH3 >= 6 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 7, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 7 AND @nMONTH3 >= 9 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 8, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 8 AND @nMONTH3 >= 9 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 9, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 9 AND @nMONTH3 >= 9 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 10, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 10 AND @nMONTH3 >= 12 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 11, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 11 AND @nMONTH3 >= 12 AND I = 1  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 12, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 12 AND @nMONTH3 >= 12 AND I = 1  GROUP BY REF_PHYS_PERS

SELECT DISTINCT T.REF_PHYS_PERS, M.M, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2
FROM 
	#SPR_ESN1 T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1 T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1
--WHERE
--	(ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)) > 0

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '203',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 9) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 10) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 11) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = 12) ,0))										
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH3) ,0))

--Начислено страховых взносов на обяза-тельное пенсионное страхование
--страховая часть

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '205',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18,2),ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 ) ,0)) 
	ELSE
		CONVERT(numeric(18,2),ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0))
	END,	
	CONVERT(numeric(18,2),ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0))


DECLARE @PERC1 NUMERIC(28,2), @IPERC1 NUMERIC(28,2)
-- для рабочих
SELECT @PERC1 = S.PERCENT1

FROM 
	dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 
WHERE
	predel > @LIMIT
	and 
	tarif = 1
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 AND [DATE] < @END_DATE where 	s1.predel > @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
SET @PERC1 = ISNULL(@PERC1,0)	
-- для инвалидов
SELECT @IPERC1 = S.PERCENT1

FROM 
	dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 
WHERE
	predel > @LIMIT
	and 
	tarif = 3
	and
	[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S1 INNER JOIN DBO.PAYS P ON S1.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = 6 AND [DATE] < @END_DATE where 	s1.predel > @LIMIT
	 ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
SET @IPERC1 = ISNULL(@IPERC1,0)	


--- с сумм, превышающих предельную величину базы	
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '206',
	CASE WHEN @nMONTH3 > 3 THEN
		(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2) ,0)) * @PERC1)/100
	ELSE
		((CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE  M = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH3) ,0))) * @PERC1)/100 	
	END,	
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH1) ,0)) * @PERC1)/100,
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH2) ,0)) * @PERC1)/100,
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2 WHERE M = @nMONTH3) ,0)) * @PERC1)/100	


update #RES2
	set C3 = (c3 - (select c3 from #RES2 where code_str = '206' )) , 
	C4 = (c4 - (select c4 from #RES2 where code_str = '206' )),
	C5= (c5 - (select c5 from #RES2 where code_str = '206' )),
	C6= (c6 - (select c6 from #RES2 where code_str = '206' ))
 from #RES2 
 where code_str = '205'

--SELECT * FROM #SPR_ESN WHERE  MONTH_BASE >= @nMONTH1 AND I = 1
--SELECT * FROM #SPR_ESN WHERE  MONTH_BASE >= @nMONTH1 AND I = 2

-- Количество чел , кому начислялись страховые взносы
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '207',
	CASE WHEN @nMONTH3 > 3 THEN
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 1 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 2 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 3 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 4 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 5 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 6 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 7 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 8 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 9 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 10 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 11 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = 12 AND MONTH_BASE <= @nMONTH3) T
			),0)
	ELSE
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = @nMONTH1
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = @nMONTH2
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = @nMONTH3) T
			),0)
	END,	
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 1 and MONTH_BASE = @nMONTH3) ,0) 		


-- Количество чел , чей лимит превышен
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '208',
	CASE WHEN @nMONTH3 > 3 THEN
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and M = 1 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 2 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 3 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 4 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 5 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 6 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 7 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 8 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 9 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 10 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 11 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = 12 AND M <= @nMONTH3) T
			),0)
	ELSE
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH1
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH2
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH3) T
			),0)
	END,	
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN2 where summa != 0 and  M = @nMONTH3) ,0) 	
	
----- на обязательное медицинское страхование
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '210', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))	 					 	 					 			 					 
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
FROM #SALARY_SUM2		 


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

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

	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),0)
		WHEN 6 THEN
			CONVERT(numeric(18,2),0)
		WHEN 9 THEN
			CONVERT(numeric(18,2),0)
		WHEN 12 THEN
			CONVERT(numeric(18,2),0)
	END,
		
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0)


SELECT MON = 1, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1M FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS 
INSERT INTO #SPR_ESN1M SELECT MON = 2, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 2 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 3, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 3 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 4, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 4 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 5, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 5 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 6, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 6 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 7, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 7 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 8, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 8 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 9, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 9 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 10, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 10 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 11, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 11 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1M SELECT MON = 12, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND  MONTH_BASE <= 12 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS

SELECT DISTINCT T.REF_PHYS_PERS, M.M, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2M 
FROM 
	#SPR_ESN1M T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1M T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1M T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1

---  Суммы, превышающие предельную величину базы для начисления страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '213',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 9) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 10) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 11) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = 12) ,0))										
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2M WHERE M = @nMONTH3) ,0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '215',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3  AND I = 1) ,0))
	ELSE
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0))	
	END,	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0))	


--ВЫРАВНИВАНИЕ ПОГРЕШНОСТИ ПО ОСНОВНОМУ ТАРИФУ
/*
--Способ заполнения страховых взносов
Выриант №1. Сумма всзносов по организации рассчитывается  по формулам расчёта для РСВ-1 от общих сумм дохода и необлагаемых сумм. 
Выриант №2. Сумма взносов по организации рассчитывается как сумма взносов, начисленных по физлицам. 
Выриант №3. Сумма взносов по организации рассчитывается как сумма взносов, начисленных по физлицам. 
Но при этом для того, чтобы выполнялись контрольные соотношения по форме, выполняется подгон необлагаемых сумм.
*/
DECLARE @SALARY_OPTIONS_OPT6_1 INT 
SET @SALARY_OPTIONS_OPT6_1 =  dbo.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPT6_1')

------------------------------------------------------------------------------------
----- расчет погрешностей для 2014 года
	IF ISNULL(@PERCENT,0) > 0
	BEGIN
		--Вычисление погрешности для страховой части	
		SELECT 
			@C3S = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 204 = 
						(CASE WHEN CODE_STR = '200' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '201' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '202' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '203' THEN C3 ELSE 0 END)
					)) * @PERCENT/100
					- CONVERT(NUMERIC(18,6), (SELECT SUM(C3) FROM #RES2 WHERE CODE_STR = '205'))
				) / (@PERCENT/100)	
			),

			@C3SS = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 204 = 
						(CASE WHEN CODE_STR = '200' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '201' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '202' THEN C3 ELSE 0 END)
						-(CASE WHEN CODE_STR = '203' THEN C3 ELSE 0 END)
					)) * @PERCENT/100
				)
			),

			@C4S = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 204 = 
						(CASE WHEN CODE_STR = '200' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '201' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '202' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '203' THEN C4 ELSE 0 END)
					)) * @PERCENT/100
					- CONVERT(NUMERIC(18,6),(SELECT SUM(C4) FROM #RES2 WHERE CODE_STR = '205'))
				) / (@PERCENT/100)	
			),

			@C4SS = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 204 = 
						(CASE WHEN CODE_STR = '200' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '201' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '202' THEN C4 ELSE 0 END)
						-(CASE WHEN CODE_STR = '203' THEN C4 ELSE 0 END)
					)) * @PERCENT/100
				)
			),			
			
			@C5S = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 204 = 
						(CASE WHEN CODE_STR = '200' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '201' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '202' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '203' THEN C5 ELSE 0 END)
					)) * @PERCENT/100
					- CONVERT(NUMERIC(18,6),(SELECT SUM(C5) FROM #RES2 WHERE CODE_STR = '205'))
				) / (@PERCENT/100)	
			),		

			@C5SS = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 204 = 
						(CASE WHEN CODE_STR = '200' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '201' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '202' THEN C5 ELSE 0 END)
						-(CASE WHEN CODE_STR = '203' THEN C5 ELSE 0 END)
					)) * @PERCENT/100
				)
			),					

			@C6S = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 204 = 
						(CASE WHEN CODE_STR = '200' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '201' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '202' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '203' THEN C6 ELSE 0 END)
					)) * @PERCENT/100
					- CONVERT(NUMERIC(18,6), (SELECT SUM(C6) FROM #RES2 WHERE CODE_STR = '205'))
				) / (@PERCENT/100)						
			),

			@C6SS = CONVERT(NUMERIC(18,2),
				(
					CONVERT(NUMERIC(18,6), SUM( --Стр 204 = 
						(CASE WHEN CODE_STR = '200' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '201' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '202' THEN C6 ELSE 0 END)
						-(CASE WHEN CODE_STR = '203' THEN C6 ELSE 0 END)
					)) * @PERCENT/100
				)
			)	
			
		FROM #RES2
		WHERE
			CODE_STR IN ('200', '201', '202', '203' )

		IF @SALARY_OPTIONS_OPT6_1 = 1
		BEGIN
			UPDATE #RES2
			SET
				C3 = CASE WHEN @nMONTH3 = 3 THEN ISNULL(@C4SS,0) + ISNULL(@C5SS,0) + ISNULL(@C6SS,0) 
						ELSE ISNULL(@C3SS,0)
					END,			
				C4 = ISNULL(@C4SS,0),
				C5 = ISNULL(@C5SS,0),
				C6 = ISNULL(@C6SS,0)
			WHERE 
				CODE_STR = '205'
			
		END
------------------------------------------------------------------------------------
		--Корректируем необлагаемые суммы на копейки округления
		
		--Досчет по базе закомментарил
		 
		IF @SALARY_OPTIONS_OPT6_1 = 3
		BEGIN
			UPDATE #RES2
			SET
				C3 = C3 + ISNULL(@C3S,0),
				C4 = C4 + ISNULL(@C4S,0),
				C5 = C5 + ISNULL(@C5S,0),
				C6 = C6 + ISNULL(@C6S,0)			 
			WHERE 
				CODE_STR = '201'
		END		
	
	END	

--- накопительной части в 2014 нет
	--IF @SALARY_OPTIONS_OPT6_1 = 1
	--BEGIN
	--		UPDATE #RES2
	--		SET
	--			C3 = CASE WHEN @nMONTH3 = 3 THEN ISNULL(@C4NS,0) + ISNULL(@C5NS,0) + ISNULL(@C6NS,0) ELSE ISNULL(@C3NS,0) END,
	--			C4 = ISNULL(@C4NS,0),
	--			C5 = ISNULL(@C5NS,0),
	--			C6 = ISNULL(@C6NS,0)
	--		WHERE 
	--			CODE_STR = '251'
	--END


	--IF @SALARY_OPTIONS_OPT6_1 = 3
	--BEGIN
	--	UPDATE #RES2
	--	SET
	--		C3 = C3 + ISNULL(@C3N,0),
	--		C4 = C4 + ISNULL(@C4N,0),
	--		C5 = C5 + ISNULL(@C5N,0),
	--		C6 = C6 + ISNULL(@C6N,0)			 
	--	WHERE 
	--		CODE_STR = '212'
	--END		

--END		


IF ISNULL(@PERCENT_OMS,0) > 0
BEGIN
	--Вычисление погрешности для ОМС	
	SELECT 
		@C3N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 215 = 
					(CASE WHEN CODE_STR = '210' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '211' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '213' THEN C3 ELSE 0 END)
				) * @PERCENT_OMS/100
				- (SELECT SUM(C3) FROM #RES2 WHERE CODE_STR = '215')
			) / (@PERCENT_OMS/100)
		),
		@C3NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 215 = 
					(CASE WHEN CODE_STR = '210' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '211' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '213' THEN C3 ELSE 0 END)
				) * @PERCENT_OMS/100
			)
		),
		@C4N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 215 = 
					(CASE WHEN CODE_STR = '210' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '211' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '213' THEN C4 ELSE 0 END)
				) * @PERCENT_OMS/100
				- (SELECT SUM(C4) FROM #RES2 WHERE CODE_STR = '215')
			) / (@PERCENT_OMS/100)
		),
		@C4NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 215 = 
					(CASE WHEN CODE_STR = '210' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '211' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '213' THEN C4 ELSE 0 END)
				) * @PERCENT_OMS/100
			)
		),
		@C5N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 215 = 
					(CASE WHEN CODE_STR = '210' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '211' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '213' THEN C5 ELSE 0 END)
				) * @PERCENT_OMS/100
				- (SELECT SUM(C5) FROM #RES2 WHERE CODE_STR = '215')
			) / (@PERCENT_OMS/100)
		),
		@C5NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 215 = 
					(CASE WHEN CODE_STR = '210' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '211' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '213' THEN C5 ELSE 0 END)
				) * @PERCENT_OMS/100
			)
		),		
		@C6N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 215 = 
					(CASE WHEN CODE_STR = '210' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '211' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '213' THEN C6 ELSE 0 END)
				) * @PERCENT_OMS/100
				- (SELECT SUM(C6) FROM #RES2 WHERE CODE_STR = '215')
			) / (@PERCENT_OMS/100)
		),
		@C6NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 215 = 
					(CASE WHEN CODE_STR = '210' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '211' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '212' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '213' THEN C6 ELSE 0 END)
				) * @PERCENT_OMS/100
			)
		)					
	FROM #RES2
	WHERE
		CODE_STR IN ('210', '211', '212', '213')

	IF @SALARY_OPTIONS_OPT6_1 = 1
	BEGIN
		UPDATE #RES2
		SET
			C3 = CASE WHEN @nMONTH3 = 3 THEN ISNULL(@C4NS,0) + ISNULL(@C5NS,0) + ISNULL(@C6NS,0) ELSE ISNULL(@C3NS,0) END,
			C4 = ISNULL(@C4NS,0),
			C5 = ISNULL(@C5NS,0),
			C6 = ISNULL(@C6NS,0)
		WHERE 
			CODE_STR = '215'
		
	END

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

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

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


--	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND FACE_GROUP = 1 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE FACE_GROUP = 1 AND MON = @nMONTH1),0)),
/* DECLARE @Res float
SET @Res = 0
 exec RSA_RSV_1_13_PFR_PREPARE @Res output, '', '20130401', '20130630', 2, 2, 170
 select @Res 	
*/
----- Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ 
----- (отражаются суммы фактически произведенных и документально подтвержденных расходов, связанных с извлечением доходов, 
-----  полученных по договору авторского заказа, договору об отчуждении исключительного права на произведения науки, литературы, 
-----  искусства, издательскому лицензионному договору, лицензионному договору о предоставлении права использования произведения науки, 
-----  литературы, искусства или суммы расходов, которые не могут быть подтверждены документально и принимаемые к вычету)
-----  Сейчас заполняем нулями
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2020',
	
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),0)
		WHEN 6 THEN
			CONVERT(numeric(18,2),0)
		WHEN 9 THEN
			CONVERT(numeric(18,2),0)
		WHEN 12 THEN
			CONVERT(numeric(18,2),0)
	END,	
	
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0)
	
----


SELECT MON = 1, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1I FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 2, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 2 AND @nMONTH3 >= 3 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 3, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 3 AND @nMONTH3 >= 3 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 4, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 4 AND @nMONTH3 >= 6 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 5, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 5 AND @nMONTH3 >= 6 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 6, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 6 AND @nMONTH3 >= 6 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 7, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 7 AND @nMONTH3 >= 9 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 8, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 8 AND @nMONTH3 >= 9 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 9, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 9 AND @nMONTH3 >= 9 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 10, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 10 AND @nMONTH3 >= 12 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 11, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 11 AND @nMONTH3 >= 12 AND I = 2  GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1I SELECT MON = 12, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 12 AND @nMONTH3 >= 12 AND I = 2  GROUP BY REF_PHYS_PERS

SELECT DISTINCT T.REF_PHYS_PERS, M.M, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2I
FROM 
	#SPR_ESN1I T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1I T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1I T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1
--WHERE
--	(ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)) > 0


-- Суммы превышающие величину базы 

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2030',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 9) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 10) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 11) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = 12) ,0))										
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH3) ,0))

--Начислено страховых взносов на обяза-тельное пенсионное страхование
--страховая часть

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2050',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 ) ,0)) 
	ELSE
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0))
	END,	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0))


--- с сумм, превышающих предельную величину базы	
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2060',
	CASE WHEN @nMONTH3 > 3 THEN
		(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I) ,0)) * @IPERC1)/100
	ELSE
		((CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE  M = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH3) ,0))) * @IPERC1)/100 	
	END,	
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH1) ,0)) * @IPERC1)/100,
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH2) ,0)) * @IPERC1)/100,
	(CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2I WHERE M = @nMONTH3) ,0)) * @IPERC1)/100	


update #RES2
	set C3 = (c3 - (select c3 from #RES2 where code_str = '2060' )) , 
	C4 = (c4 - (select c4 from #RES2 where code_str = '2060' )),
	C5= (c5 - (select c5 from #RES2 where code_str = '2060' )),
	C6= (c6 - (select c6 from #RES2 where code_str = '2060' ))
 from #RES2 
 where code_str = '2050'

-- Количество чел , чей лимит НЕ превышен
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2070',
	CASE WHEN @nMONTH3 > 3 THEN
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and MONTH_BASE = 1 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 2 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 3 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 4 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 5 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 6 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 7 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 8 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 9 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 10 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 11 AND MONTH_BASE <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = 12 AND MONTH_BASE <= @nMONTH3) T
			),0)
	ELSE
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = @nMONTH1
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = @nMONTH2
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = @nMONTH3) T
			),0)
	END,	
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 AND I = 2 and  MONTH_BASE = @nMONTH3) ,0) 		

-- Количество чел , чей лимит превышен

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2080',
	CASE WHEN @nMONTH3 > 3 THEN
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and M = 1 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 2 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 3 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 4 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 5 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 6 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 7 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 8 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 9 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 10 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 11 AND M <= @nMONTH3
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = 12 AND M <= @nMONTH3) T
			),0)
	ELSE
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH1
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH2
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH3) T
			),0)
	END,	
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN2I where summa != 0 and  M = @nMONTH3) ,0) 	
	
----- на обязательное медицинское страхование
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2100', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL_I ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL_I ELSE 0 END))
 					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL_I ELSE 0 END))	 					 	 					 			 					 
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL_I ELSE 0 END)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL_I ELSE 0 END))
FROM #SALARY_SUM2		 


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

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

	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),0)
		WHEN 6 THEN
			CONVERT(numeric(18,2),0)
		WHEN 9 THEN
			CONVERT(numeric(18,2),0)
		WHEN 12 THEN
			CONVERT(numeric(18,2),0)
	END,
		
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0)


SELECT MON = 1, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1IM FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 2, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 2 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 3, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 3 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 4, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 4 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 5, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 5 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 6, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 6 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 7, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 7 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 8, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 8 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 9, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 9 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 10, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 10 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 11, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 11 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1IM SELECT MON = 12, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND  MONTH_BASE <= 12 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS

SELECT DISTINCT T.REF_PHYS_PERS, M.M, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2IM 
FROM 
	#SPR_ESN1IM T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1IM T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1IM T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1

---  Суммы, превышающие предельную величину базы для начисления страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2130',

	CASE @nMONTH3 
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 3) ,0))	
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 6) ,0))	
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 9) ,0))	
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 2) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 3) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 4) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 5) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 6) ,0))	
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 7) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 8) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 9) ,0))			
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 10) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 11) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = 12) ,0))										
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN2IM WHERE M = @nMONTH3) ,0))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2150',
	CASE WHEN @nMONTH3 > 3 THEN
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3  AND I = 2) ,0))
	ELSE
		CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0))
		+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0))	
	END,	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH1) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH2) ,0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUMMA) FROM #SPR_ESN WHERE WAY_CALC = 3 AND I = 2 AND MONTH_BASE = @nMONTH3) ,0))	


--ВЫРАВНИВАНИЕ ПОГРЕШНОСТИ ПО ИНВАЛИДАМ
/*
--Способ заполнения страховых взносов
Выриант №1. Сумма всзносов по организации рассчитывается  по формулам расчёта для РСВ-1 от общих сумм дохода и необлагаемых сумм. 
Выриант №2. Сумма взносов по организации рассчитывается как сумма взносов, начисленных по физлицам. 
Выриант №3. Сумма взносов по организации рассчитывается как сумма взносов, начисленных по физлицам. 
Но при этом для того, чтобы выполнялись контрольные соотношения по форме, выполняется подгон необлагаемых сумм.
*/

	--Вычисление погрешности для накопительной части	
	/* в 2014 не используется*/	
	
IF ISNULL(@IPERCENT,0) > 0
BEGIN
	--Вычисление погрешности для страховой части	
	SELECT 
		@C3S = CONVERT(NUMERIC(18,2),
			(
				CONVERT(NUMERIC(18,6), SUM( --Стр 2040 = 
					(CASE WHEN CODE_STR = '2000' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2010' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2020' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2030' THEN C3 ELSE 0 END)
				)) * @IPERCENT/100
				- CONVERT(NUMERIC(18,6), (SELECT SUM(C3) FROM #RES2 WHERE CODE_STR = '2050'))
			) / (@IPERCENT/100)	
		),
		@C3SS = CONVERT(NUMERIC(18,2),
			(
				CONVERT(NUMERIC(18,6), SUM( --Стр 2040 = 
					(CASE WHEN CODE_STR = '2000' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2010' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2020' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2030' THEN C3 ELSE 0 END)
				)) * @IPERCENT/100
			)
		),
		@C4S = CONVERT(NUMERIC(18,2),
			(
				CONVERT(NUMERIC(18,6), SUM( --Стр 2040 = 
					(CASE WHEN CODE_STR = '2000' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2010' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2020' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2030' THEN C4 ELSE 0 END)
				)) * @IPERCENT/100
				- CONVERT(NUMERIC(18,6),(SELECT SUM(C4) FROM #RES2 WHERE CODE_STR = '2050'))
			) / (@IPERCENT/100)	
		),
		@C4SS = CONVERT(NUMERIC(18,2),
			(
				CONVERT(NUMERIC(18,6), SUM( --Стр 2040 = 
					(CASE WHEN CODE_STR = '2000' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2010' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2020' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2030' THEN C4 ELSE 0 END)
				)) * @IPERCENT/100
			)
		),			
		@C5S = CONVERT(NUMERIC(18,2),
			(
				CONVERT(NUMERIC(18,6), SUM( --Стр 2040 = 
					(CASE WHEN CODE_STR = '2000' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2010' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2020' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2030' THEN C5 ELSE 0 END)
				)) * @IPERCENT/100
				- CONVERT(NUMERIC(18,6),(SELECT SUM(C5) FROM #RES2 WHERE CODE_STR = '2050'))
			) / (@IPERCENT/100)	
		),		
		@C5SS = CONVERT(NUMERIC(18,2),
			(
				CONVERT(NUMERIC(18,6), SUM( --Стр 2040 = 
					(CASE WHEN CODE_STR = '2000' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2010' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2020' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2030' THEN C5 ELSE 0 END)
				)) * @IPERCENT/100
			)
		),
		@C6S = CONVERT(NUMERIC(18,2),
			(
				CONVERT(NUMERIC(18,6), SUM( --Стр 2040 = 
					(CASE WHEN CODE_STR = '2000' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2010' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2020' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2030' THEN C6 ELSE 0 END)
				)) * @IPERCENT/100
				- CONVERT(NUMERIC(18,6), (SELECT SUM(C6) FROM #RES2 WHERE CODE_STR = '2050'))
			) / (@IPERCENT/100)						
		),
		@C6SS = CONVERT(NUMERIC(18,2),
			(
				CONVERT(NUMERIC(18,6), SUM( --Стр 2040 = 
					(CASE WHEN CODE_STR = '2000' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2010' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2020' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2030' THEN C6 ELSE 0 END)
				)) * @IPERCENT/100
			)
		)			
	FROM #RES2
	WHERE
		CODE_STR IN ('2000', '2010', '2020', '2030')

	IF @SALARY_OPTIONS_OPT6_1 = 1
	BEGIN
		UPDATE #RES2
		SET
			C3 = CASE WHEN @nMONTH3 = 3 THEN ISNULL(@C4SS,0) + ISNULL(@C5SS,0) + ISNULL(@C6SS,0) ELSE ISNULL(@C3SS,0) END,
			C4 = ISNULL(@C4SS,0),
			C5 = ISNULL(@C5SS,0),
			C6 = ISNULL(@C6SS,0)
		WHERE 
			CODE_STR = '2050'
		
	END
	
	---Корректируем необлагаемые суммы на копейки округления

	IF @SALARY_OPTIONS_OPT6_1 = 3
	BEGIN		
		UPDATE #RES2
		SET
			C3 = C3 + ISNULL(@C3S,0),
			C4 = C4 + ISNULL(@C4S,0),
			C5 = C5 + ISNULL(@C5S,0),
			C6 = C6 + ISNULL(@C6S,0)			 
		WHERE 
			CODE_STR = '2010'
			
	END	
	
END	
	


IF ISNULL(@IPERCENT_OMS,0) > 0
BEGIN
	--Вычисление погрешности для ОМС	
	SELECT 
		@C3N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2150 = 
					(CASE WHEN CODE_STR = '2100' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2110' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2130' THEN C3 ELSE 0 END)
				) * @IPERCENT_OMS/100
				- (SELECT SUM(C3) FROM #RES2 WHERE CODE_STR = '2150')
			) / (@IPERCENT_OMS/100)
		),

		@C3NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2150  = 
					(CASE WHEN CODE_STR = '2100' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2110' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C3 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2130' THEN C3 ELSE 0 END)
				) * @IPERCENT_OMS/100
			)
		),
		
		@C4N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2150 = 
					(CASE WHEN CODE_STR = '2100' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2110' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2130' THEN C4 ELSE 0 END)
				) * @IPERCENT_OMS/100
				- (SELECT SUM(C4) FROM #RES2 WHERE CODE_STR = '2150')
			) / (@IPERCENT_OMS/100)
		),
		@C4NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2150 = 
					(CASE WHEN CODE_STR = '2100' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2110' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C4 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2130' THEN C4 ELSE 0 END)
				) * @IPERCENT_OMS/100
			)
		),
		
		@C5N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2150 = 
					(CASE WHEN CODE_STR = '2100' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2110' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2130' THEN C5 ELSE 0 END)
				) * @IPERCENT_OMS/100
				- (SELECT SUM(C5) FROM #RES2 WHERE CODE_STR = '2150')
			) / (@IPERCENT_OMS/100)
		),

		@C5NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2150 = 
					(CASE WHEN CODE_STR = '2100' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2110' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C5 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2130' THEN C5 ELSE 0 END)
				) * @IPERCENT_OMS/100
			)
		),
				
		@C6N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2150 = 
					(CASE WHEN CODE_STR = '2100' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2110' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2130' THEN C6 ELSE 0 END)
				) * @IPERCENT_OMS/100
				- (SELECT SUM(C6) FROM #RES2 WHERE CODE_STR = '2150')
			) / (@IPERCENT_OMS/100)
		),
		@C6NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2150 = 
					(CASE WHEN CODE_STR = '2100' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2110' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2120' THEN C6 ELSE 0 END)
					-(CASE WHEN CODE_STR = '2130' THEN C6 ELSE 0 END)
				) * @IPERCENT_OMS/100
			)
		)			
	FROM #RES2
	WHERE
		CODE_STR IN ('2100', '2110', '2120', '2130')


	IF @SALARY_OPTIONS_OPT6_1 = 1
	BEGIN
		UPDATE #RES2
		SET
			C3 = CASE WHEN @nMONTH3 = 3 THEN ISNULL(@C4NS,0) + ISNULL(@C5NS,0) + ISNULL(@C6NS,0) ELSE ISNULL(@C3NS,0) END,
			C4 = ISNULL(@C4NS,0),
			C5 = ISNULL(@C5NS,0),
			C6 = ISNULL(@C6NS,0)
		WHERE 
			CODE_STR = '2150'
		
	END

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

END		

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

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

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

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


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


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

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

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

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

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


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

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

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

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


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

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

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

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

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



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

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


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

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



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


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

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

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

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

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


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

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

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

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


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

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

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

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

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


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

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

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

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


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


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

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



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

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

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


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

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

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

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


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

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

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

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

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

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

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

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

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


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

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

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

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

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


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

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



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

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


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


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

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

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

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

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


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

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

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

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


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

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

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

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE = @nMONTH3) ,0)


/*******Раздел 2.4*** Класс условий труда - вредный, подкласс условий труда - 3.3  ******/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2520', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
 			 
FROM #SPR_ESN 
WHERE WAY_CALC = 11	AND SP = 'В3.3'	 

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2530',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN 
WHERE WAY_CALC = 10	AND SP = 'В3.3'


------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '2550', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT 
	'2560',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN 
WHERE WAY_CALC = 11 AND SP = 'В3.3'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2570',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE = @nMONTH3) ,0) 


/********Расчет допольнительного тарифа страховых взносов  по доп тарифу 2**********/
/*******Раздел 2.4**** Класс условий труда - вредный, подкласс условий труда - 3.2 *****/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2580', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
 			 
FROM #SPR_ESN 
WHERE WAY_CALC = 11	 AND SP = 'В3.2'	 

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2590',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN 
WHERE WAY_CALC = 11	 AND SP = 'В3.2'	 

------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '2610', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT 
	'2620',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN 
WHERE WAY_CALC = 11	 AND SP = 'В3.2'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2630',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.2' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.2' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.2' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.2' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.2' and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.2' and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.2' and  MONTH_BASE = @nMONTH3) ,0)

/*******Раздел 2.4**** Класс условий труда - вредный, подкласс условий труда - 3.1 *****/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ 
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2640', 
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			 
			 
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
 			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH3),0))
 			 
FROM #SPR_ESN 
WHERE WAY_CALC = 11	 AND SP = 'В3.1'	 

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2650',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN 
WHERE WAY_CALC = 11	 AND SP = 'В3.1'	



------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '2670', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT 
	'2680',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN 
WHERE WAY_CALC = 11	 AND SP = 'В3.1'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2690',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE = @nMONTH3) ,0)

--select * from #RES2 
---------------
/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/

DECLARE @Date1M datetime, @Date2M datetime, @Date3M datetime

SELECT @BDate = @START_DATE, @EndDate = @END_DATE
SET @EDate = dateadd(year,1,convert(varchar, YEAR(@BDate))+'0101')

if @nMONTH3 =3
begin
	SET @Date1M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0101')
	SET @Date2M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0201')
	SET @Date3M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0301')
end
if @nMONTH3 =6
begin
	SET @Date1M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0401')
	SET @Date2M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0501')
	SET @Date3M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0601')
end
if @nMONTH3 =9
begin
	SET @Date1M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0701')
	SET @Date2M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0801')
	SET @Date3M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0901')
end
if @nMONTH3 =12
begin
	SET @Date1M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'1001')
	SET @Date2M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'1101')
	SET @Date3M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'1201')
end

/* Считаем что все наши организации не состоят из уставных вкладов инвалидов , поэтому таблицу 3.1 -3.2 не заполняем */
/* Среднесписочная численность всего */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 0, DEFAULT))

/*INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '331',@NAvgCount,
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date1M, @Date2M, @DEP_LINK, 0, 1, 0, DEFAULT)),
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date2M, @Date3M, @DEP_LINK, 0, 1, 0, DEFAULT)),
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date3M, @END_DATE, @DEP_LINK, 0, 1, 0, DEFAULT))	

/* Среднесписочная численность работников инвалидов */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 1, DEFAULT))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '332',@NAvgCount,
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date1M, @Date2M, @DEP_LINK, 0, 1, 1, DEFAULT)),
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date2M, @Date3M, @DEP_LINK, 0, 1, 1, DEFAULT)),
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date3M, @END_DATE, @DEP_LINK, 0, 1, 1, DEFAULT))	

*/

/* Завершаем - списываем значения во временную таблицу */
DECLARE @Table_Razd1 VARCHAR(100)
EXEC dbo.X_GET_TABLE_NAME @Table_Razd1 OUTPUT
EXEC ('select * INTO ' + @Table_Razd1 + ' from #RES2 order by code_str')
EXEC dbo.BufferClear
EXEC dbo.BufferPush -116, @Table_Razd1

DROP TABLE #RES2














GO


GRANT EXECUTE ON dbo.[RSA_RSV_1_14_PFR_PREPARE] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[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

DECLARE @DEFAULT_KBK INT
SET @DEFAULT_KBK = (Select TOP 1 KBK.LINK_KBK FROM dbo.KU_EmplStafKBK(default) KBK WHERE KBK.LINK_EMPL = @LINK_EMPL)
SET @DEFAULT_KBK = ISNULL((SELECT CH.NEW_LINK FROM dbo.SAL_SFIN_CHANGES(@DATE_BEGIN) CH WHERE CH.LINK = @DEFAULT_KBK),@DEFAULT_KBK)

--
IF @RECALC <= 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
	)


	/*Заменяем источники финансирования в базовых начислениях с учетом истории изменений источников*/
	UPDATE B SET B.LINK_VKR = CH.NEW_LINK
	FROM #BASE1 B INNER JOIN dbo.SAL_SFIN_CHANGES(@DATE_BEGIN) CH ON CH.LINK = B.LINK_VKR	

	DECLARE @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

	/*Заменяем источники финансирования в базовых начислениях с учетом истории изменений источников*/
	UPDATE B SET B.LINK_VKR = CH.NEW_LINK
	FROM #BASE1 B INNER JOIN dbo.SAL_SFIN_CHANGES(@DATE_BEGIN) CH ON CH.LINK = B.LINK_VKR

	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 @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,@DEFAULT_KBK),
		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, DAYS = SUM(CJ.DAYS), HOURS = SUM(CJ.HOURS), SUMMA = SUM(SUMMA)
INTO #SUM_OLD
from 
	dbo.SDOC_AVAC SA inner join dbo.CALCULATE_JURNAL CJ on CJ.LINK_DOC = SA.LINK_UP
	inner join dbo.sdoc d on CJ.LINK_DOC = d.link 
where
	COALESCE(@LINK_VAC,0) > 0
	AND
	SA.REF_DOC = @LINK_VAC
	and
	d.object = (Select top 1 link from s_objects where code = @OBJ_CODE)
GROUP BY
	CJ.DATE_BEGIN, CJ.DATE_END, CJ.LINK_VKR

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
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SU_REESTR_DGH_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SU_REESTR_DGH_SAVE]

GO

CREATE PROCEDURE [dbo].SU_REESTR_DGH_SAVE
	@LINK		int	OUTPUT,
	@Number 		varchar(10),
	@Date		datetime,
	@PERS_LINK	 	int,
	@Date1		datetime,
	@Date2		datetime,
	@TYPE		tinyint,
	@Payment		tinyint,
	@Summa 		numeric(20,2),
	@AVANCE		NUMERIC(18,2) = 0,
	@COMMENT		varchar(254),
	@PAYS		int,
	@VZNOS 		tinyint,
	@FLAG_NALOG tinyint,
	@FLAG_ESN tinyint,
	@FLAG_TRAVMA tinyint,
	@LINK_KBK INT,
	@varKSDepLink INT = NULL
AS
DECLARE @varKSERROR	tinyint,
		@varKStrancount	int,
		@varKSEventText varchar(100),
		@varKSchrNAME  varchar(30),
		@varKSobjSALARY_REESTR_DGH int,
		@varKSRowCount int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

	SELECT @varKSchrNAME = rtrim(FM)+' '+left(IM,1)+'.'+left(OT,1)+'.' FROM PERSON WHERE LINK = @PERS_LINK
	SELECT @varKSobjSALARY_REESTR_DGH = LINK FROM S_OBJECTS WHERE CODE = 'SALARY_REESTR_DGH'
	SET @LINK_KBK = COALESCE(@LINK_KBK,0)

	IF @Date IS NULL or @Date1 IS NULL or @Date2 IS NULL or @TYPE IS NULL or @Payment IS NULL
		or @VZNOS IS NULL or @FLAG_NALOG IS NULL or @PERS_LINK IS NULL OR @PERS_LINK = 0 OR @LINK_KBK = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END

	---
	IF @varKSDepLink IS NULL
		exec dbo.xd_whats_zb @varKSDepLink output

	IF @LINK is null OR @LINK = 0
	BEGIN
		INSERT INTO REESTR_DGH WITH (ROWLOCK) (NUMBER, [DATE], PERS_LINK, DATE1, DATE2, TYPE, PAYMENT,
				SUMMA, AVANCE, COMMENT, VZNOS, LINK_PAYS, FLAG_NALOG, FLAG_ESN,FLAG_TRAVMA,DEP_LINK, LINK_KBK)
		VALUES (@Number, @Date, @PERS_LINK, @Date1, @Date2, @TYPE, @Payment, 
			@Summa,@AVANCE, @COMMENT, @VZNOS, @PAYS, @FLAG_NALOG, @FLAG_ESN,@FLAG_TRAVMA, @varKSDepLink, @LINK_KBK)
		SELECT @varKSERROR = @@ERROR, @LINK = @@IDENTITY
		IF @varKSERROR <> 0
			BEGIN
				ROLLBACK
				RETURN 7
			END
	END
	ELSE
		BEGIN
			UPDATE REESTR_DGH WITH (ROWLOCK) 
			SET NUMBER = @Number, [DATE] = @Date, PERS_LINK = @PERS_LINK,
		  		DATE1 = @Date1, DATE2 = @Date2, TYPE =@TYPE, PAYMENT = @Payment, 
				SUMMA = @Summa, AVANCE = @AVANCE ,COMMENT = @COMMENT,
				VZNOS = @VZNOS, LINK_PAYS = @PAYS, FLAG_NALOG = @FLAG_NALOG,FLAG_ESN = @FLAG_ESN, FLAG_TRAVMA =@FLAG_TRAVMA, DEP_LINK = @varKSDepLink,
				LINK_KBK = @LINK_KBK
			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


	
	SET @varKSEventText = 'Договор ГПХ:' + ' ' +  LTRIM(RTRIM(@varKSchrNAME))
	EXECUTE WF_GENERATEEVENT 'Сохранение строки реестра', @varKSEventText, @varKSobjSALARY_REESTR_DGH, 'REESTR_DGH',@LINK

WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0





GO


GRANT EXECUTE ON dbo.[SU_REESTR_DGH_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].[BB_CREATE_PROV_RECEPTION_CASH]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_CREATE_PROV_RECEPTION_CASH]
GO








CREATE	PROCEDURE BB_CREATE_PROV_RECEPTION_CASH
	@iLinkDoc 	int,
	@iDel		tinyint = 0	
AS

DECLARE @iTypLink	int,
	@iTypLinkB	int,
	@iTypLinkV	int,
	@iLink 		int,
	@iLinkUp 	int,
	@cNameOper 	varchar(250),
	@nSumma 	numeric(28,2),
	@iKBK 		int,
	@iSGU 		int, 
	@iEKR 		int, 
	@iDopCl 	int,
	@cSource 	int,
 
	@iDep 		int, 
	@iDepAcc 	int, 
	@iLinkGP1 	int,
	@iOrders 	int,
	@iRet		int,
	@cErrTxt 	varchar(60),
	@cG2Name 	varchar(254),
	@cObjCOde   varchar(254)


IF @iLinkDoc IS NULL OR @iLinkDoc <= 0
	RETURN -1	


select @iDepAcc = ACC, @cObjCOde = SO.CODE
from dbo.G_PROV G
inner join dbo.s_objects so on so.LINK = G.object 
WHERE g.LINK = @iLinkDoc


if @cObjCOde = 'DOC_RECEPTION_CARD'
	SELECT TOP 1 @iTypLinkB = TYP_LINK, @iTypLinkV = TYP_LINK_V 
	FROM dbo.DOC_REC_CARD_OPTIONS

else
	SELECT TOP 1 @iTypLinkB = TYPLINK_R, @iTypLinkV = TYP_LINK_V 
	FROM dbo.DOCUMENTS_REC_CASH_OPTIONS

IF @iTypLinkB IS NULL OR @iTypLinkB <= 0
	RETURN -2	

IF @iTypLinkV IS NULL OR @iTypLinkV <= 0
	set @iTypLinkV = @iTypLinkB

DECLARE GRID_CUR CURSOR LOCAL STATIC READ_ONLY FOR
SELECT T.LINK, T.KBK, T.EKR, T.DOP_CLASSIF, T.SOURCE, T.SUMMA, case T.SOURCE when 1 then @iTypLinkB else @iTypLinkV end, G1.NAME_OPER
FROM  RECEPTION_CASH_TABLE T
left join dbo.G_PROV1 G1 on G1.LINK = case T.SOURCE when 1 then @iTypLinkB else @iTypLinkV end
where T.SUMMA <> 0 and T.LINK_UP = @iLinkDoc

IF @iDel = 1
	DELETE FROM G_PROV1 WHERE LINK_UP = @iLinkDoc


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, @cSource, @nSumma, @iTypLink, @cNameOper
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 @iRet = FB_SAVE_G_PROV2_AP_LIMIT @iLinkGP1, @iTypLink, @nSumma, NULL, @iKBK, @iEKR,  @iDopCl, NULL, NULL, @iDepAcc, @cNameOper, @cSource,NULL, NULL
	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, @cSource, @nSumma, @iTypLink, @cNameOper
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
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RSA_4FSS_09022012_PREPARE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RSA_4FSS_09022012_PREPARE]

GO

CREATE PROCEDURE dbo.RSA_4FSS_09022012_PREPARE
	@Res float output, @varcStr varchar(250), @vardBegin datetime = '20050101', @vardEnd datetime = '20051231', @variCol int, @variRow int, @variLSF int
AS 

EXEC dbo.BufferClear

DECLARE @OUT_VAL NUMERIC(20), @START_DATE DATETIME, @END_DATE DATETIME, @DEP_LINK INT

DECLARE --Для выравнивания погрешности
	@C3N NUMERIC(18,6), @C4N NUMERIC(18,6), @C5N NUMERIC(18,6), @C6N NUMERIC(18,6),
	@C3NS NUMERIC(18,6), @C4NS NUMERIC(18,6), @C5NS NUMERIC(18,6), @C6NS NUMERIC(18,6)


select @DEP_LINK = Link_Organization from report_saved_forms where link_saved_form =  @variLSF
set @res = 0
SELECT @START_DATE = @vardBegin, @END_DATE = @vardEnd

DECLARE @BYearDate	datetime
SET @BYearDate = dbo.DateBeginOfYear (@START_DATE)

declare @EndYear datetime
Set @EndYear = dbo.DateEndOfYear(@START_DATE)

DECLARE @nYEAR INT, @nMONTH1 INT, @nMONTH2 INT, @nMONTH3 INT

SELECT 
	@nYEAR = YEAR(@START_DATE),
	@nMONTH1 = MONTH(@START_DATE),
	@nMONTH2 = MONTH(@START_DATE)+1,
	@nMONTH3 = MONTH(@START_DATE)+2

create table #SPR_ESN ([MONTH_BASE] TINYINT, SUMMA_BASE numeric(18,6) default 0.00, DED_M numeric(18,6) default 0.00, INV_M numeric(18,6) default 0.00, SUMMA numeric(18,6) default 0.00, WAY_CALC int default 0.00, REF_PHYS_PERS int default 0, KATEG TINYINT)

Insert InTo #SPR_ESN ([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG)
Select [MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG
from dbo.SA_ESN_VIEW(@nYEAR, @nMONTH3, @DEP_LINK, 0) WHERE WAY_CALC = 2
---Суммы по договорникам
INSERT INTO #SPR_ESN 
	([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG)
SELECT 
	MONTH(G.[DATE]) AS MONTH_BASE, GT.SUMMA_BASE, 0, 0, GT.SUMMA, P.WAY_CALC, GT.PERS_LINK,
	KATEG = (CASE WHEN I.LINK IS NULL THEN (F.ENVD + 1) ELSE 3 END)
FROM 
	dbo.SDOC G
	INNER JOIN dbo.SDOC_DGH_TABLE GT ON G.LINK = GT.LINK_UP
	INNER JOIN dbo.PAYS P ON P.LINK = GT.LINK_PAY
	INNER JOIN dbo.SAL_SFIN F ON F.LINK = GT.LINK_VKR
	LEFT JOIN dbo.pers_invalid I ON GT.PERS_LINK = I.PERS_LINK 
	AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH(G.[DATE]),@nYEAR)) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')
WHERE
	G.[OBJECT] =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOCUMENTS_DGH')
	AND GT.[OBJECT] = 3
	AND FLAG_JC = 1
	AND P.WAY_CALC = 2
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3
	AND LINK_DEP = @DEP_LINK


/*РАЗДЕЛ 2.1*/
DECLARE @BDate datetime, @EndDate datetime, @EDate datetime, @NAvgCount int

SELECT @BDate = @START_DATE, @EndDate = @END_DATE
SET @EDate = dateadd(year,1,convert(varchar, YEAR(@BDate))+'0101')

CREATE TABLE #RES2(CODE_STR VARCHAR(10), BASE_FSS NUMERIC(18,6), CNT_FSS INT, CNT_FEM INT , NUM_PP Varchar(50) default '')

--ОСТАТКИ ПО СЧЁТУ 303.02 НА НАЧАЛО ГОДА
CREATE TABLE #REST_30302_BY ([DATE] DATETIME, REST NUMERIC(18,2))

DECLARE @Cur1 CURSOR, @LINK_ACC INT
SET @Cur1 = CURSOR FORWARD_ONLY

FOR SELECT LINK FROM dbo.S_ACCOUNTS WHERE CODE LIKE '303.02%'

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @LINK_ACC
WHILE (@@fetch_status <> -1)
BEGIN

	IF (@@fetch_status <> -2)
	BEGIN

		INSERT INTO #REST_30302_BY ([DATE], REST)
		SELECT @BYearDate, REST = coalesce(sum(K_SUMMA)-sum(D_SUMMA),0) 
		FROM dbo.ARestGroupedTableByDate (@BYearDate, @LINK_ACC, DEFAULT)
		WHERE DEP_LINK = @DEP_LINK
	END

	FETCH NEXT FROM @Cur1 INTO @LINK_ACC
END

CLOSE @Cur1
DEALLOCATE @Cur1

--ОСТАТКИ ПО СЧЁТУ 303.02 НА КОНЕЦ ОТЧЕТНОГО КВАРТАЛА
DECLARE @QV_DATE DATETIME
SET @QV_DATE = @END_DATE+1

SET @Cur1 = CURSOR FORWARD_ONLY

FOR SELECT LINK FROM dbo.S_ACCOUNTS WHERE CODE LIKE '303.02%'

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @LINK_ACC
WHILE (@@fetch_status <> -1)
BEGIN

	IF (@@fetch_status <> -2)
	BEGIN

		INSERT INTO #REST_30302_BY ([DATE], REST)
		SELECT @END_DATE, REST = coalesce(sum(K_SUMMA)-sum(D_SUMMA),0) 
		FROM dbo.ARestGroupedTableByDate (@QV_DATE, @LINK_ACC, DEFAULT)
		WHERE DEP_LINK = @DEP_LINK
	END

	FETCH NEXT FROM @Cur1 INTO @LINK_ACC
END

CLOSE @Cur1
DEALLOCATE @Cur1

INSERT INTO #RES2 (CODE_STR, BASE_FSS, CNT_FSS, CNT_FEM)
SELECT '0101', SUM(REST), 0, 0 FROM #REST_30302_BY WHERE [DATE] = @BYearDate HAVING SUM(REST) > 0

INSERT INTO #RES2 (CODE_STR, BASE_FSS, CNT_FSS, CNT_FEM)
SELECT '0112', -SUM(REST), 0, 0 FROM #REST_30302_BY WHERE [DATE] = @BYearDate HAVING SUM(REST) < 0

INSERT INTO #RES2 (CODE_STR, BASE_FSS, CNT_FSS, CNT_FEM)
SELECT '0109', -SUM(REST), 0, 0 FROM #REST_30302_BY WHERE [DATE] = @END_DATE HAVING SUM(REST) < 0

INSERT INTO #RES2 (CODE_STR, BASE_FSS, CNT_FSS, CNT_FEM)
SELECT '0119', SUM(REST), 0, 0 FROM #REST_30302_BY WHERE [DATE] = @END_DATE HAVING SUM(REST) > 0

--- Номера платежек 
CREATE TABLE #PLAT (VID TINYINT, Y INT, MON TINYINT, SUMMA NUMERIC(18,2), Y_p INT, MON_p TINYINT, NUMBER VARCHAR(10))

	exec dbo.BufferClear 'DT'
	exec dbo.BufferClear 'KT'

	INSERT INTO BUFFER (link, id)
	select link, 'DT' from s_accounts where cSinth = '303' and cAnalit = '02' --С 290экр НЕ ДОЛЖЕН БРАТЬСЯ

	INSERT INTO BUFFER (link, id)
	select link, 'KT' from s_accounts where cSinth = '304' and cAnalit = '05'

	INSERT INTO BUFFER (link, id)
	select link, 'KT' from s_accounts where cSinth = '201' and (cAnalit = '11' or cAnalit = '21' or cAnalit = '27')

	INSERT INTO #PLAT (VID, Y, MON, SUMMA,Y_P,MON_P,NUMBER)
	SELECT  1,
		Y = CONVERT(INT,YEAR(p.DATE_PROV)), 
		MON = CONVERT(INT,MONTH(p.DATE_PROV)),
		P.SUMMA,  
		Y_P = CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')), 
		MON_P = CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.')),
		P.NUMBER	
	from 
		dbo.AProvByBufferConditionsShortDate(@START_DATE, @END_DATE, 'DT', 'KT') P	
		inner join dbo.DOCUMENTS_PAY_ADD PA on P.link = PA.link
		inner join dbo.g_prov G on G.link = PA.link
		LEFT JOIN dbo.KOSGU DG ON DG.LINK = P.DT_EKR
	WHERE
		P.DEP_LINK = @DEP_LINK
		AND
		G.DEP = @DEP_LINK
		--AND
		--CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.')) <= @M
		--AND
		--CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')) = @Y
		AND
		DG.CODE <> '290'

	exec dbo.BufferClear 'DT'
	exec dbo.BufferClear 'KT'
	
	
	
INSERT INTO #RES2 (CODE_STR, BASE_FSS, CNT_FSS, CNT_FEM)
SELECT '01163', 
		(SELECT ISNULL(SUM(SUMMA),0) FROM #PLAT WHERE Y >= @nYEAR and MON = @nMONTH1), 
		'', 
		0   

INSERT INTO #RES2 (CODE_STR, BASE_FSS, CNT_FSS, CNT_FEM)
SELECT '01164', 
		(SELECT ISNULL(SUM(SUMMA),0) FROM #PLAT WHERE Y >= @nYEAR and MON = @nMONTH2), 
		'', 
		0   

INSERT INTO #RES2 (CODE_STR, BASE_FSS, CNT_FSS, CNT_FEM)
SELECT '01165', 
		(SELECT ISNULL(SUM(SUMMA),0) FROM #PLAT WHERE Y >= @nYEAR and MON = @nMONTH3), 
		'', 
		0   

--- Сведения по номерам платежек
SELECT  VID,
		Y , 
		MON ,
		NUMBER	
INTO #PLAT_PP
FROM #PLAT 
GROUP  BY VID , Y , MON, NUMBER

DROP TABLE #PLAT

BEGIN 
	declare @Cur cursor , @VID tinyint , @Y INT, @MON TINYINT, @NUMBER VARCHAR(10)

	SET @Cur = CURSOR FORWARD_ONLY
	FOR 
		select VID, Y, MON, NUMBER from #PLAT_PP order by VID, Y, MON, NUMBER
	OPEN @Cur
	FETCH NEXT FROM @Cur INTO @VID, @Y, @MON, @NUMBER
	
	WHILE (@@fetch_status <> -1)
	BEGIN
		
		IF (@@fetch_status <> -2)
		BEGIN	
			if  @Y = @nYEAR and @MON = @nMONTH1
				UPDATE #RES2
					set NUM_PP = (case when NUM_PP is null or NUM_PP= '' then ltrim(RTRIM(@NUMBER)) else ltrim(RTRIM(NUM_PP))+','+ ltrim(RTRIM(@NUMBER)) end )
				where code_str = '01163' 

			if  @Y = @nYEAR and @MON = @nMONTH2
				UPDATE #RES2
					set NUM_PP = (case when NUM_PP is null or NUM_PP= '' then ltrim(RTRIM(@NUMBER)) else ltrim(RTRIM(NUM_PP))+','+ ltrim(RTRIM(@NUMBER)) end )
				where code_str = '01164'

			if  @Y = @nYEAR and @MON = @nMONTH3
				UPDATE #RES2
					set NUM_PP = (case when NUM_PP is null or NUM_PP= '' then ltrim(RTRIM(@NUMBER)) else ltrim(RTRIM(NUM_PP))+','+ ltrim(RTRIM(@NUMBER)) end )
				where code_str = '01165'				

		end
		FETCH NEXT FROM @Cur INTO @VID, @Y, @MON, @NUMBER
	end

CLOSE @Cur
DEALLOCATE @Cur

END 

drop table #PLAT_PP

-- exec dbo.RI_REPORT_FORMULA_ALL_CALCULATE '2014-01-01 00:00:00','2014-03-31 00:00:00',2,1,2745
/*declare @Res float
set @Res = 0
 exec dbo.RSA_4FSS_09022012_PREPARE @Res output, '', '20140101', '20140331', 2, 1, 2745
*/

/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/

/* Среднесписочная численность работающих инвалидов */
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(CJ.period_begin) = @nYEAR and Month(CJ.period_begin) <= @nMONTH3 
	and CJ.LINK_DEP = @DEP_LINK
	and P.[OBJECT] = 1
GROUP BY
	Month(CJ.PERIOD_BEGIN)
UNION ALL	
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(SUMMA - ISNULL(B.SUMMA_BASE,0)) --на которые не начисляются страховые взносы
from 
	#DGH_CJ CJ
	LEFT JOIN #DGH_FAKT_BASE B ON B.PERS_LINK = CJ.PERS_LINK AND B.MONTH_BASE = Month(CJ.PERIOD_BEGIN)
where 	
	Month(CJ.period_begin) <= @nMONTH3 
GROUP BY
	Month(CJ.PERIOD_BEGIN)
) AS T
GROUP BY 
	MON
	
--Суммы выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со ст.7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
INSERT INTO #RES2 SELECT '030103', SUM(SUMMA_ALL), 0, 0, '' FROM #SALARY_SUM2
INSERT INTO #RES2 SELECT '030104', SUM(SUMMA_ALL), 0, 0, '' FROM #SALARY_SUM2 WHERE MON = @nMONTH1
INSERT INTO #RES2 SELECT '030105', SUM(SUMMA_ALL), 0, 0, '' FROM #SALARY_SUM2 WHERE MON = @nMONTH2
INSERT INTO #RES2 SELECT '030106', SUM(SUMMA_ALL), 0, 0, '' FROM #SALARY_SUM2 WHERE MON = @nMONTH3


--select * from #RES2 where CODE_STR in ('030103', '030104', '030105', '030106')
DECLARE @TMP_VAL NUMERIC(18,2)
--Суммы, не подлежащие обложению страховыми взносами в соответствии со ст.9 Федерального закона от 24 июля 2009 г. № 212-ФЗ
--INV_M теперь содержит только льготы (100 тыс инвалидам теперь нет)
SET @TMP_VAL = ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN ) ,0) + ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM2),0)
INSERT INTO #RES2 VALUES('030203', @TMP_VAL, 0, 0, '')

SET @TMP_VAL = ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN  WHERE MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM2 WHERE MON = @nMONTH1),0)
INSERT INTO #RES2 VALUES('030204', @TMP_VAL, 0, 0, '')

SET @TMP_VAL = ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN  WHERE MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM2 WHERE MON = @nMONTH2),0)
INSERT INTO #RES2 VALUES('030205', @TMP_VAL, 0, 0, '')

SET @TMP_VAL = ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN  WHERE MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM2 WHERE MON = @nMONTH3),0)
INSERT INTO #RES2 VALUES('030206', @TMP_VAL, 0, 0, '')

--select * from #RES2 where CODE_STR in ('030203', '030204', '030205', '030206')

DECLARE @LIMIT NUMERIC(18,2)

SELECT @LIMIT = MAX(S.PREDEL)
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3 AND P.WAY_CALC = 2
WHERE 
	DATE = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3 AND P.WAY_CALC = 2 AND DATE < @END_DATE ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0

SET @LIMIT = ISNULL(@LIMIT,0)


--  тариф, применяемый  свыше установленного предела величины базы (%)
DECLARE 
	@PERCENT1 NUMERIC(18,2),
	@PERCENT1_IN NUMERIC(18,2)
--	@PERCENT_FSS NUMERIC(18,2)

-- Рабочие 	
SELECT @PERCENT1 = S.PERCENT1
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3 AND P.WAY_CALC = 2
WHERE 
	predel = @LIMIT
	and tarif =1
	and 
	DATE = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3 AND P.WAY_CALC = 2 AND DATE < @END_DATE ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
-- нивалиды
SELECT @PERCENT1_IN = S.PERCENT1
FROM 
	dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3 AND P.WAY_CALC = 2
WHERE 
	predel = @LIMIT
	and tarif =3
	and 
	DATE = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3 AND P.WAY_CALC = 2 AND DATE < @END_DATE ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0

SET @PERCENT1 = ISNULL(@PERCENT1,0)
SET @PERCENT1_IN = ISNULL(@PERCENT1_IN,0)

SELECT MON = 1, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1 FROM #SPR_ESN WHERE MONTH_BASE <= 1 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 2, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 2 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 3, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 3 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 4, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 4 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 5, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 5 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 6, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 6 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 7, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 7 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 8, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 8 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 9, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 9 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 10, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 10 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 11, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 11 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1 SELECT MON = 12, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE MONTH_BASE <= 12 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS

SELECT DISTINCT T.REF_PHYS_PERS, M.M, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2
FROM 
	#SPR_ESN1 T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1 T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1

--Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную в соответствии со ст. 8 Федерального закона от 24 
INSERT INTO #RES2 SELECT '030303', SUM(SUMMA), 0, 0, '' FROM #SPR_ESN2 WHERE M <= @nMONTH3
INSERT INTO #RES2 SELECT '030304', SUM(SUMMA), 0, 0, '' FROM #SPR_ESN2 WHERE M = @nMONTH1
INSERT INTO #RES2 SELECT '030305', SUM(SUMMA), 0, 0, '' FROM #SPR_ESN2 WHERE M = @nMONTH2
INSERT INTO #RES2 SELECT '030306', SUM(SUMMA), 0, 0, '' FROM #SPR_ESN2 WHERE M = @nMONTH3

--из них: сумма выплат и иных вознаграждений физическим лицам, являющимся инвалидами I, II, III группы
SELECT MON = 1, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END INTO #SPR_ESN1KATEG3 FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 1 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 2, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 2 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 3, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 3 AND @nMONTH3 >= 3 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 4, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 4 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 5, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 5 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 6, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 6 AND @nMONTH3 >= 6 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 7, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 7 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 8, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 8 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 9, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 9 AND @nMONTH3 >= 9 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 10, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 10 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 11, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 11 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS
INSERT INTO #SPR_ESN1KATEG3 SELECT MON = 12, REF_PHYS_PERS, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > @LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT ELSE 0 END FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE <= 12 AND @nMONTH3 >= 12 GROUP BY REF_PHYS_PERS

SELECT DISTINCT T.REF_PHYS_PERS, M.M, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2KATEG3
FROM 
	#SPR_ESN1KATEG3 T INNER JOIN dbo.months_ex(@BYearDate, @END_DATE) M ON 1=1
	LEFT JOIN #SPR_ESN1KATEG3 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1KATEG3 T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.MON = M.M - 1
WHERE
	(ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)) > 0


SET @TMP_VAL = ISNULL( (SELECT SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M <= @nMONTH3),0)
INSERT INTO #RES2 VALUES('030503', @TMP_VAL, 0, 0, '')

SET @TMP_VAL = ISNULL( (SELECT SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN  WHERE KATEG = 3 AND MONTH_BASE = @nMONTH1) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH1),0)
INSERT INTO #RES2 VALUES('030504', @TMP_VAL, 0, 0, '')

SET @TMP_VAL = ISNULL( (SELECT SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN  WHERE KATEG = 3 AND MONTH_BASE = @nMONTH2) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH2),0)
INSERT INTO #RES2 VALUES('030505', @TMP_VAL, 0, 0, '')

SET @TMP_VAL = ISNULL( (SELECT SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN  WHERE KATEG = 3 AND MONTH_BASE = @nMONTH3) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH3),0)
INSERT INTO #RES2 VALUES('030506', @TMP_VAL, 0, 0, '')

--select * from #RES2 where code_str in ('030503','030504', '030505','030506')
--ВЫРАВНИВАНИЕ ПОГРЕШНОСТИ ПО ОСНОВНОМУ ТАРИФУ
/*
--Способ заполнения страховых взносов
Выриант №1. Сумма всзносов по организации рассчитывается  по формулам расчёта для 4-ФСС от общих сумм дохода и необлагаемых сумм. 
Выриант №2. Сумма взносов по организации рассчитывается как сумма взносов, начисленных по физлицам. 
Выриант №3. Сумма взносов по организации рассчитывается как сумма взносов, начисленных по физлицам. 
Но при этом для того, чтобы выполнялись контрольные соотношения по форме, выполняется подгон необлагаемых сумм.
*/
DECLARE @SALARY_OPTIONS_OPT5_1 INT 
SET @SALARY_OPTIONS_OPT5_1 = dbo.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPT5_1')

--select @PERCENT1 , @PERCENT1_IN

--select * from 	#RES2
--	WHERE
--		CODE_STR IN ('030104', '030204', '030304', '030504')

IF ISNULL(@PERCENT1,0) > 0
BEGIN

	--Вычисление погрешности для накопительной части	
	SELECT 
		@C3N = CONVERT(NUMERIC(18,2), 
			(
				SUM( --Стр 4 (030403)  = 
					(CASE WHEN CODE_STR = '030103' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030203' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030303' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030503' THEN BASE_FSS  ELSE 0 END) -- за минусом базы инвалидов
				) * @PERCENT1/100
				+ SUM( --Стр 4 (030403)  = 
					(CASE WHEN CODE_STR = '030503' THEN BASE_FSS  ELSE 0 END) -- база инвалидов
				) * @PERCENT1_IN/100				
				- (SELECT SUM(BASE_FSS) FROM #RES2 WHERE CODE_STR in ('0121','0123', '0124','0125'))
			) / @PERCENT1/100
		),
		@C3NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 4 (030403)  = 
					(CASE WHEN CODE_STR = '030103' THEN BASE_FSS  ELSE 0 END) 
					-(CASE WHEN CODE_STR = '030203' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030303' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030503' THEN BASE_FSS  ELSE 0 END) -- за минусом базы инвалидов
				) * @PERCENT1/100
				+
				SUM( --Стр 4 (030403)  = 
					(CASE WHEN CODE_STR = '030503' THEN BASE_FSS  ELSE 0 END) 
				) * @PERCENT1_IN/100				
			)
		),		
		@C4N = CONVERT(NUMERIC(18,2), 
			(
				SUM( --Стр 4 (030404)  = 
					(CASE WHEN CODE_STR = '030104' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030204' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030304' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030504' THEN BASE_FSS  ELSE 0 END) -- за минусом базы инвалидов
				) * @PERCENT1/100
				+ SUM( --Стр 4 (030404)  = 
					(CASE WHEN CODE_STR = '030504' THEN BASE_FSS  ELSE 0 END) -- база инвалидов
				) * @PERCENT1_IN/100				
				- (SELECT SUM(BASE_FSS) FROM #RES2 WHERE CODE_STR = '0123')
			) / @PERCENT1/100	
		),
		@C4NS = CONVERT(NUMERIC(18,2), 
			(
				SUM( --Стр 4 (030404)  = 
					(CASE WHEN CODE_STR = '030104' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030204' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030304' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030504' THEN BASE_FSS  ELSE 0 END) -- за минусом базы инвалидов			
				) * @PERCENT1/100
				+ SUM( --Стр 4 (030403)  = 
					(CASE WHEN CODE_STR = '030504' THEN BASE_FSS  ELSE 0 END) -- база инвалидов
				) * @PERCENT1_IN/100			
			)
		),		
		@C5N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 4 (030405)  = 
					(CASE WHEN CODE_STR = '030105' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030205' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030305' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030505' THEN BASE_FSS  ELSE 0 END) -- за минусом базы инвалидов
				) * @PERCENT1/100
				+ SUM( --Стр 4 (030404)  = 
					(CASE WHEN CODE_STR = '030505' THEN BASE_FSS  ELSE 0 END) -- база инвалидов
				) * @PERCENT1_IN/100
				- (SELECT SUM(BASE_FSS) FROM #RES2 WHERE CODE_STR = '0124')
			) / @PERCENT1/100			
		),
		@C5NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 4 (030405)  = 
					(CASE WHEN CODE_STR = '030105' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030205' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030305' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030505' THEN BASE_FSS  ELSE 0 END) -- за минусом базы инвалидов			
				) * @PERCENT1/100
				+ SUM( --Стр 4 (030404)  = 
					(CASE WHEN CODE_STR = '030505' THEN BASE_FSS  ELSE 0 END) -- база инвалидов
				) * @PERCENT1_IN/100				
			)
		),		
		@C6N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 4 (030405)  = 
					(CASE WHEN CODE_STR = '030106' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030206' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030306' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030506' THEN BASE_FSS  ELSE 0 END) -- за минусом базы инвалидов
				) * @PERCENT1/100
				+ SUM( --Стр 4 (030404)  = 
					(CASE WHEN CODE_STR = '030506' THEN BASE_FSS  ELSE 0 END) -- база инвалидов
				) * @PERCENT1_IN/100				
				- (SELECT SUM(BASE_FSS) FROM #RES2 WHERE CODE_STR = '0125')
			) / @PERCENT1/100							
		),
		@C6NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 4 (030405)  = 
					(CASE WHEN CODE_STR = '030106' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030206' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030306' THEN BASE_FSS  ELSE 0 END)
					-(CASE WHEN CODE_STR = '030506' THEN BASE_FSS  ELSE 0 END) -- за минусом базы инвалидов			
				) * @PERCENT1/100
				+ SUM( --Стр 4 (030404)  = 
					(CASE WHEN CODE_STR = '030506' THEN BASE_FSS  ELSE 0 END) -- база инвалидов
				) * @PERCENT1_IN/100				
			)
		)		
	FROM #RES2
	WHERE
		CODE_STR IN ('030103', '030203', '030303', '030503','030104', '030204', '030304', '030504','030105', '030205', '030305', '030505','030106', '030206', '030306', '030506')

	IF @SALARY_OPTIONS_OPT5_1 = 1
	BEGIN
		--Начислено ЕСН. 1 мес
		UPDATE #RES2
		SET BASE_FSS = ISNULL(@C4NS,0)			 
		WHERE 
			CODE_STR = '0123'
		
		UPDATE #RES2
		SET BASE_FSS = ISNULL(@C5NS,0)		 
		WHERE 
			CODE_STR = '0124'
			
		UPDATE #RES2
		SET BASE_FSS = ISNULL(@C6NS,0)		 
		WHERE 
			CODE_STR = '0125'
	
	END

	IF @SALARY_OPTIONS_OPT5_1 = 3
	BEGIN
	
		UPDATE #RES2
		SET BASE_FSS = BASE_FSS + ISNULL(@C3N,0)			 
		WHERE 
			CODE_STR = '030203'
		
		UPDATE #RES2
		SET BASE_FSS = BASE_FSS + ISNULL(@C4N,0)			 
		WHERE 
			CODE_STR = '030204'
			
		UPDATE #RES2
		SET BASE_FSS = BASE_FSS + ISNULL(@C5N,0)			 
		WHERE 
			CODE_STR = '030205'
			
		UPDATE #RES2
		SET BASE_FSS = BASE_FSS + ISNULL(@C6N,0)			 
		WHERE 
			CODE_STR = '030206'
	
	END

end


-- Тоже выводим по физлицу в таблицу 3.1
CREATE TABLE #RAZD31 (LINK INT, COL5 NUMERIC(18,2), COL6 NUMERIC(18,2), COL7 NUMERIC(18,2), COL8 NUMERIC(18,2))

INSERT INTO #RAZD31 (LINK, COL5, COL6, COL7, COL8)
SELECT DISTINCT 
	P.REF_PHYS_PERS,
	S5 = ISNULL(S51.SUMMA,0) - ISNULL(S52.SUMMA,0),
	S6 = ISNULL(S61.SUMMA,0) - ISNULL(S62.SUMMA,0),
	S7 = ISNULL(S71.SUMMA,0) - ISNULL(S72.SUMMA,0),
	S8 = ISNULL(S81.SUMMA,0) - ISNULL(S82.SUMMA,0)
FROM 
	#SPR_ESN P

	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3 GROUP BY REF_PHYS_PERS) S51 ON S51.REF_PHYS_PERS = P.REF_PHYS_PERS
	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M <= @nMONTH3 GROUP BY REF_PHYS_PERS) S52 ON S52.REF_PHYS_PERS = P.REF_PHYS_PERS

	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE = @nMONTH1 GROUP BY REF_PHYS_PERS) S61 ON S61.REF_PHYS_PERS = P.REF_PHYS_PERS
	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH1 GROUP BY REF_PHYS_PERS) S62 ON S62.REF_PHYS_PERS = P.REF_PHYS_PERS

	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE = @nMONTH2 GROUP BY REF_PHYS_PERS) S71 ON S71.REF_PHYS_PERS = P.REF_PHYS_PERS
	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH2 GROUP BY REF_PHYS_PERS) S72 ON S72.REF_PHYS_PERS = P.REF_PHYS_PERS

	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M) FROM #SPR_ESN WHERE KATEG = 3 AND MONTH_BASE = @nMONTH3 GROUP BY REF_PHYS_PERS) S81 ON S81.REF_PHYS_PERS = P.REF_PHYS_PERS
	LEFT JOIN (SELECT REF_PHYS_PERS, SUMMA = SUM(SUMMA) FROM #SPR_ESN2KATEG3 WHERE M = @nMONTH3 GROUP BY REF_PHYS_PERS) S82 ON S82.REF_PHYS_PERS = P.REF_PHYS_PERS
	
WHERE KATEG = 3

DECLARE @Table_Razd31 VARCHAR(100)
EXEC dbo.X_GET_TABLE_NAME @Table_Razd31 OUTPUT
EXEC ('select * INTO ' + @Table_Razd31 + ' from #RAZD31')
EXEC dbo.BufferPush -116, @Table_Razd31

--Используется в хранимке SA_4FSS_28022011_PREPARE_INV

--Р3.ТАБЛИЦА 9

Declare @StBase5 table (link int)
Insert into @StBase5 (link)
select distinct link_pays from tax_ref where link_tax = (select top 1 link from pays where object = 3 and way_calc = 5)

--Фактическая база для договорников
SELECT GT.PERS_LINK, MONTH(G.[DATE]) AS MONTH_BASE, SUMMA_BASE = sum(CASE WHEN GT.WAY_CALC  = 5 THEN GT.SUMMA_BASE ELSE 0 END)
INTO #DGH_FAKT_BASE2
FROM 
	dbo.DOCUMENTS_DGH G 
	--INNER JOIN dbo.DOCUMENTS_DGH_T1 T1 ON T1.LINK = G.LINK
	--INNER JOIN dbo.REESTR_DGH R ON R.LINK = T1.LINK_DOG  --AND FLAG_TRAVMA = 1	
	INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK --AND T1.PERS_LINK = GT.PERS_LINK 
WHERE 
	G.LINK_DEP = @DEP_LINK
	AND FLAG_JC = 1
	--AND GT.WAY_CALC  = 5
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3 
GROUP BY   GT.PERS_LINK,  MONTH(G.[DATE]) /*, GT.WAY_CALC*/


SELECT MON, SUMMA_ALL = SUM(SUMMA_ALL), SUMMA_NO = SUM(SUMMA_NO), SUMMA_ALL_I = SUM(SUMMA_ALL_I), SUMMA_NO_I = SUM(SUMMA_NO_I)
INTO #SALARY_SUM
FROM 
(
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(CASE WHEN B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0 THEN SUMMA ELSE 0 END), --на которые не начисляются страховые взносы
	SUMMA_ALL_I = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA ELSE 0 END),
	SUMMA_NO_I = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) AND I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA ELSE 0 END)
from 
	dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
	INNER JOIN DBO.EMPL E ON E.LINK = CJ.LINK_EMPL
	LEFT JOIN @StBase5 B ON B.LINK = cj.LINK_PAYS
	LEFT JOIN DBO.PERS_INVALID I ON I.PERS_LINK = E.PERS_LINK 
			AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN I.DATE_BEGIN AND ISNULL(I.DATE_END,'29990101')
			--AND COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate
where 	
	Year(period_begin) = @nYEAR and Month(period_begin) <= @nMONTH3 
	and CJ.LINK_DEP = @DEP_LINK
	and P.[OBJECT] = 1
GROUP BY
	Month(CJ.PERIOD_BEGIN)
UNION ALL	
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA_ALL = SUM(CJ.SUMMA),
	SUMMA_NO = SUM( CJ.SUMMA - ISNULL(B.SUMMA_BASE,0)), --на которые не начисляются страховые взносы
	SUMMA_ALL_I = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA ELSE 0 END),
	SUMMA_NO_I = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA - ISNULL(B.SUMMA_BASE,0) ELSE 0 END)
from 
	#DGH_CJ CJ
	INNER JOIN #DGH_FAKT_BASE2 B ON B.PERS_LINK = CJ.PERS_LINK AND B.MONTH_BASE = Month(CJ.PERIOD_BEGIN)
	LEFT JOIN DBO.KU_PERS_INVALID I ON I.PERS_LINK = CJ.PERS_LINK 
		AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN I.DATE_BEGIN AND ISNULL(I.DATE_END,'29990101')
		--AND COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate
where 	
	Month(period_begin) <= @nMONTH3 
GROUP BY
	Month(CJ.PERIOD_BEGIN)
) AS T
GROUP BY 
	MON
------------------------

--Льготы по травматизму
DECLARE @LINK_S_OBJ INT
SET @LINK_S_OBJ = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOCUMENTS_CLOSE_MONTH')

CREATE TABLE #TRAVM_LGOTY (I TINYINT, M TINYINT, SUMMA NUMERIC(18,2))
--скидки по травматизму
INSERT INTO #TRAVM_LGOTY (I, M, SUMMA)
SELECT I = (CASE WHEN ISNULL(I.PERS_LINK,0) = 0 THEN 0 ELSE 1 END), MONTH(D.[DATE]), SUM(SUMMA)
FROM
	dbo.SDOC D
	INNER JOIN dbo.SDOC_DOT_SKIDKI S ON S.LINK_UP = D.LINK
	LEFT JOIN dbo.pers_invalid I ON S.LINK_PERS = I.PERS_LINK 
		AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH(D.[DATE]),YEAR(D.[DATE]))) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')	
WHERE
	D.[OBJECT] = @LINK_S_OBJ AND D.FLAG_JC = 1 AND D.LINK_DEP = @DEP_LINK
	AND YEAR(D.[DATE]) = @nYEAR AND MONTH(D.[DATE]) <= @nMONTH3
GROUP BY
	ISNULL(I.PERS_LINK,0), MONTH(D.[DATE])
	
----Вычеты по травматизму	
INSERT INTO #TRAVM_LGOTY (I, M, SUMMA)
SELECT I = (CASE WHEN ISNULL(I.PERS_LINK,0) = 0 THEN 0 ELSE 1 END), MONTH(D.[DATE]), SUM(SUMMA)
FROM
	dbo.SDOC D
	INNER JOIN dbo.SDOC_DOT_VYCHET S ON S.LINK_UP = D.LINK
	LEFT JOIN dbo.pers_invalid I ON S.LINK_PERS = I.PERS_LINK 
		AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH(D.[DATE]),YEAR(D.[DATE]))) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')	
WHERE
	D.[OBJECT] = @LINK_S_OBJ AND D.FLAG_JC = 1 AND D.LINK_DEP = @DEP_LINK
	AND YEAR(D.[DATE]) = @nYEAR AND MONTH(D.[DATE]) <= @nMONTH3
GROUP BY
	ISNULL(I.PERS_LINK,0), MONTH(D.[DATE])	

--Данные для таблицы 6
CREATE TABLE #TABLE6 (MON TINYINT, SUMMA3 NUMERIC(18,2), SUMMA4 NUMERIC(18,2), SUMMA5 NUMERIC(18,2) )
INSERT INTO #TABLE6 (MON, SUMMA3, SUMMA4, SUMMA5)
SELECT 
	M.NUM, 
	SUMMA3 = /*ROUND(*/ ISNULL( (SELECT SUM(SUMMA_ALL)-SUM(SUMMA_NO) FROM #SALARY_SUM WHERE MON = M.NUM) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #TRAVM_LGOTY WHERE M = M.NUM),0) /*,0)*/,
	SUMMA4 = /*ROUND(*/ ISNULL( (SELECT SUM(SUMMA_ALL_I)-SUM(SUMMA_NO_I) FROM #SALARY_SUM WHERE MON = M.NUM) ,0) - ISNULL((SELECT SUM(SUMMA) FROM #TRAVM_LGOTY WHERE I = 1 AND M = M.NUM),0) /*,0)*/,
	SUMMA5 = /*ROUND(*/ ISNULL( (SELECT SUM(SUMMA_NO) FROM #SALARY_SUM WHERE MON = M.NUM) ,0) + ISNULL((SELECT SUM(SUMMA) FROM #TRAVM_LGOTY WHERE M = M.NUM),0) /*,0)*/
FROM
	dbo.MONTHS M
	
	
INSERT INTO #RES2 SELECT '060103', ISNULL( (SELECT SUM(SUMMA3) FROM #TABLE6) ,0) , 0, 0, ''
INSERT INTO #RES2 SELECT '060104', ISNULL( (SELECT SUM(SUMMA4) FROM #TABLE6) ,0), 0, 0, ''
INSERT INTO #RES2 SELECT '060105', ISNULL( (SELECT SUM(SUMMA5) FROM #TABLE6) ,0), 0, 0, ''
---
INSERT INTO #RES2 SELECT '060303', ISNULL( (SELECT SUM(SUMMA3) FROM #TABLE6 WHERE MON = @nMONTH1) ,0) , 0, 0, ''
INSERT INTO #RES2 SELECT '060304', ISNULL( (SELECT SUM(SUMMA4) FROM #TABLE6 WHERE MON = @nMONTH1) ,0), 0, 0, ''
INSERT INTO #RES2 SELECT '060305', ISNULL( (SELECT SUM(SUMMA5) FROM #TABLE6 WHERE MON = @nMONTH1) ,0), 0, 0, ''
---
INSERT INTO #RES2 SELECT '060403', ISNULL( (SELECT SUM(SUMMA3) FROM #TABLE6 WHERE MON = @nMONTH2) ,0) , 0, 0, ''
INSERT INTO #RES2 SELECT '060404', ISNULL( (SELECT SUM(SUMMA4) FROM #TABLE6 WHERE MON = @nMONTH2) ,0), 0, 0, ''
INSERT INTO #RES2 SELECT '060405', ISNULL( (SELECT SUM(SUMMA5) FROM #TABLE6 WHERE MON = @nMONTH2) ,0), 0, 0, ''
---
INSERT INTO #RES2 SELECT '060503', ISNULL( (SELECT SUM(SUMMA3) FROM #TABLE6 WHERE MON = @nMONTH3) ,0) , 0, 0, ''
INSERT INTO #RES2 SELECT '060504', ISNULL( (SELECT SUM(SUMMA4) FROM #TABLE6 WHERE MON = @nMONTH3) ,0), 0, 0, ''
INSERT INTO #RES2 SELECT '060505', ISNULL( (SELECT SUM(SUMMA5) FROM #TABLE6 WHERE MON = @nMONTH3) ,0), 0, 0, ''

--Р3.ТАБЛИЦА 10
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA = SUM(SUMMA)
INTO 
	#SALARY_SUM1
from 
	dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
where 	
	Year(period_begin) = @nYEAR and Month(period_begin) <= @nMONTH3 
	and CJ.LINK_DEP = @DEP_LINK
	and CJ.LINK_PAYS = (select top 1 link from pays where object = 3 and way_calc = 5)
GROUP BY
	Month(CJ.PERIOD_BEGIN)

INSERT INTO #RES2 SELECT '1021', SUM(SUMMA), 0, 0, '' FROM #SALARY_SUM1 WHERE MON < @nMONTH1
INSERT INTO #RES2 SELECT '1023', SUM(SUMMA), 0, 0, '' FROM #SALARY_SUM1 WHERE MON = @nMONTH1
INSERT INTO #RES2 SELECT '1024', SUM(SUMMA), 0, 0, '' FROM #SALARY_SUM1 WHERE MON = @nMONTH2
INSERT INTO #RES2 SELECT '1025', SUM(SUMMA), 0, 0, '' FROM #SALARY_SUM1 WHERE MON = @nMONTH3

--- Номера платежек 
CREATE TABLE #PLAT1(VID TINYINT, Y INT, MON TINYINT, SUMMA NUMERIC(18,2), Y_p INT, MON_p TINYINT, NUMBER VARCHAR(10))

	exec dbo.BufferClear 'DT'
	exec dbo.BufferClear 'KT'

	INSERT INTO BUFFER (link, id)
	select link, 'DT' from s_accounts where cSinth = '303' and cAnalit = '06' --С 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 #PLAT1 (VID, Y, MON, SUMMA,Y_P,MON_P,NUMBER)
	SELECT  1,
		Y = CONVERT(INT,YEAR(p.DATE_PROV)), 
		MON = CONVERT(INT,MONTH(p.DATE_PROV)),
		P.SUMMA,  
		Y_P = CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')), 
		MON_P = CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.')),
		P.NUMBER	
	from 
		dbo.AProvByBufferConditionsShortDate(@START_DATE, @END_DATE, 'DT', 'KT') P	
		inner join dbo.DOCUMENTS_PAY_ADD PA on P.link = PA.link
		inner join dbo.g_prov G on G.link = PA.link
		LEFT JOIN dbo.KOSGU DG ON DG.LINK = P.DT_EKR
	WHERE
		P.DEP_LINK = @DEP_LINK
		AND
		G.DEP = @DEP_LINK
		--AND
		--CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.')) <= @M
		--AND
		--CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')) = @Y
		AND
		DG.CODE <> '290'

	exec dbo.BufferClear 'DT'
	exec dbo.BufferClear 'KT'
	
	
	
INSERT INTO #RES2 (CODE_STR, BASE_FSS, CNT_FSS, CNT_FEM)
SELECT '10123', 
		(SELECT ISNULL(SUM(SUMMA),0) FROM #PLAT1 WHERE Y >= @nYEAR and MON = @nMONTH1), 
		'', 
		0   

INSERT INTO #RES2 (CODE_STR, BASE_FSS, CNT_FSS, CNT_FEM)
SELECT '10124', 
		(SELECT ISNULL(SUM(SUMMA),0) FROM #PLAT1 WHERE Y >= @nYEAR and MON = @nMONTH2), 
		'', 
		0   

INSERT INTO #RES2 (CODE_STR, BASE_FSS, CNT_FSS, CNT_FEM)
SELECT '10125', 
		(SELECT ISNULL(SUM(SUMMA),0) FROM #PLAT1 WHERE Y >= @nYEAR and MON = @nMONTH3), 
		'', 
		0   

--- Сведения по номерам платежек
SELECT  VID,
		Y , 
		MON ,
		NUMBER	
INTO #PLAT_PP1
FROM #PLAT1 
GROUP  BY VID , Y , MON, NUMBER

DROP TABLE #PLAT1

BEGIN 
	declare @Cur_1 cursor , @VID1 tinyint , @Y1 INT, @MON1 TINYINT, @NUMBER1 VARCHAR(10)

	SET @Cur_1 = CURSOR FORWARD_ONLY
	FOR 
		select VID, Y, MON, NUMBER from #PLAT_PP1 order by VID, Y, MON, NUMBER
	OPEN @Cur_1
	FETCH NEXT FROM @Cur_1 INTO @VID1, @Y1, @MON1, @NUMBER1
	
	WHILE (@@fetch_status <> -1)
	BEGIN
		
		IF (@@fetch_status <> -2)
		BEGIN	
			if  @Y1 = @nYEAR and @MON1 = @nMONTH1
				UPDATE #RES2
					set NUM_PP = (case when NUM_PP is null or NUM_PP= '' then ltrim(RTRIM(@NUMBER1)) else ltrim(RTRIM(NUM_PP))+','+ ltrim(RTRIM(@NUMBER1)) end )
				where code_str = '10123' 

			if  @Y1 = @nYEAR and @MON1 = @nMONTH2
				UPDATE #RES2
					set NUM_PP = (case when NUM_PP is null or NUM_PP= '' then ltrim(RTRIM(@NUMBER1)) else ltrim(RTRIM(NUM_PP))+','+ ltrim(RTRIM(@NUMBER1)) end )
				where code_str = '10124'

			if  @Y1 = @nYEAR and @MON1 = @nMONTH3
				UPDATE #RES2
					set NUM_PP = (case when NUM_PP is null or NUM_PP= '' then ltrim(RTRIM(@NUMBER1)) else ltrim(RTRIM(NUM_PP))+','+ ltrim(RTRIM(@NUMBER1)) end )
				where code_str = '10125'				

		end
		FETCH NEXT FROM @Cur_1 INTO @VID1, @Y1, @MON1, @NUMBER1
	end

CLOSE @Cur_1
DEALLOCATE @Cur_1

END 

drop table #PLAT_PP1

-- exec dbo.RI_REPORT_FORMULA_ALL_CALCULATE '2014-01-01 00:00:00','2014-03-31 00:00:00',2,1,2745
/*declare @Res float
set @Res = 0
 exec dbo.RSA_4FSS_09022012_PREPARE @Res output, '', '20140101', '20140331', 2, 1, 2745
*/






INSERT INTO #RES2
SELECT '1101', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 10),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 10),0),	
	0, ''

INSERT INTO #RES2
SELECT '1102', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 10 AND [STATUS] = 3),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 10 AND [STATUS] = 3),0),	
	0, ''	
	
INSERT INTO #RES2
SELECT '1104', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 11),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 11),0),	
	0, ''

INSERT INTO #RES2
SELECT '1105', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 11 AND [STATUS] = 3),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 11 AND [STATUS] = 3),0),	
	0, ''		

INSERT INTO #RES2
SELECT '1107', 
	ISNULL((SELECT SUM(SUMMA) FROM #ATR_4FSS WHERE F4FSS = 12),0),
	ISNULL((SELECT SUM(CNT_DAYS) FROM #ATR_4FSS WHERE F4FSS = 12),0),	
	0, ''

DECLARE  @SPO4 INT
SELECT @SPO4 = (SELECT distinct LINK FROM dbo.SA_SZV4_SPR WHERE code = 'О4' AND spr_code = 'SPO_USL_TRUDA' )




----- Таблица результатов по спецоценке
--Р2.ТАБЛИЦА 10
select [KOL_ALL] = SUM(S.NUM_STAKE),
		[KOL_SPO_ALL] = SUM(CASE WHEN S.COD_SPO_USL_TRUD IS NOT NULL THEN S.NUM_STAKE ELSE 0 END ),
		[KOL_SPO_3] =  SUM(CASE WHEN (ISNULL(S.COD_SPO_USL_TRUD, 0) <> 0 
							AND S.COD_SPO_USL_TRUD = @SPO4 
							)  
					   THEN  S.NUM_STAKE 
					   ELSE 0 END) ,	   
		[KOL_SPO_4] = SUM(CASE WHEN (ISNULL(S.COD_SPO_USL_TRUD, 0) <> 0 
							AND S.COD_SPO_USL_TRUD <> @SPO4 
							)  
					   THEN  S.NUM_STAKE 
					   ELSE 0 END) 	  
	
INTO 
	#STAF_ALL
from 
	dbo.staff s inner join dbo.staff_head sh on s.link_up = sh.LINK
where 	
	sh.DEP_LINK = @DEP_LINK
	and @vardEnd between s.date_begin and s.date_end 




INSERT INTO #RES2 SELECT '100103', KOL_ALL, 0, 0, '' FROM #STAF_ALL 
INSERT INTO #RES2 SELECT '100104', KOL_SPO_ALL, 0, 0, '' FROM #STAF_ALL 
INSERT INTO #RES2 SELECT '100105', KOL_SPO_3, 0, 0, '' FROM #STAF_ALL 
INSERT INTO #RES2 SELECT '100106', KOL_SPO_4, 0, 0, '' FROM #STAF_ALL 


/* Завершаем - списываем значения во временную таблицу */
DECLARE @Table_Razd1 VARCHAR(100)
EXEC dbo.X_GET_TABLE_NAME @Table_Razd1 OUTPUT
EXEC ('select * INTO ' + @Table_Razd1 + ' from #RES2 order by code_str')
EXEC dbo.BufferPush -115, @Table_Razd1


DROP TABLE #RES2
DROP TABLE #SPR_ESN
DROP TABLE #ATR_4FSS
DROP TABLE #DGH_FAKT_BASE
DROP TABLE #SALARY_SUM2
DROP TABLE #SPR_ESN1
DROP TABLE #SPR_ESN2
DROP TABLE #SPR_ESN1KATEG3
DROP TABLE #SPR_ESN2KATEG3
DROP TABLE #RAZD31
DROP TABLE #DGH_FAKT_BASE2
DROP TABLE #SALARY_SUM
DROP TABLE #SALARY_SUM1
DROP TABLE #TRAVM_LGOTY
DROP TABLE #TABLE6




GO


GRANT EXECUTE ON dbo.[RSA_4FSS_09022012_PREPARE] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SZVK_SV_WD_DELETE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZVK_SV_WD_DELETE]

GO



---------------------------------

CREATE PROCEDURE dbo.SA_SZVK_SV_WD_DELETE
	@varKSintLINK	int
AS
DECLARE @varKStrancount	int,
		@varKSObjectLink	int,
		@varKSEventText	varchar(254)

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

	DECLARE @link_up int
	select @link_up = link_up from dbo.SZV_K_sved_WORK_DEP where link = @varKSintLINK
	
	Select  @varKSEventText = 'Период трудовой или иной общественно-полезной деятельности по физлицу ' + RTRIM(LTRIM(FIO)) from dbo.SA_SZV_K_SVEDENIA 
		WHERE link = @LINK_UP


	Select  @varKSEventText = @varKSEventText + ' № ' + STR(orders) + ' наименование ' + LTRIM(RTRIM(NAME_DEP)) + ' вид деятельности' + LTRIM(RTRIM(VID_WORK_N)) from dbo.SA_SZV_K_sved_WORK_DEP 
		WITH (UPDLOCK) WHERE link1 = @varKSintLINK    

	IF @@RowCount = 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 2
	END

	DELETE FROM dbo.SZV_K_sved_WORK_DEP WHERE LINK = @varKSintLINK
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END


	/*Правильная сортировка*/
	declare @uslovie int
	set @uslovie = 1
	
	update SZV_K_sved_WORK_DEP set orders = 0 where link_up = @link_up
	
	while @uslovie > 0
	begin
		update SZV_K_sved_WORK_DEP set orders = @uslovie 
		from SZV_K_sved_WORK_DEP as tt
		where 	
			link_up = @link_up
			and coalesce(orders,0) = 0
			and link= (select min(link) from SZV_K_sved_WORK_DEP t where coalesce(orders,0) = 0 and link_up = @link_up)
	
		if @@rowcount > 0
			set @uslovie = @uslovie + 1
		else
			set @uslovie = 0
	end

IF @@TRANCOUNT > @varKStrancount
	BEGIN
		SELECT @varKSObjectLink = LINK FROM S_OBJECTS WHERE CODE = 'SA_SZV_K_DEP_PERIOD'
		EXECUTE WF_GENERATEEVENT 'Удаление из справочника', @varKSEventText, @varKSObjectLink, 'SA_SZV_K_DEP_PERIOD', @varKSintLINK

		COMMIT TRAN
	END
RETURN 0



GO


GRANT EXECUTE ON dbo.[SA_SZVK_SV_WD_DELETE] TO PUBLIC

GO




GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SZVK_SV_WD_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZVK_SV_WD_SAVE]

GO

/*declare @p1 float
set @p1=7
exec [dbo].SA_SZVK_SV_WD_SAVE @p1 output,1,0,74578,'СОЦСТРАХ'
select @p1

select * from szv4_spr
select * from SZV_K_SVED_WORK_DEP
*/


------------------------------------------------------------------------
CREATE   PROCEDURE dbo.SA_SZVK_SV_WD_SAVE
	@link		int output,
	@link_up	int,
	@orders		int,
	@NAME_DEP   VARCHAR(254),
	@INN		VARCHAR(12),
	@KPP		VARCHAR(9),
	@OKPO		VARCHAR(20),
	@vid_work	VARCHAR(10)
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 ISNULL(@NAME_DEP,'') = '' or ISNULL(@vid_work,'') = ''
BEGIN
	ROLLBACK
	RETURN 5
END

SELECT @varKSsoLink = LINK FROM s_objects  WHERE CODE = 'SA_SZV_K_DEP_PERIOD'

IF @LINK is null OR @LINK = 0
	BEGIN

		INSERT INTO dbo.SZV_K_sved_work_dep WITH (ROWLOCK) (link_up, orders, NAME_DEP, INN,KPP, OKPO, vid_work)
			VALUES (@link_up, @orders, @NAME_DEP, @INN,@KPP,@OKPO, ltrim(rtrim(@vid_work)))

		SELECT @varKSERROR = @@ERROR, @LINK = @@IDENTITY
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
ELSE
	BEGIN

		UPDATE dbo.SZV_K_sved_work_dep WITH (ROWLOCK) 
		SET 	link_up = @link_up, orders = @orders, NAME_DEP = @NAME_DEP,INN= @INN,KPP=@KPP,OKPO= @OKPO, vid_work = ltrim(RTRIM(@vid_work))

		WHERE LINK = @LINK

		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END

/*Правильная сортировка*/
declare @uslovie int
set @uslovie = 1

update SZV_K_sved_work_dep set orders = 0 where link_up = @link_up

while @uslovie > 0
begin
	update SZV_K_sved_work_dep set orders = @uslovie 
	from SZV_K_sved_work_dep as tt
	where 	
		link_up = @link_up
		and coalesce(orders,0) = 0
		and link = (select min(t.link) from SZV_K_sved_work_dep t where coalesce(orders,0) = 0 and link_up = @link_up)

	if @@rowcount > 0
		set @uslovie = @uslovie + 1
	else
		set @uslovie = 0
end


declare @varKSEventText varchar(200)
Select  @varKSEventText = 'Период трудовой или иной общественно-полезной деятельности для СЗВ-К по физлицу' + RTRIM(LTRIM(FIO)) from dbo.SA_SZV_K_SVEDENIA where link = @LINK_UP
/*EXECUTE WF_GENERATEEVENT 'Сохранение расчета', @varKSEventText, @varKSsoLink, 'SA_SZV_K_DEP_PERIOD',@LINK
*/WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN

RETURN 0






GO


GRANT EXECUTE ON dbo.[SA_SZVK_SV_WD_SAVE] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SAL_CHANGE_KBK]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SAL_CHANGE_KBK]

GO

CREATE    PROC [dbo].SAL_CHANGE_KBK
	@OLD_KBK_LINK	INT,
	@NEW_KBK_LINK	INT,
	@DATE		DATETIME,
	@OPT1		TINYINT = 0,
	@OPT2		TINYINT = 0,
	@OPT3		TINYINT = 0,
	@OPT4		TINYINT = 0,
	@LINK_EMPL	INT = NULL,
	@OPT5		TINYINT = 0 --Замена у договорников
AS

IF COALESCE(is_member('db_owner'),0) = 0
BEGIN
	RAISERROR('Данная функция работает только для пользователя роли "DB_OWNER" !!!',11,1)
	RETURN 1
END


IF @LINK_EMPL IS NOT NULL
	SET @OPT5 = 0

---
IF @OLD_KBK_LINK IS NULL
OR @OLD_KBK_LINK = 0
OR @NEW_KBK_LINK IS NULL
OR @NEW_KBK_LINK = 0
OR @DATE IS NULL
	RETURN 1


declare @varKSparSFIN varchar(20),  @varKSparSFIN_OLD varchar(20) , @cStr VARCHAR (256)

SELECT 
	@varKSparSFIN_OLD = CODE,
	@varKSparSFIN = (SELECT B.CODE FROM dbo.SAL_SFIN B WHERE B.LINK = A.LINK_CH_SFIN)
FROM dbo.SAL_SFIN A WHERE A.LINK = @OLD_KBK_LINK AND A.LINK_CH_SFIN IS NOT NULL AND A.LINK_CH_SFIN <> @NEW_KBK_LINK

IF @varKSparSFIN IS NOT NULL
BEGIN

		SET @cStr = 'В спраочнике "Источники финансирования" для источника "'+LTRIM(RTRIM(@varKSparSFIN_OLD)) +'" указан новый источник "'+ltrim(rtrim(@varKSparSFIN))+'"!'
		RAISERROR(@cStr, 11, 1)
		RETURN 1
END	



declare @DEP_LINK int
exec dbo.xd_whats_zb @DEP_LINK output

DECLARE @LINK_EMPL1 INT
SET @LINK_EMPL1 = (CASE WHEN @LINK_EMPL IS NULL THEN -1 ELSE @LINK_EMPL END)

SET @OPT1 = COALESCE(@OPT1,0)
SET @OPT2 = COALESCE(@OPT2,0)
SET @OPT3 = COALESCE(@OPT3,0)
SET @OPT4 = COALESCE(@OPT4,0)
SET @OPT5 = COALESCE(@OPT5,0)

---Расширить период редактирования
SELECT * INTO #TMP_DATES FROM dbo.ADMIN_INFO

DECLARE @KASSA INT, @BB DATETIME, @BE DATETIME
SELECT @KASSA = LINK FROM DBO.S_OBJECTS WHERE CODE = 'KASSA'
SELECT @BB = CONVERT(DATETIME, '19000101', 112), @BE = CONVERT(DATETIME, '20990101', 112)
EXECUTE DBO.I_SET_ADMIN_DATE @KASSA, @BB, @BB, @BE

IF @OPT1 = 1 BEGIN

	/*ПОСТОЯННЫЕ НАЧИСЛЕНИЯ*/
	INSERT INTO dbo.PAYS_EMPL (LINK_EMPL, LINK_SOVM, LINK_PAYS, DATE, SUMMA, LINK_MP, LINK_KBK, NO_CALC)
	SELECT 
		PE.LINK_EMPL, PE.LINK_SOVM, PE.LINK_PAYS, [DATE] = @DATE, PE.SUMMA, PE.LINK_MP, LINK_KBK = @NEW_KBK_LINK, PE.NO_CALC
	FROM dbo.sa_dict_pays_empl0(@LINK_EMPL1,DEFAULT,DEFAULT) PE INNER JOIN dbo.EMPL E ON E.LINK = PE.LINK_EMPL
	WHERE
		E.DEP_LINK = @DEP_LINK
		AND PE.LINK_KBK = @OLD_KBK_LINK
		AND @DATE BETWEEN PE.DATE_BEG AND ISNULL(PE.DATE_END,@DATE)
		AND @DATE > PE.[DATE_BEG]
		AND PE.SUMMA > 0
		AND NOT EXISTS (SELECT * FROM dbo.PAYS_EMPL PE2 WHERE PE.LINK_EMPL = PE2.LINK_EMPL 
							AND ISNULL(PE.LINK_SOVM,0) = ISNULL(PE2.LINK_SOVM,0)
							AND PE.[LINK_PAYS] = PE2.[LINK_PAYS]						
							AND @DATE = PE2.[DATE]
							)
	ORDER BY
			PE.LINK_EMPL, PE.LINK_SOVM					

	UPDATE PE
		SET PE.LINK_KBK = @NEW_KBK_LINK
	FROM dbo.PAYS_EMPL PE INNER JOIN dbo.EMPL E ON E.LINK = PE.LINK_EMPL
	WHERE	
		E.DEP_LINK = @DEP_LINK
		AND PE.LINK_KBK = @OLD_KBK_LINK
		AND @DATE = PE.[DATE]
		AND PE.SUMMA > 0
		AND	(@LINK_EMPL IS NULL OR @LINK_EMPL = E.LINK)	
	
	----Часы нагрузки
	if object_id('tempdb..#STO_WEEK_HOURS') is not null
		DROP TABLE #STO_WEEK_HOURS

	SELECT 
		PE.link, PE.link_up, PE.link_tar_empl, PE.link_pay, PE.link_paral, PE.link_clas, PE.link_les, PE.week_hours, PE.[percent], PE.t, 
		DATE1 = @DATE, PE.DATE2, LINK_KBK = @NEW_KBK_LINK, PE.link_empl, PE.NO_CALC, PE.M_STAVKA	
	INTO #STO_WEEK_HOURS	
	FROM dbo.EMPL E INNER JOIN dbo.STO_WEEK_HOURS PE ON PE.LINK_EMPL = E.LINK
	WHERE	
		LINK_KBK = @OLD_KBK_LINK
		AND @DATE BETWEEN PE.DATE1 AND ISNULL(PE.DATE2,@DATE)
		AND @DATE > PE.DATE1
		AND E.dep_link = @DEP_LINK
		AND	(@LINK_EMPL IS NULL OR @LINK_EMPL = E.LINK)	
	---
	INSERT INTO dbo.STO_WEEK_HOURS (link_up, link_tar_empl, link_pay, link_paral, link_clas, link_les, week_hours,[percent], t, DATE1, DATE2, LINK_KBK, link_empl, NO_CALC, M_STAVKA)
	SELECT link_up, link_tar_empl, link_pay, link_paral, link_clas, link_les, week_hours,[percent], t, DATE1, DATE2, LINK_KBK, link_empl, NO_CALC, M_STAVKA
	FROM
		#STO_WEEK_HOURS PE
	WHERE
		(@LINK_EMPL IS NULL OR @LINK_EMPL = PE.LINK_EMPL)	
		AND
		NOT EXISTS (SELECT * FROM dbo.STO_WEEK_HOURS PE2 WHERE PE.LINK_EMPL = PE2.LINK_EMPL 
							AND ISNULL(PE.link_tar_empl,0) = ISNULL(PE2.link_tar_empl,0)
							AND PE.[link_pay] = PE2.[link_pay]						
							AND @DATE = PE2.[DATE1] )				
	---
	UPDATE PE
	SET PE.DATE2 = DATEADD(DAY,-1,@DATE)
	FROM dbo.STO_WEEK_HOURS PE INNER JOIN #STO_WEEK_HOURS PE2 ON PE.LINK = PE2.LINK
	WHERE (@LINK_EMPL IS NULL OR @LINK_EMPL = PE.LINK_EMPL)

	-----
	UPDATE PE
		SET PE.LINK_KBK = @NEW_KBK_LINK
	FROM dbo.EMPL E INNER JOIN dbo.STO_WEEK_HOURS PE ON PE.LINK_EMPL = E.LINK
	WHERE	
		LINK_KBK = @OLD_KBK_LINK
		AND @DATE = PE.DATE1
		AND E.dep_link = @DEP_LINK
		AND (@LINK_EMPL IS NULL OR @LINK_EMPL = PE.LINK_EMPL)

	------------ Надбавка за предмет
	UPDATE	dbo.STO_LESSON_PAYS
	SET	LINK_KBK = @NEW_KBK_LINK
	WHERE	
		ISNULL(LINK_KBK,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND @DATE <= [date_begin]
		AND dep_link = @DEP_LINK
		AND @LINK_EMPL IS NULL
	
	----Надбавки по тарификации
	if object_id('tempdb..#STO_ADD_PAYMENT') is not null
		DROP TABLE #STO_ADD_PAYMENT

	SELECT 
		PE.LINK, PE.link_tar_empl, PE.link_pay, date_begin = @DATE, PE.date_end, PE.[percent], PE.comment, PE.ets_only, PE.mode, 
		PE.summa, LINK_KBK = @NEW_KBK_LINK, PE.link_expir, PE.link_empl, PE.NO_CALC
	INTO #STO_ADD_PAYMENT	
	FROM dbo.EMPL E INNER JOIN dbo.STO_ADD_PAYMENT PE ON PE.LINK_EMPL = E.LINK
	WHERE	
		LINK_KBK = @OLD_KBK_LINK
		AND @DATE BETWEEN PE.DATE_BEGIN AND ISNULL(PE.DATE_END,@DATE)
		AND @DATE > PE.DATE_BEGIN
		AND E.dep_link = @DEP_LINK
		AND (@LINK_EMPL IS NULL OR @LINK_EMPL = PE.LINK_EMPL)
	---
	INSERT INTO dbo.STO_ADD_PAYMENT (link_tar_empl, link_pay, date_begin, date_end, [percent], comment, ets_only, mode, 
		summa, LINK_KBK, link_expir, link_empl, NO_CALC)
	SELECT link_tar_empl, link_pay, date_begin, date_end, [percent], comment, ets_only, mode, 
		summa, LINK_KBK, link_expir, link_empl, NO_CALC
	FROM
		#STO_ADD_PAYMENT PE
	WHERE
		(@LINK_EMPL IS NULL OR @LINK_EMPL = PE.LINK_EMPL)
		AND
		NOT EXISTS (SELECT * FROM dbo.STO_ADD_PAYMENT PE2 WHERE PE.LINK_EMPL = PE2.LINK_EMPL 
							AND ISNULL(PE.link_tar_empl,0) = ISNULL(PE2.link_tar_empl,0)
							AND PE.[link_pay] = PE2.[link_pay]						
							AND @DATE = PE2.[DATE_BEGIN]
							)				
	---
	UPDATE PE
	SET PE.DATE_END = DATEADD(DAY,-1,@DATE)
	FROM dbo.STO_ADD_PAYMENT PE INNER JOIN #STO_ADD_PAYMENT PE2 ON PE.LINK = PE2.LINK
	WHERE (@LINK_EMPL IS NULL OR @LINK_EMPL = PE.LINK_EMPL)

	-----
	UPDATE PE
		SET PE.LINK_KBK = @NEW_KBK_LINK
	FROM dbo.EMPL E INNER JOIN dbo.STO_ADD_PAYMENT PE ON PE.LINK_EMPL = E.LINK
	WHERE	
		LINK_KBK = @OLD_KBK_LINK
		AND @DATE = PE.DATE_BEGIN
		AND E.dep_link = @DEP_LINK			
		AND (@LINK_EMPL IS NULL OR @LINK_EMPL = PE.LINK_EMPL)
	
	-- Постоянные удержания
	UPDATE dbo.EMPL_TAX
	SET	LINK_VKR = @NEW_KBK_LINK
	FROM dbo.EMPL E INNER JOIN dbo.EMPL_TAX ET ON ET.LINK_EMPL = E.LINK
	WHERE ISNULL(LINK_VKR,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND @DATE <= ISNULL(DATE2,@DATE)
		AND E.DEP_LINK = @DEP_LINK
		AND (@LINK_EMPL IS NULL OR @LINK_EMPL = ET.LINK_EMPL)
	
	--- Замена в штатном расписании
	SELECT 
		T.LINK_UP, T.SUBDIV_LINK, T.POST_LINK, T.OKLAD, T.NUM_STAKE,
		T.DEY_LINK, T.KAT_LINK, T.GOSSL, T.FIN, T.FIN_FOND, T.KAT_GOS_LINK, 
		DATE_BEGIN = @DATE, T.DATE_END, T.GR_GOS_LINK, T.ETS_RAZR, LINK_KBK = @NEW_KBK_LINK
	INTO	#TMP
	FROM	dbo.STAFF_HEAD H INNER JOIN STAFF T ON H.LINK = T.LINK_UP
	WHERE	@DATE BETWEEN T.DATE_BEGIN AND T.DATE_END
		AND H.DEP_LINK = @DEP_LINK
		AND ISNULL(T.LINK_KBK,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND @DATE > T.DATE_BEGIN
		AND (@LINK_EMPL IS NULL OR @LINK_EMPL IS NOT NULL AND EXISTS (SELECT * FROM dbo.ITEM_MOVE IM WHERE IM.EMPL_LINK = @LINK_EMPL AND IM.STAFF_LINK = H.LINK))
		
	---
	ALTER TABLE dbo.STAFF DISABLE TRIGGER ALL

		UPDATE	dbo.STAFF
		SET	DATE_END = DATEADD(DAY,-1,@DATE)
		FROM	dbo.STAFF_HEAD H INNER JOIN dbo.STAFF T ON H.LINK = T.LINK_UP
		WHERE	@DATE BETWEEN T.DATE_BEGIN AND T.DATE_END 
			AND H.DEP_LINK = @DEP_LINK
			AND @DATE > T.DATE_BEGIN
			AND ISNULL(T.LINK_KBK,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND (@LINK_EMPL IS NULL OR @LINK_EMPL IS NOT NULL AND EXISTS (SELECT * FROM dbo.ITEM_MOVE IM WHERE IM.EMPL_LINK = @LINK_EMPL AND IM.STAFF_LINK = H.LINK))

	ALTER TABLE [dbo].[STAFF] ENABLE  TRIGGER ALL

	---

	ALTER TABLE dbo.STAFF DISABLE TRIGGER ALL

		INSERT INTO dbo.STAFF
		(
			LINK_UP, SUBDIV_LINK, POST_LINK, OKLAD, NUM_STAKE, 
			DEY_LINK, KAT_LINK, GOSSL, FIN, FIN_FOND, KAT_GOS_LINK, 
			DATE_BEGIN, DATE_END, GR_GOS_LINK, ETS_RAZR, LINK_KBK
		)
		SELECT 
			LINK_UP, SUBDIV_LINK, POST_LINK, OKLAD, NUM_STAKE, 
			DEY_LINK, KAT_LINK, GOSSL, FIN, FIN_FOND, KAT_GOS_LINK, 
			DATE_BEGIN, DATE_END, GR_GOS_LINK, ETS_RAZR, LINK_KBK
		from	 #TMP

	ALTER TABLE [dbo].[STAFF] ENABLE  TRIGGER ALL
	
	---
	ALTER TABLE dbo.STAFF DISABLE TRIGGER ALL

		UPDATE	dbo.STAFF
		SET	LINK_KBK = @NEW_KBK_LINK
		FROM	dbo.STAFF_HEAD H INNER JOIN dbo.STAFF T ON H.LINK = T.LINK_UP
		WHERE	H.DEP_LINK = @DEP_LINK
			AND T.DATE_BEGIN = @DATE
			AND ISNULL(T.LINK_KBK,@OLD_KBK_LINK) = @OLD_KBK_LINK
			AND (@LINK_EMPL IS NULL OR @LINK_EMPL IS NOT NULL AND EXISTS (SELECT * FROM dbo.ITEM_MOVE IM WHERE IM.EMPL_LINK = @LINK_EMPL AND IM.STAFF_LINK = H.LINK))

	ALTER TABLE [dbo].[STAFF] ENABLE  TRIGGER ALL

	--- Замена в расчетах отчислений ЕСН
	ALTER TABLE dbo.SDOC_ESN_TABLE DISABLE TRIGGER ALL

	UPDATE GT
	SET	
		GT.LINK_VKR = @NEW_KBK_LINK
	FROM 
		dbo.SDOC S 
		INNER JOIN dbo.SDOC_ESN SD on S.LINK = SD.LINK_UP
		INNER JOIN dbo.SDOC_ESN_TABLE GT on S.LINK = GT.LINK_UP
	WHERE
		@DATE <= S.DATE_CALC
		AND
		S.LINK_DEP = @DEP_LINK
		AND
		ISNULL(GT.LINK_VKR,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND 
		(@LINK_EMPL IS NULL OR @LINK_EMPL = GT.LINK_EMPL)

	ALTER TABLE [dbo].SDOC_ESN_TABLE ENABLE  TRIGGER ALL

END

 --Замена в журнале операций
IF @OPT2 = 1 BEGIN

	ALTER TABLE [dbo].[CALCULATE_JURNAL]
		DISABLE TRIGGER ALL
	
	UPDATE dbo.CALCULATE_JURNAL 
	SET LINK_VKR = @NEW_KBK_LINK 
	WHERE ISNULL(LINK_VKR,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND @DATE <= PERIOD_BEGIN -- Сформированные после смены КБК
		AND LINK_DEP = @DEP_LINK
		AND (@LINK_EMPL IS NULL OR LINK_EMPL = @LINK_EMPL)

	ALTER TABLE [dbo].[CALCULATE_JURNAL]
		ENABLE  TRIGGER ALL


	--Замена в предоставленных вычетах
	ALTER TABLE [dbo].[SAL_DED_MONTH]
		DISABLE TRIGGER ALL
	
	UPDATE dbo.SAL_DED_MONTH 
	SET LINK_VKR = @NEW_KBK_LINK 
	FROM SAL_DED_MONTH CJ INNER JOIN dbo.EMPL E ON CJ.LINK_EMPL = E.LINK
	WHERE ISNULL(LINK_VKR,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND @DATE <= DATE_DED -- Сформированные после смены КБК
		AND E.DEP_LINK = @DEP_LINK
		AND (@LINK_EMPL IS NULL OR CJ.LINK_EMPL = @LINK_EMPL)
	
	ALTER TABLE [dbo].[SAL_DED_MONTH]
		ENABLE  TRIGGER ALL

END

 --Замена в остатках
IF @OPT3 = 1 BEGIN

	ALTER TABLE [dbo].[SAL_REMAIN]
		DISABLE TRIGGER ALL
	
	UPDATE dbo.SAL_REMAIN 
	SET LINK_VKR = @NEW_KBK_LINK 
	FROM dbo.SAL_REMAIN R INNER JOIN dbo.EMPL E ON R.LINK_EMPL = E.LINK
	WHERE ISNULL(LINK_VKR,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND year(@DATE) <= YEAR_SAL
		AND E.DEP_LINK = @DEP_LINK
		AND (@LINK_EMPL IS NULL OR R.LINK_EMPL = @LINK_EMPL)
	
	ALTER TABLE [dbo].[SAL_REMAIN]
		ENABLE  TRIGGER ALL
END

IF @OPT4 = 1 BEGIN
	--Замена в исполнительных листах
	ALTER TABLE dbo.SDOC_WRIT DISABLE TRIGGER ALL
	
		UPDATE dbo.SDOC_WRIT
		SET	LINK_VKR = @NEW_KBK_LINK
		FROM dbo.SDOC S INNER JOIN dbo.SDOC_WRIT SD ON S.LINK = SD.LINK_UP 
		WHERE ISNULL(LINK_VKR,@OLD_KBK_LINK) = @OLD_KBK_LINK
			AND (@DATE <= DATE1 OR @DATE BETWEEN DATE1 AND DATE2)
			AND S.LINK_DEP = @DEP_LINK
			AND (@LINK_EMPL IS NULL OR SD.LINK_EMPL = @LINK_EMPL)
	
	ALTER TABLE [dbo].[SDOC_WRIT] ENABLE  TRIGGER ALL
END

IF @OPT5 = 1 BEGIN

	--Замена в договорах
	CREATE TABLE #REESTR_DGH (NEW_LINK int NOT NULL, OLD_LINK int NOT NULL)

	INSERT INTO dbo.REESTR_DGH 
		(NUMBER, [DATE], DATE1, DATE2, [TYPE], PAYMENT, SUMMA, COMMENT, VZNOS, LINK_PAYS, FLAG_NALOG, DEP_LINK, PERS_LINK, FLAG_ESN, FLAG_TRAVMA, LINK_KBK, AVANCE)
	OUTPUT inserted.LINK, inserted.SUMMA INTO #REESTR_DGH (NEW_LINK, OLD_LINK) --временно вместо суммы копирую страрый линк для истории, сумму потом верну из старой записи
	SELECT
		NUMBER, [DATE], @DATE, DATE2, [TYPE], PAYMENT, LINK, COMMENT, VZNOS, LINK_PAYS, FLAG_NALOG, DEP_LINK, PERS_LINK, FLAG_ESN, FLAG_TRAVMA, @NEW_KBK_LINK, AVANCE
	FROM 
		dbo.REESTR_DGH R
	WHERE
		R.DEP_LINK = @DEP_LINK
		AND
		R.LINK_KBK = @OLD_KBK_LINK
		AND
		@DATE <= ISNULL(DATE2,@DATE)
		AND
		@DATE > ISNULL(DATE1,@DATE)
	
	--	
	UPDATE dbo.REESTR_DGH SET LINK_KBK = @NEW_KBK_LINK WHERE LINK_KBK = @OLD_KBK_LINK AND @DATE <= ISNULL(DATE1,@DATE)		

	UPDATE B SET B.DATE2 = @DATE - 1
	FROM #REESTR_DGH A INNER JOIN dbo.REESTR_DGH B ON B.LINK = A.OLD_LINK

	--в новых копиях возвращаю на место сумму из копий
	UPDATE C
		SET C.SUMMA = B.SUMMA 
	FROM
		#REESTR_DGH A 
		INNER JOIN dbo.REESTR_DGH B ON B.LINK = A.OLD_LINK		
		INNER JOIN dbo.REESTR_DGH C ON C.LINK = A.NEW_LINK

	--Копирую хвост с вычетами
	INSERT INTO dbo.EMPL_DED (DED_LINK, DATE1, DATE2, LINK_DGH)
	SELECT 
		DED_LINK, DATE1, DATE2, A.NEW_LINK
	FROM 
		#REESTR_DGH A INNER JOIN dbo.EMPL_DED B ON B.LINK_DGH = A.OLD_LINK

	--в постоянных удержаниях тоже замена КБК
	--новые строки со старыми линками
	SELECT 
		B.LINK, LINK_TAX, @DATE AS DATE1, DATE2, SUMMA, @NEW_KBK_LINK AS LINK_VKR, B.LINK_DGH
	INTO
		#TMP_EMPL_TAX	
	FROM 
		#REESTR_DGH A INNER JOIN dbo.EMPL_TAX B ON B.LINK_DGH = A.OLD_LINK
	WHERE
		B.LINK_VKR = @OLD_KBK_LINK
		AND
		@DATE <= ISNULL(DATE2,@DATE)
		AND
		@DATE > ISNULL(DATE1,@DATE)
		
	---	
	UPDATE B SET B.LINK_VKR = @NEW_KBK_LINK
	FROM dbo.EMPL_TAX B
	WHERE B.LINK_VKR = @OLD_KBK_LINK AND @DATE <= ISNULL(B.DATE1,@DATE)	
	
	--вставляю новые строки
	INSERT INTO dbo.EMPL_TAX (LINK_TAX, DATE1, DATE2, SUMMA, LINK_VKR, LINK_DGH)
	SELECT LINK_TAX, DATE1, DATE2, SUMMA, LINK_VKR, LINK_DGH FROM #TMP_EMPL_TAX

	--в тех строках, с которых сделал копию закрываю дату
	UPDATE B SET DATE2 = @DATE - 1
	FROM #TMP_EMPL_TAX A INNER JOIN dbo.EMPL_TAX B ON B.LINK = A.LINK

	--Копирую хвост с постоянными удержаниями
	INSERT INTO dbo.EMPL_TAX (LINK_TAX, DATE1, DATE2, SUMMA, LINK_VKR, LINK_DGH)
	SELECT 
		LINK_TAX, DATE1, DATE2, SUMMA, LINK_VKR, A.NEW_LINK
	FROM 
		#REESTR_DGH A INNER JOIN dbo.EMPL_TAX B ON B.LINK_DGH = A.OLD_LINK

	--Замена в журнале операций по договорникам

	ALTER TABLE [dbo].[CALCULATE_JURNAL]
		DISABLE TRIGGER ALL
	
	UPDATE dbo.CALCULATE_JURNAL SET LINK_VKR = @NEW_KBK_LINK 
	WHERE 
		ISNULL(LINK_VKR,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND @DATE <= PERIOD_BEGIN -- Сформированные после смены КБК
		AND LINK_DEP = @DEP_LINK
		AND PERS_LINK IS NOT NULL

	ALTER TABLE [dbo].[CALCULATE_JURNAL]
		ENABLE  TRIGGER ALL		

END

--
UPDATE dbo.SAL_SFIN SET LINK_CH_SFIN = @NEW_KBK_LINK, DATE_CHANGE = @DATE, USED = 0 WHERE LINK = @OLD_KBK_LINK 

--ВЕРНУТЬ ПРЕЖНИЙ ПЕРИОД РЕДАКТИРОВАНИЯ

SELECT @BB = BEGINDATE, @BE = ENDDATE FROM #TMP_DATES
EXECUTE DBO.I_SET_ADMIN_DATE @KASSA, @BB, @BB, @BE


RETURN 0



GO


GRANT EXECUTE ON dbo.[SAL_CHANGE_KBK] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[KU_ORDER_CONFIRM]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KU_ORDER_CONFIRM]

GO

/*к
© Кейсистемс (Keysystems), 2005
*/

CREATE   PROCEDURE [dbo].KU_ORDER_CONFIRM
	@LINK int,
	@Status int = 1
AS
	DECLARE @trancount int, @SQLError int, @RowCount int, @txt varchar(254), @event varchar(254), @otype int, @MSG VARCHAR(254)
	SET @trancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON
	BEGIN TRAN
	COMMIT TRAN

	SET @txt = case when @Status=1 then 'Утверждение' else 'Отмена' end + ' приказа'
	SELECT 
		@event = '№ '+rtrim(number)+' от '+convert(varchar(10), [date], 104)+' '''+rtrim(comment)+'''', @otype = type,
		@MSG = LEFT(@txt + ' ' + '№ '+rtrim(number)+' от '+convert(varchar(10), [date], 104)+' '''+rtrim(ot.name)+'''', 254)
		FROM orders O INNER JOIN dbo.ORDER_TYPES ot ON O.[TYPE] = ot.CODE WHERE link=@LINK

IF @otype NOT IN (1, 101) BEGIN
	IF @Status<>1 and exists(SELECT * FROM vacation WHERE order_link=@LINK and flag_jc=1)
	BEGIN
		ROLLBACK
		RETURN 106
	END

	IF @Status<>1 and exists(SELECT * FROM travel WHERE order_link=@LINK and flag_jc=1 )
	BEGIN
		ROLLBACK
		RETURN 106
	END

	IF @Status<>1 and exists(SELECT * from dbo.DIS_FACE_1 WHERE order_link = @LINK AND flag_jc = 1)
	BEGIN
		ROLLBACK
		RETURN 106
	END	
END

	IF @otype in (3, 103) AND @Status = 1 BEGIN
		SELECT	LINK, EMPL_LINK, DIS_DATE
		INTO	#TEMP_DIS
		FROM	ITEM_DIS_FACE WHERE ORDER_LINK = @LINK

		DECLARE @MSG_DIS VARCHAR(255)
		DECLARE @DIS_LINK INT, @DIS_EMPL_LINK INT, @DIS_DATE DATETIME
		WHILE EXISTS(SELECT * FROM #TEMP_DIS) BEGIN
			SELECT TOP 1 @DIS_LINK = LINK, @DIS_EMPL_LINK = EMPL_LINK, @DIS_DATE = DIS_DATE FROM #TEMP_DIS
			DELETE FROM #TEMP_DIS WHERE LINK = @DIS_LINK
			SET @MSG_DIS = ''
			-- проверка наличия отпуска на момент увольнения
			IF EXISTS(   
				SELECT	*
				FROM	ITEM_VACATION IV LEFT JOIN ITEM_VACATION_BREAK IVB ON IV.LINK = IVB.VAC_LINK AND IVB.ACTIVE = 1
				WHERE	IV.EMPL_LINK = @DIS_EMPL_LINK AND IV.ACTIVE = 1
						AND (@DIS_DATE < CASE WHEN ISNULL(IVB.DATE_BREAK,0) = 0 THEN IV.DATE_END
											   ELSE CASE WHEN ISNULL(IVB.LEN_KAL_DAYS,0) = 0 THEN IVB.DATE_BREAK - 1
														 ELSE DATEADD(DAY,IVB.LEN_KAL_DAYS,IV.DATE_END) 
													END 
										  END)
					) BEGIN
				SET	@MSG_DIS = 'Невозможно уволить сотрудника в период его отпуска' + CHAR(10) + CHAR(10)
				SELECT	TOP 1
						@MSG_DIS = @MSG_DIS + 'Приказ № ' + RTRIM(number) + ' от ' + CONVERT(VARCHAR(10),DATE,104) + ' г. (' + RTRIM(FIO) + ')'
				FROM	VACATION
				WHERE	EMPL_LINK = @DIS_EMPL_LINK AND ACTIVE = 1 AND @DIS_DATE <= DATE_END

				DELETE FROM #TEMP_DIS
			END
		END
		DROP TABLE #TEMP_DIS

		IF LEN(RTRIM(@MSG_DIS)) > 0 BEGIN
			RAISERROR(@MSG_DIS, 11, 1)
			ROLLBACK
			RETURN 666
		END
	
	END

	IF @otype = 24	
		IF @Status<>1 and exists(SELECT TE.LINK FROM DBO.STO_TAR_EMPL TE WHERE TE.ORDER_LINK = @LINK)
		BEGIN
			ROLLBACK
			RETURN 106
		END

	UPDATE orders SET status = @Status WHERE link=@LINK
	SELECT @SQLError = @@ERROR, @RowCount = @@ROWCOUNT
	IF @SQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
	IF @RowCount = 0
	BEGIN
		ROLLBACK
		RETURN 2
	END

	UPDATE ITEM_CHANGE_FM SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_DIS_FACE SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_ENCOUR SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_MOVE SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_ORDER_UNDO SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_TRAVEL SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_TRAVEL_LONG SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_VACATION SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_VACATION_BREAK SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_VACATION_DIS SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_ENCOUR SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_PENALTY SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_PENALTY_CANCEL SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_SUBST SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_FREE SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_WELFARE SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_COMB SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_CHANGE_OKLAD_STAFF SET active = @Status WHERE order_link=@LINK

	

	DECLARE @item_link int, @empl_link int, @date_begin datetime, @date_end datetime, @type int
	DECLARE @cur CURSOR 

	IF @otype in (4, 104, 15) and dbo.sa_get_option_by_code('TABEL_OPTIONS_OTP_AVTO_OTP') = 1 BEGIN
		SET @cur = CURSOR FAST_FORWARD FOR
			SELECT link, empl_link, date_begin, date_end, type_link FROM item_vacation WHERE order_link=@link
		OPEN @cur
		FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type
		WHILE @@fetch_status=0 BEGIN
			exec dbo.SA_SET_DAYS_IN_TABELS @empl_link, @date_begin, @date_end, @MSG
			FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type
			IF @otype IN (4,104)AND @type IN (SELECT VV.LINK FROM VACATION_VID VV INNER JOIN TYP_DAYS TD ON VV.TYPE_LINK = TD.LINK WHERE TD.WORK_D = 7) BEGIN
				UPDATE EMPL
				SET NOTWORK =	CASE WHEN @Status = 1 THEN 1
						     ELSE 0
						END
				WHERE EMPL.LINK = @empl_link
			END
		END
		CLOSE @cur
		DEALLOCATE @cur
	END

	IF @otype in (11,16) and dbo.sa_get_option_by_code('TABEL_OPTIONS_OTP_AVTO_OTP') = 1 BEGIN
		SET @cur = CURSOR FAST_FORWARD FOR
			SELECT ivb.link, ivb.empl_link, ivb.DATE_BREAK, date_end, type_link, IVB.LEN_KAL_DAYS, IVB.BREAK_WORK_DAYS FROM item_vacation iv inner join item_vacation_break ivb on ivb.vac_link = iv.link WHERE ivb.order_link=@link
		OPEN @cur
		DECLARE @BREAK_WORK_DAYS INT		-- КОЛИЧЕСТВО КАЛЕНДАРНЫХ ДНЕЙ ОТЗЫВА
		DECLARE @LEN_KAL_DAYS INT			-- КОЛИЧЕСТВО КАЛЕНДАРНЫХ ДНЕЙ ПРОДЛЕНИЯ
		FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type, @LEN_KAL_DAYS, @BREAK_WORK_DAYS
		WHILE @@fetch_status=0 BEGIN
			if @BREAK_WORK_DAYS = 0
				-- ОТЗЫВ ИЗ ОТПУСКА
				exec dbo.SA_SET_DAYS_IN_TABELS @empl_link, @date_begin, @date_end, @MSG
			else 	begin
				-- ОТЗЫВ ИЗ ОТПУСКА НА НЕСКОЛЬКО ДНЕЙ
				SET @date_end = @date_end + @LEN_KAL_DAYS
				exec dbo.SA_SET_DAYS_IN_TABELS @empl_link, @date_begin, @date_end, @MSG
			end
			FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type, @LEN_KAL_DAYS, @BREAK_WORK_DAYS
		END
		CLOSE @cur
		DEALLOCATE @cur
	END

	IF @otype in (12) and dbo.sa_get_option_by_code('TABEL_OPTIONS_OTP_AVTO_OTP') = 1 BEGIN
		SET @cur = CURSOR FAST_FORWARD FOR
			SELECT ivb.link, ivb.empl_link, iv.date_begin, ivb.NEW_DATE_END, type_link FROM item_vacation iv inner join item_vacation_dis ivb on ivb.vac_link = iv.link WHERE ivb.order_link=@link
		OPEN @cur
		FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type
		WHILE @@fetch_status=0 BEGIN
			exec dbo.SA_SET_DAYS_IN_TABELS @empl_link, @date_begin, @date_end, @MSG
			FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type
		END
		CLOSE @cur
		DEALLOCATE @cur
	END


	IF @otype in (5, 105) and dbo.sa_get_option_by_code('TABEL_OPTIONS_OTP_AVTO_COM') = 1 BEGIN
		SET @cur = CURSOR FAST_FORWARD FOR
			SELECT link, empl_link, date_begin, date_end, type_link FROM item_travel WHERE order_link=@link
		OPEN @cur
		FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type
		WHILE @@fetch_status=0 BEGIN
			exec dbo.SA_SET_DAYS_IN_TABELS @empl_link, @date_begin, @date_end, @MSG
			FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type
		END
		CLOSE @cur
		DEALLOCATE @cur
	END

	IF @otype in (13) and dbo.sa_get_option_by_code('TABEL_OPTIONS_OTP_AVTO_COM') = 1 BEGIN
		SET @cur = CURSOR FAST_FORWARD FOR
			SELECT ivb.link, ivb.empl_link, iv.date_begin, ivb.NEW_DATE_END, type_link FROM item_travel iv inner join item_travel_long ivb on ivb.TRAVEL_LINK = iv.link WHERE ivb.order_link=@link
		OPEN @cur
		FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type
		WHILE @@fetch_status=0 BEGIN
			exec dbo.SA_SET_DAYS_IN_TABELS @empl_link, @date_begin, @date_end, @MSG
			FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type
		END
		CLOSE @cur
		DEALLOCATE @cur
	END

	-- КОПИРОВАНИЕ СВЕДЕНИЙ О ПРЕДЫДУЩИХ МЕСТАХ РАБОТЫ ПРИ ВТОРИЧНОМ ПРИЕМЕ НА РАБОТУ
	IF @otype in (1,101) BEGIN
		DECLARE NEW_FAC_CUR CURSOR FOR SELECT EMPL_LINK, DATE_BEGIN FROM ITEM_MOVE WHERE ORDER_LINK = @LINK
		DECLARE @OLDWORK_LINK INT
		OPEN NEW_FAC_CUR
		FETCH NEXT FROM NEW_FAC_CUR INTO @EMPL_LINK, @DATE_BEGIN
		DECLARE @EMPL_OLDWORK TABLE(LINK INT IDENTITY(1,1),LINK_OLD INT, EMPL_LINK INT,DATE_BEGIN DATETIME,DATE_END DATETIME,DEP VARCHAR(254),PLACE VARCHAR(254),POST VARCHAR(254),REASON VARCHAR(254))
		DECLARE @EMPL_WORK TABLE(LINK INT IDENTITY(1,1), MOVE_LINK INT, EMPL_LINK INT, DATE_BEGIN DATETIME, DATE_END DATETIME, DEP VARCHAR(254), PLACE VARCHAR(254), POST VARCHAR(254), REASON VARCHAR(254))
		DECLARE @I INT, @J INT
		DECLARE @OLDWORK_NEW_LINK INT
		DECLARE @EMPL_OLD_LINK INT
		--
		DECLARE	@DEP VARCHAR(254)
		DECLARE @DATE_DIS DATETIME
		DECLARE	@OLD_LINK INT
		DECLARE	@OLD_NEW_LINK INT
		DECLARE @REAS_DIS VARCHAR(254)
		--
		SET @I = 1
		WHILE @@FETCH_STATUS = 0 BEGIN
			IF @Status = 1 and not exists(select * from empl_oldwork where empl_link = @empl_link) BEGIN
				SET @EMPL_OLD_LINK = (	SELECT	TOP 1 LINK
							FROM	KU_EMPL_PLACING
							WHERE	PERS_LINK IN (SELECT PERS_LINK FROM EMPL WHERE LINK = @EMPL_LINK)
								AND STATUS = 1
								AND LINK != @EMPL_LINK
							ORDER BY DATE_BEGIN DESC
						      )
				-- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * --
				-- занесение в предыдущие места работы сведений о предыдущих местах работы --
				-- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * --
				IF EXISTS(SELECT * FROM EMPL_OLDWORK WHERE EMPL_LINK = @EMPL_OLD_LINK AND DATE_BEGIN <= @DATE_BEGIN) BEGIN
					INSERT INTO @EMPL_OLDWORK
					SELECT LINK, EMPL_LINK,DATE_BEGIN,DATE_END,DEP,PLACE,POST,REASON FROM EMPL_OLDWORK WHERE EMPL_LINK = @EMPL_OLD_LINK AND DATE_BEGIN <= @DATE_BEGIN
					SET @J = @@IDENTITY
					WHILE @I <= @J BEGIN
						INSERT INTO EMPL_OLDWORK(EMPL_LINK,DATE_BEGIN,DATE_END,DEP,PLACE,POST,REASON)
						SELECT @EMPL_LINK,DATE_BEGIN,DATE_END,DEP,PLACE,POST,REASON FROM @EMPL_OLDWORK WHERE LINK = @I
						SET @OLDWORK_NEW_LINK = @@IDENTITY
						INSERT OLDWORK_KOEF(OLDWORK_LINK,EXPIR_LINK,KOEF)
						SELECT @OLDWORK_NEW_LINK,EXPIR_LINK,KOEF FROM OLDWORK_KOEF WHERE OLDWORK_LINK = (SELECT LINK_OLD FROM @EMPL_OLDWORK WHERE LINK = @I)
						SET @I = @I + 1
					END
				END
				-- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * --
				-- занесение в предыдущие места работы сведений о приемах и переводах в текущей организации --
				-- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * --
				IF EXISTS (SELECT * FROM DIS_FACE  WHERE EMPL_LINK = @EMPL_OLD_LINK AND ACTIVE = 1) BEGIN
					SET @DEP = (SELECT NAME FROM DEPARTMENTS WHERE LINK = (SELECT DEP_LINK FROM EMPL WHERE LINK = @EMPL_OLD_LINK))
					SELECT @DATE_DIS = dis_date, @REAS_DIS = RTRIM(reason_name) FROM DIS_FACE WHERE EMPL_LINK = @EMPL_OLD_LINK AND ACTIVE = 1
					INSERT	INTO @EMPL_WORK
					SELECT	LINK, EMPL_LINK, DATE_BEGIN, DATE_END, @DEP, '', ISNULL(POST_NAME,''), @REAS_DIS
					FROM	KU_ONLY_MOVES
					WHERE	EMPL_LINK = @EMPL_OLD_LINK
					ORDER	BY EMPL_LINK, DATE_BEGIN
					--
					UPDATE	@EMPL_WORK
					SET	DATE_END = @DATE_DIS
					WHERE	LINK = (SELECT COUNT(*) FROM @EMPL_WORK)
					--	
					SET @OLD_LINK = 1
					WHILE EXISTS(SELECT * FROM @EMPL_WORK WHERE LINK = @OLD_LINK) BEGIN
						INSERT INTO EMPL_OLDWORK(EMPL_LINK, DATE_BEGIN, DATE_END, DEP, PLACE, POST, REASON)
						SELECT @EMPL_LINK, DATE_BEGIN, DATE_END, DEP, PLACE, POST, REASON FROM @EMPL_WORK WHERE LINK = @OLD_LINK
						SET @OLD_NEW_LINK = @@IDENTITY
						INSERT OLDWORK_KOEF(OLDWORK_LINK, EXPIR_LINK, KOEF)
						SELECT @OLD_NEW_LINK, EXPIR_LINK, KOEF FROM MOVE_KOEF WHERE MOVE_LINK = (SELECT MOVE_LINK FROM @EMPL_WORK WHERE LINK = @OLD_LINK)
						SET @OLD_LINK = @OLD_LINK + 1
					END
				END
			END
			FETCH NEXT FROM NEW_FAC_CUR INTO @EMPL_LINK, @DATE_BEGIN
		END
		CLOSE NEW_FAC_CUR
		DEALLOCATE NEW_FAC_CUR
	END

	EXEC WF_GENERATEEVENT @txt, @event, null, 'ORDERS', @LINK
	IF @@TRANCOUNT > @trancount
		COMMIT TRAN
	RETURN 0





GO


GRANT EXECUTE ON dbo.[KU_ORDER_CONFIRM] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[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) 
	BEGIN
		SET @NEXT = LEFT( LEFT('0000000000', @MAX_LEN - LEN(@NEXT)) + @NEXT, 10)
	END
	ELSE 
		BEGIN 
			SELECT '111'
			IF @NEXT LIKE '%[^9]%'
			BEGIN
				SELECT '222'
				SET @NEXT = LEFT( LEFT('0000000000', LEN(@NEXT)-1 - @MAX_LEN ) + @NEXT, 10)
			END
			else 
				begin 
					SELECT '333'
					SET @NEXT = '1'
				END 
		END 
	
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.[KIR_BANK_FORMAT_SAVE_STR]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KIR_BANK_FORMAT_SAVE_STR]

GO

CREATE  PROCEDURE dbo.KIR_BANK_FORMAT_SAVE_STR
	@varKSnLink INT output,
	@varKSnLINK_PART INT,
	@varKSnLINK_FLD INT,
	@varKScCode VARCHAR(60),
	@varKSnORDERS INT,
	@varKSbIsfIXED BIT,
	@varKSnMaxLen INT,
	@varKSnDecimals INT,
	@varKSnPadType TINYINT,
	@varKScRightBorder VARCHAR(10),
	@varKScPaddingChar varchar(1),
	@varKScCODE_DBF VARCHAR(10),
	@varKScTYPE_DBF CHAR(1),
	@varKScCONST_VALUE VARCHAR(254),
	@FUNC TINYINT,
	@DOP TINYINT
AS BEGIN
	DECLARE 
		@varKSSQLError	tinyint, @varKSRowCount INT,
		@varKSstrVALUE	varchar(7000),
		@varKStrancount	int

	SET @varKStrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON

	BEGIN TRAN
	COMMIT TRAN

	
	IF EXISTS(Select * FROM S_BANK_FORMAT_PARTS WHERE CODE = @varKScCode AND LINK <> @varKSnLink)	BEGIN
		ROLLBACK
		RETURN 4
	END

	IF @varKSnLink is null OR @varKSnLink = 0 BEGIN
			INSERT INTO S_BANK_FORMAT_TABLE
				(LINK_PART, LINK_FLD, 
				CODE, ORDERS, 
				IsFixed, MaxLen, Decimals, 
				PadType, RightBorder, PaddingChar,
				CODE_DBF, TYPE_DBF, CONST_VALUE, FUNC, DOP
				)
			VALUES(
				@varKSnLINK_PART, 
				@varKSnLINK_FLD, 
				@varKScCode, 
				@varKSnORDERS, 
				ISNULL(@varKSbIsfIXED, 0),
				ISNULL(@varKSnMaxLen, 0), 
				ISNULL(@varKSnDecimals, 0),
				ISNULL(@varKSnPadType, 1),
				ISNULL(@varKScRightBorder, ''),
				ISNULL(@varKScPaddingChar, ''),
				ISNULL(@varKScCODE_DBF, ''),
				ISNULL(@varKScTYPE_DBF, 'C'),
				ISNULL(@varKScCONST_VALUE, ''),
				@FUNC,
				@DOP
			)
		SELECT @varKSSQLError = @@ERROR, @varKSnLink = @@IDENTITY
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	ELSE BEGIN
		UPDATE S_BANK_FORMAT_TABLE
		SET 
			LINK_PART = @varKSnLINK_PART, 
			LINK_FLD = @varKSnLINK_FLD, 
			CODE = @varKScCode, 
			ORDERS = @varKSnORDERS, 
			IsFixed = ISNULL(@varKSbIsfIXED, 0),
			MaxLen = ISNULL(@varKSnMaxLen, 0), 
			Decimals = ISNULL(@varKSnDecimals, 0),
			PadType = ISNULL(@varKSnPadType, 1),
			RightBorder = ISNULL(@varKScRightBorder, ''),
			PaddingChar = ISNULL(@varKScPaddingChar, ''),
			CODE_DBF = ISNULL(@varKScCODE_DBF, ''),
			TYPE_DBF = ISNULL(@varKScTYPE_DBF, 'C'),
			CONST_VALUE = ISNULL(@varKScCONST_VALUE, ''),
			FUNC = @FUNC,
			DOP = @DOP
		WHERE LINK = @varKSnLink

		SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 1
		END
	END


	
	IF @@TRANCOUNT > @varKStrancount
		COMMIT
	RETURN 0
END


GO


GRANT EXECUTE ON dbo.[KIR_BANK_FORMAT_SAVE_STR] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[scriptsFormatPayRollUser]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[scriptsFormatPayRollUser]

GO


CREATE procedure dbo.scriptsFormatPayRollUser (@format_code varchar(254))
as

declare @resStr table (id int not null identity (1,1), txt varchar(8000))

set nocount on

Set @format_code = rtrim(ltrim(@format_code))

insert into @resStr (txt)
SELECT '/*EXPORT_PAYROLL*/'

insert into @resStr (txt)
select
'-- Добавление формата выгрузки в банкомат для штатных сотрудников <<' + rtrim(ltrim([NAME])) + '>>' + CHAR(13) + CHAR(10) + replicate('-', 150) + CHAR(13) + CHAR(10)
from dbo.S_BANK_FORMATS where code = @format_code

insert into @resStr (txt)
select CHAR(13) + CHAR(10) + '-- Добавление формата '  + CHAR(13) + CHAR(10)

insert into @resStr(txt)
Select CHAR(13) + CHAR(10) +
'IF NOT EXISTS (SELECT * FROM dbo.S_BANK_FORMATS WHERE code = ''' + @format_code + ''')
BEGIN
	INSERT INTO dbo.S_BANK_FORMATS(CODE, NAME, IsUserObject, UserFilename, PRINT_OBJECT_METHOD, QUERY_ADD_MODULE, QUERY_REPMAKER, QUERY_REPORT, QUERY_REPORT_PATH, LastFileNumber, IsDefaultFormat, SumType )
	VALUES( ''' + LTRIM(RTRIM(CODE)) + ''', ' +
		'''' + LTRIM(RTRIM(NAME)) + ''', ' +
		LTRIM(RTRIM(CONVERT(VARCHAR(254),IsUserObject))) + ', ' +
		LTRIM(RTRIM(CONVERT(VARCHAR(254),UserFilename))) + ', ' +
		'''' + LTRIM(RTRIM(PRINT_OBJECT_METHOD)) + ''', ' +
		'''' + LTRIM(RTRIM(QUERY_ADD_MODULE)) + ''', ' +
		'''' + LTRIM(RTRIM(QUERY_REPMAKER)) + ''', ' +
		'''' + LTRIM(RTRIM(QUERY_REPORT)) + ''', ' +
		'''' + LTRIM(RTRIM(QUERY_REPORT_PATH)) + ''', ' + 
		+ LTRIM(RTRIM(CONVERT(VARCHAR(254),LastFileNumber))) + ', '  +
		+ LTRIM(RTRIM(CONVERT(VARCHAR(254),0))) + ', ' +
		+ LTRIM(RTRIM(CONVERT(VARCHAR(254),SumType))) + ')'+ CHAR(13) +CHAR(10) +
				'END'  + CHAR(13) + CHAR(10) + 'GO'+ CHAR(13) + CHAR(10)
FROM	dbo.S_BANK_FORMATS WHERE code = @format_code 


Declare socur cursor For 
	Select fl.LINK_FMT, fl.LINK, @format_code+ '_f' + LTRIM(RTRIM(CONVERT(VARCHAR(254),fl.ORDERS)))
		FROM dbo.S_BANK_FORMAT_FILES fl 
		where fl.LINK_FMT = COALESCE((SELECT TOP 1 LINK FROM dbo.S_BANK_FORMATS WHERE CODE = @format_code),0)

Declare @fmt_link int, @file_link int, @file_code varchar(254)
open socur
FETCH NEXT FROM socur INTO @fmt_link, @file_link, @file_code
WHILE @@FETCH_STATUS = 0
BEGIN

	insert into @resStr(txt)
	Select	CHAR(13) + CHAR(10) +
	'	IF NOT EXISTS (SELECT * FROM dbo.S_BANK_FORMAT_FILES WHERE code = ''' + @file_code +''' OR LINK_FMT IN (SELECT link FROM dbo.S_BANK_FORMATS WHERE code = ''' + @format_code + ''') AND ORDERS = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),ORDERS))) + ' )
	BEGIN 
		INSERT INTO dbo.S_BANK_FORMAT_FILES (LINK_FMT,CODE,NAME,ORDERS,TextCodePage,FileType,FileNameShablon)
		SELECT	' + 
			'(SELECT link FROM dbo.S_BANK_FORMATS WHERE code = ''' + @format_code + '''), ' +
			'''' + LTRIM(RTRIM(CONVERT(VARCHAR(254),@file_code))) + ''', ' +
			'''' + LTRIM(RTRIM(NAME)) + ''', ' +
			LTRIM(RTRIM(CONVERT(VARCHAR(254),ORDERS))) + ', ' +
			LTRIM(RTRIM(CONVERT(VARCHAR(254),TextCodePage))) + ', ' +
			LTRIM(RTRIM(CONVERT(VARCHAR(254),FileType))) + ', ' +
			'''' + LTRIM(RTRIM(FileNameShablon)) + ''''  + CHAR(13) +CHAR(10) +
				'	END
	ELSE BEGIN
		UPDATE dbo.S_BANK_FORMAT_FILES
		SET LINK_FMT = (SELECT link FROM dbo.S_BANK_FORMATS WHERE code = ''' + @format_code + '''),
			CODE = ''' + LTRIM(RTRIM(CONVERT(VARCHAR(254),@file_code))) + ''',
			NAME = ''' + LTRIM(RTRIM(NAME)) + ''',
			ORDERS = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),ORDERS))) + ',
			TextCodePage = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),TextCodePage))) + ',
			FileType = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),FileType))) + ',
			FileNameShablon = ''' + LTRIM(RTRIM(FileNameShablon)) + ''',
			GRP_EKR = ' + LTRIM(RTRIM(CONVERT(VARCHAR(3),GRP_EKR))) + '
		WHERE CODE = ''' + @file_code +''' OR LINK_FMT IN (SELECT link FROM dbo.S_BANK_FORMATS WHERE code = ''' + @format_code + ''') AND ORDERS = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),ORDERS))) + ' 
		
	END'   + CHAR(13) + CHAR(10) + 'GO'+ CHAR(13) + CHAR(10)
FROM	dbo.S_BANK_FORMAT_FILES WHERE LINK = @file_link

	Declare socur1 cursor For Select prt.link, @file_code + '_p' + LTRIM(RTRIM(CONVERT(VARCHAR(254),prt.ORDERS)))  FROM dbo.S_BANK_FORMAT_PARTS prt where prt.LINK_FILE = @file_link

	Declare @link_part int, @part_code varchar(254)
	open socur1
	FETCH NEXT FROM socur1 INTO @link_part, @part_code
	WHILE @@FETCH_STATUS = 0
	BEGIN

		insert into @resStr(txt)
		Select	CHAR(13) + CHAR(10) +
		'		IF NOT EXISTS (SELECT * FROM dbo.S_BANK_FORMAT_PARTS prt where code = ''' + @part_code +''' OR LINK_FILE IN (SELECT LINK FROM dbo.S_BANK_FORMAT_FILES WHERE CODE = ''' + @file_code + ''') AND ORDERS = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),ORDERS))) + '  )
		BEGIN 
			INSERT INTO dbo.S_BANK_FORMAT_PARTS (LINK_FILE,ORDERS,CODE,NAME,DELIM_STR,DELIM_USED,DATEFMT, CENTFORMAT,FLOATFMT,ONE_ROW)
			SELECT  ' + 
				'(SELECT LINK FROM dbo.S_BANK_FORMAT_FILES f WHERE CODE = ''' + @file_code + '''), ' + 
				LTRIM(RTRIM(CONVERT(VARCHAR(254),ORDERS))) + ', ' +
				'''' + LTRIM(RTRIM(@part_code)) + ''', ' +
				'''' + LTRIM(RTRIM(NAME)) + ''', ' +
				'''' + LTRIM(RTRIM(DELIM_STR)) + ''', ' +			
				LTRIM(RTRIM(CONVERT(VARCHAR(254),DELIM_USED))) + ', ' +
				LTRIM(RTRIM(CONVERT(VARCHAR(254),DATEFMT))) + ', ' +
				LTRIM(RTRIM(CONVERT(VARCHAR(254),CENTFORMAT))) + ', ' +
				LTRIM(RTRIM(CONVERT(VARCHAR(254),FLOATFMT))) + ', ' +
				LTRIM(RTRIM(CONVERT(VARCHAR(254),ONE_ROW))) + CHAR(13) + CHAR(10) +
				'		END
			ELSE BEGIN
				UPDATE dbo.S_BANK_FORMAT_PARTS
				SET LINK_FILE = (SELECT LINK FROM dbo.S_BANK_FORMAT_FILES f WHERE CODE = ''' + @file_code + '''),
					ORDERS = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),ORDERS))) + ',
					CODE = ''' + LTRIM(RTRIM(@part_code)) + ''',
					NAME = ''' + LTRIM(RTRIM(NAME)) + ''',
					DELIM_STR = ''' + LTRIM(RTRIM(DELIM_STR)) + ''',
					DELIM_USED = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),DELIM_USED))) + ',
					DATEFMT = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),DATEFMT))) + ',
					CENTFORMAT = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),CENTFORMAT))) + ',
					FLOATFMT = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),FLOATFMT))) + ',
					ONE_ROW = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),ONE_ROW))) + '
				WHERE CODE = ''' + @part_code +''' OR LINK_FILE IN (SELECT LINK FROM dbo.S_BANK_FORMAT_FILES WHERE CODE = ''' + @file_code + ''') AND ORDERS = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),ORDERS))) + '
			
			END
			'   + CHAR(13) + CHAR(10) + 'GO'+ CHAR(13) + CHAR(10)

			FROM dbo.S_BANK_FORMAT_PARTS prt where prt.LINK = @link_part


			Declare socur2 cursor For Select s.link, @part_code + '_s' + LTRIM(RTRIM(CONVERT(VARCHAR(254),s.ORDERS)))  FROM dbo.S_BANK_FORMAT_TABLE s where s.LINK_PART = @link_part
	
			Declare @link_s int, @s_code varchar(254)
			open socur2
			FETCH NEXT FROM socur2 INTO @link_s, @s_code
			WHILE @@FETCH_STATUS = 0
			BEGIN
				insert into @resStr(txt)
				Select	CHAR(13) + CHAR(10) +
				'			IF NOT EXISTS (SELECT * FROM dbo.S_BANK_FORMAT_TABLE s where s.code = ''' + @s_code +''' OR LINK_PART IN (SELECT LINK FROM dbo.S_BANK_FORMAT_PARTS WHERE CODE = ''' + @part_code + ''') AND ORDERS = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),ORDERS))) + '  )
				BEGIN 
					INSERT INTO dbo.S_BANK_FORMAT_TABLE (LINK_PART,LINK_FLD,CODE,ORDERS,IsFixed,MaxLen,Decimals,PadType,RightBorder,PaddingChar,CODE_DBF,TYPE_DBF,CONST_VALUE,FUNC,DOP)
					SELECT  ' + 
						'(SELECT LINK FROM dbo.S_BANK_FORMAT_PARTS prt WHERE CODE = ''' + @part_code + '''), ' + 
						'(SELECT LINK FROM dbo.S_BANK_FORMAT_BASE WHERE CODE = ''' + (select rtrim(ltrim(code)) from dbo.S_BANK_FORMAT_BASE where link = LINK_FLD) + '''), ' + 
						'''' + LTRIM(RTRIM(@s_code)) + ''', ' +
						LTRIM(RTRIM(CONVERT(VARCHAR(254),ORDERS))) + ', ' +
						LTRIM(RTRIM(CONVERT(VARCHAR(254),IsFixed))) + ', ' +
						LTRIM(RTRIM(CONVERT(VARCHAR(254),MaxLen))) + ', ' +
						LTRIM(RTRIM(CONVERT(VARCHAR(254),Decimals))) + ', ' +
						LTRIM(RTRIM(CONVERT(VARCHAR(254),PadType))) + ', ' +
						'''' + LTRIM(RTRIM(RightBorder)) + ''', ' +
						'''' + LTRIM(RTRIM(PaddingChar)) + ''', ' +
						'''' + LTRIM(RTRIM(CODE_DBF)) + ''', ' +
						'''' + LTRIM(RTRIM(TYPE_DBF)) + ''', ' +
						'''' + LTRIM(RTRIM(CONST_VALUE)) + ''', ' +
						LTRIM(RTRIM(CONVERT(VARCHAR(254),ISNULL(FUNC,0)))) + ', ' +
						LTRIM(RTRIM(CONVERT(VARCHAR(254),ISNULL(DOP,0)))) +  CHAR(13) +CHAR(10) + 
	'			END
				ELSE BEGIN
					UPDATE dbo.S_BANK_FORMAT_TABLE
					SET LINK_PART = (SELECT LINK FROM dbo.S_BANK_FORMAT_PARTS prt WHERE CODE = ''' + @part_code + '''),
						LINK_FLD = (SELECT LINK FROM dbo.S_BANK_FORMAT_BASE WHERE CODE = ''' + (select rtrim(ltrim(code)) from dbo.S_BANK_FORMAT_BASE where link = LINK_FLD) + '''),
						CODE = ''' + LTRIM(RTRIM(@s_code)) + ''',
						ORDERS = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),ORDERS))) + ',
						IsFixed = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),IsFixed))) + ',
						MaxLen = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),MaxLen))) + ',
						Decimals = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),Decimals))) + ',
						PadType = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),PadType))) + ',
						RightBorder = ''' + LTRIM(RTRIM(RightBorder)) + ''',
						PaddingChar = ''' + LTRIM(RTRIM(PaddingChar)) + ''',
						CODE_DBF = ''' + LTRIM(RTRIM(CODE_DBF)) + ''',
						TYPE_DBF = ''' + LTRIM(RTRIM(TYPE_DBF)) + ''',
						CONST_VALUE = ''' + LTRIM(RTRIM(CONST_VALUE)) + ''',
						FUNC =' + LTRIM(RTRIM(CONVERT(VARCHAR(254),ISNULL(FUNC,0)))) + ',
						DOP =' + LTRIM(RTRIM(CONVERT(VARCHAR(254),ISNULL(DOP,0)))) + ' 
					WHERE CODE = ''' + @s_code +''' OR LINK_PART IN (SELECT LINK FROM dbo.S_BANK_FORMAT_PARTS WHERE CODE = ''' + @part_code + ''') AND ORDERS = ' + LTRIM(RTRIM(CONVERT(VARCHAR(254),ORDERS))) + ' 
				END
				'   + CHAR(13) + CHAR(10) + 'GO'+ CHAR(13) + CHAR(10)
				FROM dbo.S_BANK_FORMAT_TABLE s where s.LINK = @link_s
				
				FETCH NEXT FROM socur2 INTO @link_s, @s_code
			END
			close socur2
			deallocate socur2

		FETCH NEXT FROM socur1 INTO @link_part, @part_code
	END
	close socur1
	deallocate socur1

	FETCH NEXT FROM socur INTO @fmt_link, @file_link, @file_code
END
close socur
deallocate socur

Select txt from @resStr order by id

set nocount off

RETURN 






GO


GRANT EXECUTE ON dbo.[scriptsFormatPayRollUser] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SZV_K_STAZH_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZV_K_STAZH_SAVE]

GO


------------------------------------------------------------------------
CREATE   PROCEDURE dbo.SA_SZV_K_STAZH_SAVE
	@link		int output,
	@link_up	int,
	@orders		int,
	@date1		datetime,
	@date2		datetime,
	@ter_usl	varchar(10) = '',
	@ter_koef	numeric(18,2),
	@osob_usl	varchar(10) = '',
	@osob_k1	varchar(20) = '',
	@osob_k2	varchar(20) = '',
	@osob_k3	varchar(20) = '',
	@post		varchar(254) = '',
	@is_osnov	varchar(10) = '',
	@is_dop		varchar(20) = '',
	@is_dop_m	tinyint,
	@is_dop_d	tinyint,
	@ud_osnov	varchar(10) = '',
	@ud_dop_m	int,
	@ud_dop_d	int,
	@ud_dop_k	numeric(18,2)
AS
DECLARE @varKSERROR	tinyint, @varKSstrVALUE	 varchar(7000), @varKStrancount	 int, @varKSRowCount INT, @varKSsoLink int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

IF coalesce(@link_up,0) = 0 or @date1 is null or @date2 is null or coalesce(@post,'') = ''
BEGIN
	ROLLBACK
	RETURN 5
END

IF exists (select * from dbo.SZV_K_STAZH where link <> @link and link_up = @link_up and (@date1 between date1 and coalesce(date2,'20990101') 
										or coalesce(@date2,'20990101') between date1 and coalesce(date2,'20990101') ))
BEGIN
	ROLLBACK
	RETURN 2003
END

SELECT @varKSsoLink = LINK FROM s_objects  WHERE CODE = 'SA_SZV_K_STAZH_OSN'

IF @LINK is null OR @LINK = 0
	BEGIN
		INSERT INTO dbo.SZV_K_STAZH WITH (ROWLOCK) (link_up, orders, date1, date2, ter_usl, ter_koef, osob_usl, osob_k1, osob_k2, osob_k3, post,
								is_osnov, is_dop, is_dop_m, is_dop_d, ud_osnov, ud_dop_m, ud_dop_d, ud_dop_k)
			VALUES (@link_up, @orders, @date1, @date2, RTRIM(LTRIM(@ter_usl)), @ter_koef, RTRIM(LTRIM(@osob_usl)), RTRIM(LTRIM(@osob_k1)), 
								RTRIM(LTRIM(@osob_k2)), RTRIM(LTRIM(@osob_k3)),RTRIM(LTRIM(@post)), RTRIM(LTRIM(@is_osnov)), RTRIM(LTRIM(@is_dop)), 
								@is_dop_m, @is_dop_d, RTRIM(LTRIM(@ud_osnov)), @ud_dop_m, @ud_dop_d, @ud_dop_k)

		SELECT @varKSERROR = @@ERROR, @LINK = @@IDENTITY
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
ELSE
	BEGIN
		UPDATE dbo.SZV_K_STAZH WITH (ROWLOCK) 
		SET 	link_up =@link_up, orders =@orders, date1 =@date1, date2 =@date2, 
			ter_usl = RTRIM(LTRIM(@ter_usl)), ter_koef = @ter_koef, osob_usl = RTRIM(LTRIM(@osob_usl)), 
			osob_k1 = RTRIM(LTRIM(@osob_k1)), osob_k2 = RTRIM(LTRIM(@osob_k2)), osob_k3 = RTRIM(LTRIM(@osob_k3)), post = RTRIM(LTRIM(@post)),
			is_osnov = RTRIM(LTRIM(@is_osnov)), is_dop = RTRIM(LTRIM(@is_dop)), is_dop_m = @is_dop_m, 
			is_dop_d = @is_dop_d, ud_osnov = RTRIM(LTRIM(@ud_osnov)), ud_dop_m = @ud_dop_m, ud_dop_d = @ud_dop_d, ud_dop_k = @ud_dop_k

		WHERE LINK = @LINK

		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END

/*Правильная сортировка*/
declare @uslovie int
set @uslovie = 1

update SZV_K_STAZH set orders = 0 where link_up = @link_up

while @uslovie > 0
begin
	update SZV_K_STAZH set orders = @uslovie 
	from SZV_K_STAZH as tt
	where 	
		link_up = @link_up
		and coalesce(orders,0) = 0
		and date1 = (select min(t.date1) from SZV_K_STAZH t where coalesce(orders,0) = 0 and link_up = @link_up)

	if @@rowcount > 0
		set @uslovie = @uslovie + 1
	else
		set @uslovie = 0
end


declare @varKSEventText varchar(200)

Select  @varKSEventText = 'Основная запись о стаже по физлицу ' + RTRIM(LTRIM(s.FIO)) + ', в организации' + RTRIM(LTRIM(sv.NAME_DEP)) 
	from dbo.SA_SZV_K_SVEDENIA  s 
		INNER join dbo.sa_szv_k_sved_work_dep sv ON s.link1 = sv.link 
	WHERE sv.link1 = @LINK_UP

EXECUTE WF_GENERATEEVENT 'Сохранение расчета', @varKSEventText, @varKSsoLink, 'SA_SZV_K_STAZH_OSN',@LINK
WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN

RETURN 0





GO


GRANT EXECUTE ON dbo.[SA_SZV_K_STAZH_SAVE] TO PUBLIC

GO




GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SZV_K_STAZH_DOP_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZV_K_STAZH_DOP_SAVE]

GO


------------------------------------------------------------------------
CREATE   PROCEDURE dbo.SA_SZV_K_STAZH_DOP_SAVE
	@link		int output,
	@link_up	int,
	@orders		int,
	@date1		datetime,
	@date2		datetime,
	@ter_usl	varchar(10) = '',
	@ter_koef	numeric(18,2),
	@osob_usl	varchar(10) = '',
	@osob_k1	varchar(20) = '',
	@osob_k2	varchar(20) = '',
	@osob_k3	varchar(20) = '',
	@post		VARCHAR(254) = '',
	@is_osnov	varchar(10) = '',
	@is_dop		varchar(20) = '',
	@is_dop_m	tinyint,
	@is_dop_d	tinyint,
	@ud_osnov	varchar(10) = '',
	@ud_dop_m	int,
	@ud_dop_d	int,
	@ud_dop_k	numeric(18,2)
AS
DECLARE @varKSERROR	tinyint, @varKSstrVALUE	 varchar(7000), @varKStrancount	 int, @varKSRowCount INT, @varKSsoLink int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

IF coalesce(@link_up,0) = 0 or @date1 is null or @date2 is null or coalesce(@post,'') = ''
BEGIN
	ROLLBACK
	RETURN 5
END

SELECT @varKSsoLink = LINK FROM s_objects  WHERE CODE = 'SA_SZV_K_STAZH_DOP'

IF @LINK is null OR @LINK = 0
	BEGIN
		INSERT INTO dbo.SZV_K_STAZH_DOP WITH (ROWLOCK) (link_up, orders, date1, date2, ter_usl, ter_koef, osob_usl, osob_k1, osob_k2, osob_k3, post,
								is_osnov, is_dop, is_dop_m, is_dop_d, ud_osnov, ud_dop_m, ud_dop_d, ud_dop_k)
			VALUES (@link_up, @orders, @date1, @date2, RTRIM(LTRIM(@ter_usl)), @ter_koef, RTRIM(LTRIM(@osob_usl)), RTRIM(LTRIM(@osob_k1)), 
								RTRIM(LTRIM(@osob_k2)), RTRIM(LTRIM(@osob_k3)),RTRIM(LTRIM(@post)), RTRIM(LTRIM(@is_osnov)), RTRIM(LTRIM(@is_dop)), 
								@is_dop_m, @is_dop_d, RTRIM(LTRIM(@ud_osnov)), @ud_dop_m, @ud_dop_d, @ud_dop_k)

		SELECT @varKSERROR = @@ERROR, @LINK = @@IDENTITY
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
ELSE
	BEGIN
		UPDATE dbo.SZV_K_STAZH_DOP WITH (ROWLOCK) 
		SET 	link_up =@link_up, orders =@orders, date1 =@date1, date2 =@date2, 
			ter_usl = RTRIM(LTRIM(@ter_usl)), ter_koef = @ter_koef, osob_usl = RTRIM(LTRIM(@osob_usl)), 
			osob_k1 = RTRIM(LTRIM(@osob_k1)), osob_k2 = RTRIM(LTRIM(@osob_k2)), osob_k3 = RTRIM(LTRIM(@osob_k3)), post = RTRIM(LTRIM(@post)),
			is_osnov = RTRIM(LTRIM(@is_osnov)), is_dop = RTRIM(LTRIM(@is_dop)), is_dop_m = @is_dop_m, 
			is_dop_d = @is_dop_d, ud_osnov = RTRIM(LTRIM(@ud_osnov)), ud_dop_m = @ud_dop_m, ud_dop_d = @ud_dop_d, ud_dop_k = @ud_dop_k

		WHERE LINK = @LINK

		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END

/*Правильная сортировка*/
declare @uslovie int
set @uslovie = 1

update SZV_K_STAZH_DOP set orders = 0 where link_up = @link_up

while @uslovie > 0
begin
	update SZV_K_STAZH_DOP set orders = @uslovie 
	from SZV_K_STAZH_DOP as tt
	where 	
		link_up = @link_up
		and coalesce(orders,0) = 0
		and link = (select min(t.link) from SZV_K_STAZH_DOP t where coalesce(orders,0) = 0 and link_up = @link_up)

	if @@rowcount > 0
		set @uslovie = @uslovie + 1
	else
		set @uslovie = 0
end


declare @varKSEventText varchar(200)

Select  @varKSEventText = 'Дополнительная запись о льготном стаже по физлицу ' + RTRIM(LTRIM(s.FIO)) + ', в организации' + RTRIM(LTRIM(sv.NAME_DEP)) 
	from dbo.SA_SZV_K_SVEDENIA  s 
		INNER join dbo.sa_szv_k_sved_work_dep sv ON s.link1 = sv.link 
		INNER join dbo.sa_szv_k_stazh st ON sv.link1 = st.link 
	WHERE st.link1 = @LINK_UP

EXECUTE WF_GENERATEEVENT 'Сохранение расчета', @varKSEventText, @varKSsoLink, 'SA_SZV_K_STAZH_DOP',@LINK
WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN

RETURN 0






GO


GRANT EXECUTE ON dbo.[SA_SZV_K_STAZH_DOP_SAVE] TO PUBLIC

GO



GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RN_GET_DEFAULT_DEP_LINK]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RN_GET_DEFAULT_DEP_LINK]

GO

CREATE      PROCEDURE dbo.RN_GET_DEFAULT_DEP_LINK
	@varKSLINK int OUTPUT
AS
SELECT TOP 1 @varKSLINK = LINK
  FROM DICTIONARY_DEPARTMENT WHERE (ZB = 1 or type = 4 or link in (select link_org from report_svod_tree where link_org is not null)) and dbo.RN_ACCESS_ONLY_ORG(link)=1

RETURN @@ROWCOUNT


GO


GRANT EXECUTE ON dbo.[RN_GET_DEFAULT_DEP_LINK] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SZV_K_OPT1_CHECK]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZV_K_OPT1_CHECK]

GO

CREATE procedure dbo.SA_SZV_K_OPT1_CHECK 
/*
Проверка корректности настройки с кодом SA_SZV_K_OPT1
*/
as

---Если там строка, то заменить на значение по умолчанию
IF EXISTS (
SELECT VALUE, ISNUMERIC(VALUE)
FROM S_OPTIONS WHERE OBJECT = 	
(SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SA_SZV_K_OPT1'))) 
AND SID IS NULL
AND ISNUMERIC(VALUE) = 0
)

	UPDATE S_OPTIONS
	SET VALUE = 200
	WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SA_SZV_K_OPT1'))) 
	AND SID IS NULL

---Если там значение слишком большое, то заменить на значение по умолчанию

IF EXISTS (
SELECT VALUE, ISNUMERIC(VALUE)
FROM S_OPTIONS WHERE OBJECT = 	
(SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SA_SZV_K_OPT1'))) 
AND SID IS NULL
AND ISNUMERIC(VALUE) = 1
AND LEN(VALUE)> 5
)

	UPDATE S_OPTIONS
	SET VALUE = 200
	WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SA_SZV_K_OPT1'))) 
	AND SID IS NULL


--- Если значение больше чем INT, то заменить на значение по умолчанию
IF dbo.sa_get_option_by_code('SA_SZV_K_OPT1') > 32000
	UPDATE S_OPTIONS
	SET VALUE = 200
	WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SA_SZV_K_OPT1'))) 
	AND SID IS NULL

RETURN 0



GO


GRANT EXECUTE ON dbo.[SA_SZV_K_OPT1_CHECK] TO PUBLIC

GO


GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BV_MAKE_INV_DOCUMENTS]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BV_MAKE_INV_DOCUMENTS]

GO


/*
© Кейсистемс (Keysystems), 2005
*/

CREATE	PROCEDURE dbo.BV_MAKE_INV_DOCUMENTS
	@varKSnLINK_DOC INT,
	@varKSnLINK_TYP INT,
	@varKScBufferName CHAR(100),
	@varKSnDEL	TINYINT = 1 /* 1- Добавить к старым записям; 2 - Удалить старые записи */	

AS

DECLARE
	@cTypeDoc CHAR(100),
	@varKSpLINK	INT,
	@varKSpLINK_UP	INT,
	@varKSpORDERS	INT,
	@varKSpINV_LINK INT,
	@varKSpGRP_CODE CHAR(7),
	@varKSpSOU_LINK INT,
	@varKSpBALANCE  NUMERIC(12,2),
	@varKSpDEPRE_SUM NUMERIC(12,2),
	@varKSpLAST_COST NUMERIC(12,2),
	@varKSpQTY	NUMERIC(12,4),
	@varKSpACC_CODE	VARCHAR(13),
	@varKSpDEPRE_CODE VARCHAR(13),
	@varKSpNOTICE	VARCHAR(60), 
	
	@ACCOUNT	INT,
	@ACCOUNT_AM	INT,
	
	@varKSdWorkDate DATETIME

SELECT @varKSdWorkDate = WORKDATE + 1 FROM USER_INFO

DECLARE @DEPRE_TABLE TABLE
	(
	[DEPRE_SUM] [NUMERIC] (20,2),
	[INV] INT
	)
INSERT INTO @DEPRE_TABLE
SELECT SUM(ART.K_SUMMA),
	ART.INV
FROM dbo.ARestGroupedTableByBufferConditions(@varKSdWorkDate, DEFAULT, 0x40, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, @varKScBufferName, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT) ART
INNER JOIN dbo.S_ACCOUNTS SA ON (SA.cSinth = '104'
	AND SA.LINK = ART.ACCOUNT)
GROUP BY ART.INV
HAVING SUM(ART.K_SUMMA) <> 0

DECLARE INV_CUR CURSOR LOCAL STATIC READ_ONLY FOR 

SELECT
	[INV_LINK] = BUF.LINK,
	[GRP_CODE] = GI.CODE,
	[SOU_LINK] = DFS.LINK,
	[BALANCE] = CASE WHEN SA1.CODE IS NULL THEN INV.COST ELSE ISNULL(ART.D_SUMMA,0) END,
	[DEPRE_SUM] =  CASE WHEN SA2.CODE IS NULL THEN ISNULL((SELECT DEPRE_SUM FROM ASSETS WHERE LINK_UP = INV.LINK),0) ELSE ISNULL(DT.DEPRE_SUM,0) END,
	[QTY] = CASE WHEN SA1.CODE IS NULL THEN 1 ELSE CASE WHEN ART.D_QUANTITY IS NULL OR ART.D_QUANTITY = 0 THEN 1 ELSE ISNULL(ART.D_QUANTITY,1) END END,
	[ACC_CODE] = ISNULL (SA11.CODE, SA_BAL_G.CODE),
	[DEPRE_CODE] = ISNULL (SA2.CODE, SA_AM_G.CODE)
FROM dbo.BufferGetTableByID(@varKScBufferName) BUF
INNER JOIN dbo.INVENTORY INV ON (INV.LINK = BUF.LINK)
INNER JOIN dbo.NOMENCLATURE N ON (N.LINK = INV.NOMENCLATURE)
INNER JOIN dbo.GROUP_INV GI ON (GI.LINK = N.GROUP_INV)
LEFT JOIN dbo.S_ACCOUNTS SA_BAL_G ON (SA_BAL_G.LINK = GI.ACCOUNT)
LEFT JOIN dbo.S_ACCOUNTS SA_AM_G ON (SA_AM_G.LINK = GI.ACCOUNT_AM)
LEFT OUTER JOIN dbo.ARestGroupedTableByConditions(@varKSdWorkDate, DEFAULT, 0x40, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT) ART ON (ART.INV = BUF.LINK)
LEFT OUTER JOIN dbo.S_ACCOUNTS SA1 ON (SA1.LINK = ART.ACCOUNT)
LEFT OUTER JOIN dbo.S_ACCOUNTS SA11 ON
	(SA1.cSINTH <> '106'
		AND SA11.LINK = SA1.LINK
	OR SA1.cSINTH = '106'
		AND SA11.cSource = SA1.cSource
		AND SA11.cSinth = SA_BAL_G.cSINTH
		AND SA11.cAnalit = SA_BAL_G.cAnalit 
		AND (SA11.cUser = SA1.cUser
			OR SA11.cUser = ''
				AND dbo.AccountsHasNoChild (SA11.LINK) = 1
			)
		)
LEFT OUTER JOIN dbo.FIN_SOURCE DFS ON (DFS.CODE = SA1.cSource)
LEFT OUTER JOIN S_ACCOUNTS SA2 ON (SA2.cSource = SA1.cSource
	AND SA2.cSinth = SA_AM_G.cSINTH
	AND SA2.cAnalit = SA_AM_G.cAnalit 
	AND (SA2.cUser = SA1.cUser OR SA2.cUser = ''
	AND dbo.AccountsHasNoChild (SA2.LINK) = 1))
LEFT JOIN  @DEPRE_TABLE DT ON (DT.INV = BUF.LINK)
WHERE ISNULL(ART.D_SUMMA, 1) > 0
	AND (SA1.CODE IS NULL OR SA1.S_ACTIVE = 1 AND SA1.S_PASSIVE = 0 AND SA1.cSinth <> '104')
---


-- Begin

IF @varKSnDEL = 2
  BEGIN
	DELETE FROM OUT_TABLE_ROW WHERE LINK_UP = @varKSnLINK_DOC AND OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOC_INVENT_TABLE_70N')
	DELETE FROM G_PROV1 WHERE LINK_UP = @varKSnLINK_DOC
  END

-- Анализ документа (код в S_OBJECTS)
SELECT @cTypeDoc = SO.CODE 
FROM G_PROV G, S_OBJECTS SO
WHERE G.LINK  = @varKSnLINK_DOC AND SO.LINK = G.OBJECT

SELECT @varKSpLINK = 0, @varKSpLINK_UP = @varKSnLINK_DOC
SELECT @varKSpORDERS = MAX(ORDERS) FROM DOC_INVENT_TABLE_70N
SET @varKSpORDERS = ISNULL(@varKSpORDERS ,0)

OPEN INV_CUR
FETCH NEXT FROM INV_CUR INTO @varKSpINV_LINK, @varKSpGRP_CODE, @varKSpSOU_LINK, @varKSpBALANCE, @varKSpDEPRE_SUM, @varKSpQTY, @varKSpACC_CODE, @varKSpDEPRE_CODE
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @varKSpLAST_COST = ISNULL(@varKSpBALANCE,0) - ISNULL(@varKSpDEPRE_SUM,0)
	SET @varKSpLINK = 0
	SET @varKSpORDERS = @varKSpORDERS + 1

	IF @varKSpQTY = 0
		SET @varKSpQTY = 1

	SELECT TOP 1
		@ACCOUNT = LINK
	FROM dbo.S_ACCOUNTS
	WHERE CODE = @varKSpACC_CODE
	
	SELECT TOP 1
		@ACCOUNT_AM = LINK
	FROM dbo.S_ACCOUNTS
	WHERE CODE = @varKSpDEPRE_CODE 

	EXECUTE dbo.BK_SAVE_DOC_TABLE_NFA @varKSpLINK OUTPUT, @varKSpLINK_UP, @varKSpORDERS,
				'INVENTORY_CARD', @varKSpINV_LINK,
				@varKSpBALANCE, @varKSpDEPRE_SUM, @varKSpQTY,
				@ACCOUNT, @ACCOUNT_AM, @varKSpSOU_LINK,
				@varKSpNOTICE

	print @varKSpLINK
	print @varKSpINV_LINK
	PRINT 'Линк записи: ' + str(isnull(@varKSpLINK,0)) + ', линк ОС: ' + str(isnull(@varKSpINV_LINK,0))

	FETCH NEXT FROM INV_CUR INTO @varKSpINV_LINK, @varKSpGRP_CODE, @varKSpSOU_LINK, @varKSpBALANCE, @varKSpDEPRE_SUM, @varKSpQTY, @varKSpACC_CODE, @varKSpDEPRE_CODE
END

CLOSE INV_CUR
DEALLOCATE INV_CUR

-- End

EXECUTE dbo.BufferClear @varKScBufferName

EXEC X_SALDO_COMMITCHANGES	

RETURN 0






GO


GRANT EXECUTE ON dbo.[BV_MAKE_INV_DOCUMENTS] 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

	SELECT @intLINK_DOC = LINK,
		@intDEP_LINK = DEP 
	FROM dbo.G_PROV WITH (NOLOCK)
	WHERE LINK = @intLINK_DOC

	IF @@ROWCOUNT = 0
	BEGIN
		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
		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

	RETURN 0
END


GO


GRANT EXECUTE ON dbo.[BK_FILL_COMISSION_IN_DOC] TO PUBLIC

GO



GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BV_SAVE_G_PROV1_OS2_OS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BV_SAVE_G_PROV1_OS2_OS]
GO

CREATE	PROCEDURE dbo.BV_SAVE_G_PROV1_OS2_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,
	@varKScErrTxt VARCHAR(60),
	@varKScACC_CODE VARCHAR(13),
	@varKSnACC_LINK INT,
	@strSOU_CODE	VARCHAR (1),
	@varKScDEP_ACC_CODE VARCHAR(13),
	@varKSnDEP_ACC_LINK INT,
	@strINV_TYPE	VARCHAR (30)

DECLARE GRID_CUR CURSOR LOCAL STATIC READ_ONLY FOR

	SELECT INV_TYPE, INV_LINK, INV_CODE, BALANCE, DEPRE_SUM, QTY, ACC_CODE, DEPRE_CODE, SOU_CODE
	FROM dbo.BK_DOC_TABLE_NFA_FN (@varKSnLINK_DOC)
	WHERE LINK_UP = @varKSnLINK_DOC
		AND (LAST_COST <> 0 OR DEPRE_SUM <> 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 TOP 1 @varKSnTYP_LINK = TYP_LINK FROM DOC_OS2_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,
	@varKScACC_CODE, @varKScDEP_ACC_CODE, @strSOU_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
*/
-- Временное решение, к версии поля суммы и амортизации не расчитывать, а хранить
-- Вычисляем линки счетов
		SELECT TOP 1 @varKSnACC_LINK = LINK FROM S_ACCOUNTS WHERE CODE = @varKScACC_CODE
		SELECT TOP 1 @varKSnDEP_ACC_LINK = LINK FROM S_ACCOUNTS WHERE CODE = @varKScDEP_ACC_CODE

/*
		IF @varKSnSUMMA1 <> ROUND(@varKSnSUMMA1,0)
			SELECT TOP 1 @varKSnSUMMA1 = SUM(ART.D_SUMMA)
			FROM dbo.ARestTableByConditions(@varKSdCALC_DATE, @varKSnACC_LINK, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, @varKSnLINK_OS, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT) ART
			GROUP BY ART.DEP_LINK, ART.EMP
			HAVING ABS(SUM(ART.D_SUMMA) - (@varKSnSUMMA1 * @varKSnQTY)) < 1
		ELSE
			SET @varKSnSUMMA1 = @varKSnSUMMA1 * @varKSnQTY

		IF @varKSnSUMMA2 <> ROUND(@varKSnSUMMA2,0)
			SELECT TOP 1 @varKSnSUMMA2 = SUM(ART.K_SUMMA)
			FROM dbo.ARestTableByConditions(@varKSdCALC_DATE, @varKSnDEP_ACC_LINK, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, @varKSnLINK_OS, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT) ART
			GROUP BY ART.DEP_LINK, ART.EMP
			HAVING ABS(SUM(ART.K_SUMMA) - (@varKSnSUMMA2 * @varKSnQTY)) < 1
		ELSE
			SET @varKSnSUMMA2 = @varKSnSUMMA2 * @varKSnQTY
*/
	  END

/*	ELSE -- Для кол-ва = 1 ничего не делаем
	  BEGIN
		SET @varKSnSUMMA1 = 0
		SET @varKSnSUMMA2 = 0
	  END
*/

	SET @varKScNAME_OPER_OS = RTRIM(ISNULL(@varKScNAME_OPER, 'Операция'))
		+ CASE
			WHEN @strINV_TYPE = 'BV_NOMENCLATURE' THEN ' Номен.№ - '
			WHEN @strINV_TYPE = 'INVENTORY_CARD' THEN ' Инв.№ - '
			ELSE ' № - '
		END
		+ RTRIM(@varKScCODE_OS) 

--select @strINV_TYPE, @varKScNAME_OPER_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,
				@strSOU_CODE, 
				@strINV_TYPE
				

	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,
		@varKScACC_CODE, @varKScDEP_ACC_CODE, @strSOU_CODE
END

CLOSE GRID_CUR
DEALLOCATE GRID_CUR

EXEC X_SALDO_COMMITCHANGES	

RETURN 0


GO
GRANT ALL ON [dbo].[BV_SAVE_G_PROV1_OS2_OS] TO PUBLIC 

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BV_SAVE_G_PROV2_AP_OS2]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BV_SAVE_G_PROV2_AP_OS2]

GO

/*
© Кейсистемс (Keysystems), 2005
*/

CREATE	PROCEDURE dbo.BV_SAVE_G_PROV2_AP_OS2
	@varKSnLINK_GP1  INT,		
	@varKSnTYP_LINK INT,			
	@varKSnLINK_INV  INT,			
	@varKSnSUMMA1	NUMERIC(28,2) = 0.00,		
	@varKSnSUMMA2	NUMERIC(28,2) = 0.00,		
	@parmQTY NUMERIC(19,2) = 0.00,		
	@varKSdCALC_DATE DATETIME = NULL,	
	@varKSnMode TINYINT = 0, 	
	@varKSpcSOU_CODE CHAR(1) = '0',
	@strINV_TYPE	VARCHAR (30) = 'INVENTORY_CARD'

AS

SELECT @varKSnSUMMA1 = ISNULL (@varKSnSUMMA1, 0), @varKSnSUMMA2	= ISNULL (@varKSnSUMMA2, 0)

DECLARE @varKScSOU_CODE CHAR(1),

	@varKScSinth CHAR(3),

	@varKSnQTY NUMERIC(19,2), 

	@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),
	@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


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 = '0'



-- Вычисление организации для ЦБ
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


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 @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
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = ART.ACCOUNT)
	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)
	ORDER BY 1, 6, D_SUMMA DESC

	SET @varKSnRowCount = @@ROWCOUNT
	IF @varKSnRowCount = 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_DT ROS
	ELSE
		SELECT @varKScSOU_CODE = @varKSpcSOU_CODE,
			@varKSnKBK = NULL,
			@varKSnEKR = NULL,
			@varKSnDEP = NULL,
			@varKSnSUB = NULL,
			@varKSnEMP = NULL,
			@varKSnNOMEN = CASE
							WHEN @strINV_TYPE = 'BV_NOMENCLATURE' THEN @varKSnLINK_INV
							ELSE NULL 
						END ,
			@varKSnINV = CASE
							WHEN @strINV_TYPE = 'INVENTORY_CARD' THEN @varKSnLINK_INV
							ELSE NULL 
						END ,
			@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
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = ART.ACCOUNT)
	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)
	ORDER BY 1, 6, D_SUMMA DESC

	SET @varKSnRowCount = @@ROWCOUNT
	IF @varKSnRowCount = 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 = @varKSpcSOU_CODE,
			@varKSnKBK = NULL,
			@varKSnEKR = NULL,
			@varKSnDEP = NULL,
			@varKSnSUB = NULL,
			@varKSnEMP = NULL,
			@varKSnNOMEN = CASE
							WHEN @strINV_TYPE = 'BV_NOMENCLATURE' THEN @varKSnLINK_INV
							ELSE NULL 
						END ,
			@varKSnINV = CASE
							WHEN @strINV_TYPE = 'INVENTORY_CARD' THEN @varKSnLINK_INV
							ELSE NULL 
						END ,
			@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-6]'))
			 OR (SA2.cAnalit = '07' AND SA1.cSinth = '103'))
		  ELSE
			SELECT @varKSnGAP_ACCOUNT_DT = ACCOUNT FROM #REST_OS_DT

	IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK = @varKSnGAP_ACCOUNT_DT AND cSinth = '106')
		  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 = '106')
			SELECT @varKSnGAP_ACCOUNT_DT = ACCOUNT FROM #REST_OS_DT
		    ELSE
			SELECT @varKSnGAP_ACCOUNT_DT = dbo.BK_GET_ACCOUNT_MASK_BY_INV (@varKSnLINK_INV, '106')
		  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-6]'))
			 OR (SA2.cAnalit = '07' AND SA1.cSinth = '103'))
		  ELSE
			SELECT @varKSnGAP_ACCOUNT_KT = ACCOUNT FROM #REST_OS_KT

	IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK = @varKSnGAP_ACCOUNT_KT AND cSinth = '106')
		  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 = '106')
			SELECT @varKSnGAP_ACCOUNT_KT = ACCOUNT FROM #REST_OS_KT
		    ELSE
			SELECT @varKSnGAP_ACCOUNT_KT = dbo.BK_GET_ACCOUNT_MASK_BY_INV (@varKSnLINK_INV, '106')
		  ELSE
			SELECT @varKSnGAP_ACCOUNT_KT = ACCOUNT FROM #REST_OS_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 @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_DT IS NULL
	  BEGIN
	    SELECT @varKScSinth = cSinth FROM S_ACCOUNTS WHERE LINK = @varKSnLINK_ACC_DT

	    IF @varKScSinth IS NOT NULL
		SET @varKSnSGU_DT = CASE 
		  WHEN @varKScSinth = '101' THEN (SELECT TOP 1 LINK FROM KOSGU WHERE CODE = '310')
		  WHEN @varKScSinth = '102' THEN (SELECT TOP 1 LINK FROM KOSGU WHERE CODE = '320')
		  WHEN @varKScSinth = '103' THEN (SELECT TOP 1 LINK FROM KOSGU WHERE CODE = '330')
		  WHEN @varKScSinth = '105' THEN (SELECT TOP 1 LINK FROM KOSGU WHERE CODE = '340')
		  ELSE (SELECT TOP 1 LINK FROM KOSGU WHERE CODE = '300') END
	    ELSE
		SELECT TOP 1 @varKSnSGU_DT = LINK FROM KOSGU WHERE CODE = '300'
	  END
-- При внутреннем перемещении Кредетовое ОСГУ равно Дебетовому
	IF @varKSnSGU_KT IS NULL 
		SET @varKSnSGU_KT = @varKSnSGU_DT

	
	SET @varKSnLINK_ACC_DT = dbo.BK_GetDBKTAccount (@varKSnLINK_ACC_DT, DEFAULT, DEFAULT, DEFAULT) -- Контроль пользовательской части счетов
	SET @varKSnLINK_ACC_KT = dbo.BK_GetDBKTAccount (@varKSnLINK_ACC_KT, DEFAULT, DEFAULT, DEFAULT) -- Контроль пользовательской части счетов

	IF EXISTS(SELECT * FROM S_ACCOUNTS WHERE LINK IN (@varKSnLINK_ACC_DT, @varKSnLINK_ACC_KT)
				AND KSU = CONVERT(TINYINT,1))
		SET @varKSnQTY = @parmQTY
	ELSE
		SET @varKSnQTY = 0

	SET @varKSnLINK_GP2 = NULL

	IF @strINV_TYPE	= 'INVENTORY_CARD'
		SELECT TOP 1 @varKScG2_NAME = ISNULL(RTRIM(@varKScG2_NAME) + ' ', '') + 'Инв.№:' + RTRIM(CODE) + ' - ' + RTRIM(NAME)
		FROM dbo.INVENTORY
		WHERE LINK = @varKSnLINK_INV
	
	IF @strINV_TYPE = 'BV_NOMENCLATURE' 
		SELECT TOP 1 @varKScG2_NAME = ISNULL(RTRIM(@varKScG2_NAME) + ' ', '') + 'Номен.№:' + RTRIM(CODE) + ' - ' + RTRIM(NAME)
		FROM dbo.NOMENCLATURE
		WHERE LINK = @varKSnLINK_INV

	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	

	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

-- select code, * from s_accounts where link = @varKSnLINK_ACC_DT

		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 EXECUTE ON dbo.[BV_SAVE_G_PROV2_AP_OS2] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BB_REESTR_DEN_SR_DATA]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BB_REESTR_DEN_SR_DATA]

GO

CREATE     PROCEDURE dbo.BB_REESTR_DEN_SR_DATA 
	@nLink INT = NULL, @BUFFER_ID VARCHAR(20) = NULL
AS

BEGIN

DECLARE @str VARCHAR(7000), 
		@nMode INT,
		@SortMode INT,
		@GroupMode INT,
		@WrapMode INT,
		@FIOShort tinyint

DECLARE @SPISOK_VEDOM TABLE (LINK INT)
INSERT INTO @SPISOK_VEDOM (LINK)
SELECT LINK FROM DBO.BUFFER WITH (NOLOCK) WHERE ID = @BUFFER_ID

IF @nLink IS NOT NULL AND NOT EXISTS (SELECT * FROM @SPISOK_VEDOM WHERE LINK = @nLink)
	INSERT INTO @SPISOK_VEDOM (LINK) VALUES (@nLink)

IF @BUFFER_ID IS NOT NULL
	SET @nLink = NULL
IF COALESCE((SELECT COUNT(*) FROM @SPISOK_VEDOM),0) =1
	SET @nLink = (SELECT LINK FROM @SPISOK_VEDOM)
		
/* Читаем настройки сортировки  1 - по фио, 2 - по табельному номеру, 3 - по коду должности */
SELECT top 1 @SortMode = ISNULL(CONVERT(INT,VALUE),1) 
FROM S_OPTIONS 
WHERE OBJECT = (SELECT top 1 LINK FROM S_OBJECTS WHERE CODE = 'VEDOM_OPTIONS_VEDOM_SORT') AND SID IS NULL

/* Читаем настройки переноса */
SELECT top 1 @WrapMode = ISNULL(CONVERT(INT,VALUE),0)
FROM S_OPTIONS 
WHERE OBJECT = (SELECT top 1 LINK FROM S_OBJECTS WHERE CODE = 'VEDOM_OPTIONS_VEDOM_PERENOS') AND SID IS NULL

/* Читаем настройки группировки */
SELECT top 1 @GroupMode = (CASE WHEN ISNULL(CONVERT(INT,VALUE),0) = 0 THEN @WrapMode else ISNULL(CONVERT(INT,VALUE),0) END)
FROM S_OPTIONS 
WHERE OBJECT = (SELECT top 1 LINK FROM S_OBJECTS WHERE CODE = 'VEDOM_OPTIONS_VEDOM_GROUP') AND SID IS NULL

SET @str = DBO.OBJECT_VAR_GET_OBJECT_VALUE('SALARY_QUERY_PAYROLL_N3','QUERY_NASTR_VALUE',1)
/* Выбирается вариант сортировки */
SET @nMode = CASE WHEN @str = 'ФИО' THEN 2 ELSE 1 END 

CREATE TABLE #SDOC_VEDOM_TABLE1 (LINK_UP INT, LINK_EMPL INT, LINK_SFIN INT, LINK_EKR INT, ORDERS INT, DISBURS NUMERIC(18,2), 
		CODE_EKR VARCHAR(3), CODE_KBK VARCHAR(30), CODE_DT VARCHAR(13), CODE_KT VARCHAR(13))

INSERT INTO 
	#SDOC_VEDOM_TABLE1 (LINK_UP, LINK_EMPL, ORDERS, DISBURS, CODE_KBK, CODE_EKR)
SELECT 
	LINK_UP, PERS_LINK, ORDERS = MAX(ORDERS), DISBURS = SUM(SUMMA), d.KBK_CODE, d.EKR_CODE
FROM 
	dbo.BB_REESTR_DEN_SR_TABLE D
WHERE 
	(D.LINK_UP = @nLink AND @nLink IS NOT NULL
	OR
	D.LINK_UP IN (SELECT LINK FROM @SPISOK_VEDOM))
GROUP BY 
	LINK_UP, PERS_LINK, d.KBK_CODE, d.EKR_CODE


------------------------------------------------------------------

DECLARE @res TABLE (
		LINK_DOC INT,DOC_DATE DATETIME, DOC_DATE1 varchar(10), DOC_NUM VARCHAR(60), 
		KASSIR VARCHAR(120), KASS_POST VARCHAR(254),
		DIV_NAME VARCHAR(254), DIV_CODE VARCHAR(10),
		TI_NAME VARCHAR(254), TI_CODE VARCHAR(10),
		VR_NAME VARCHAR(254), VR_CODE VARCHAR(10),
		NAME_PAYR VARCHAR(254),
		NAME_PAY VARCHAR(120), CODE_PAY VARCHAR(10),
		DATE_BEGIN DATETIME, DATE_END DATETIME, 
		[MONTH] VARCHAR(20), [YEAR] VARCHAR(4), 
		NPP INT IDENTITY,
		LINK_EMPL INT, 
		TN VARCHAR(15), 
		FIO VARCHAR(254),
		S_FIO VARCHAR(100),
		FM VARCHAR(50), 
		IM VARCHAR(50), 
		OT VARCHAR(50), 
		SUMMA NUMERIC(15,2),
		SUMMA1 VARCHAR(18), 
		ACCT VARCHAR(254), 
		ACCT_V VARCHAR(254), 
		BANK_LINK INT, BANK_NAME VARCHAR(254), BIK VARCHAR(9), DEP_ACCT VARCHAR(30),
		CARD_LINK INT, CARD_NAME VARCHAR(254), CARD_CODE VARCHAR(3), CARD_POSTF VARCHAR(2),
		NOSB VARCHAR(4), NFSB VARCHAR(5), NDOG_SB VARCHAR(20), DATE_DOGSB datetime,
		POST_CODE VARCHAR(10),
		POST VARCHAR(254),
		OKLAD NUMERIC(15,0),
		STAKE NUMERIC(5,2),
		DAYS_W numeric (3,0),
		HOURS_W numeric (3,0),
		DAYS_H numeric (3,0),
		HOURS_H numeric (3,0),
		SERNUM VARCHAR(20),
		SUM_ALL NUMERIC(20,2),  COUNT_OP INT,
		DEP_NAME VARCHAR(254),
		PASSPORT VARCHAR(254),
		ADDRESS VARCHAR(254),
		PINDEX VARCHAR(10),
		PHONE VARCHAR(20),
		FD_CODE varchar(2),
		FD_DATE varchar(8),
		FD_ROVD varchar(254),
		SUBDIV_CODE varchar(20),
		SUBDIV varchar(254),
		BIRTHDAY varchar(8),
		ADDR varchar(254),
		shild int,
		REGION  VARCHAR(120), ABR_REGION  VARCHAR(12),
		RAION   VARCHAR(120), ABR_RAION  VARCHAR(12),
		GOROD	VARCHAR(50), ABR_GOROD  VARCHAR(12),
		NAS_PUNKT   VARCHAR(120), ABR_NAS_PUNKT  VARCHAR(12),
		ULICA	VARCHAR(120), ABR_ULICA  VARCHAR(12),
		DOM	VARCHAR(5), KORPUS VARCHAR(5), KVARTIRA VARCHAR(5),
		DEP_INN VARCHAR(12), DEP_KPP VARCHAR(9), DEP_OKPO VARCHAR(20), DEP_OGRN VARCHAR(13),
		EXRT INT, EXRT_D INT, LINK_DEP INT, FRMT_LINK INT,
		DD VARCHAR(2), MM VARCHAR(2), YYYY VARCHAR(4),
		CODE_EKR VARCHAR(3), LINK_EKR INT,
		EKR_ANALIT VARCHAR(3),
		CODE_KBK VARCHAR(30),
		CODE_DT VARCHAR(13),
		CODE_KT VARCHAR(13),
/*+*/	RND varchar(16), [DATE] varchar(8), [TIME] varchar(8) 
	)

	DECLARE 
		@ORGNAME VARCHAR(254), @DEP_LINK INT,
		@DOC_DATE DATETIME, @DOC_DATE1 varchar(10), @DOC_NUM VARCHAR(60), 
		@DOC_DT_BEG DATETIME, @DOC_DT_END DATETIME,
		@KASSIR VARCHAR(254), @KASS_POST VARCHAR(254),
		@DIV_NAME VARCHAR(254), @DIV_CODE VARCHAR(10),
		@TI_NAME VARCHAR(254), @TI_CODE VARCHAR(10),
		@VR_NAME VARCHAR(254), @VR_CODE VARCHAR(10),
		@NAME_PAY VARCHAR(254), @CODE_PAY VARCHAR(10), @NAME_PAYR VARCHAR(254),
		@DATE_BEGIN DATETIME, @DATE_END DATETIME,
		@Month VARCHAR(20), @Year VARCHAR(4),
		@DEP_ACCT VARCHAR(30),
		@CARD_LINK int, @DEP_INN VARCHAR(12), @DEP_KPP VARCHAR(9), @DEP_OKPO VARCHAR(20), @DEP_OGRN VARCHAR(13),
		@TYPE_DAYS  int 

	SET @TYPE_DAYS = (select top 1 link  from TYP_DAYS  where name = 'Выходные и праздничные'	)
	SELECT  top 1 
			@ORGNAME 	= LEFT(DEP.[NAME],254), 
			@DEP_LINK 	= DEP.LINK,
			@DEP_INN = LEFT(INN,12), @DEP_KPP = LEFT(KPP,9), @DEP_OKPO = LEFT(OKPO,20), @DEP_OGRN = LEFT(OGRN,13)
	FROM dbo.DICTIONARY_DEPARTMENT DEP, USER_DEP UI WHERE DEP.LINK = UI.DEP_LINK

	---		
	SELECT top 1 
		@DOC_DATE = R.[DATE],
		@DOC_DATE1 = convert(varchar(10), R.[DATE], 103) ,
		@DOC_DT_BEG = R.[DATE], 
		@DOC_DT_END = R.[DATE],
		@DOC_NUM = LEFT(R.NUMBER,60),
		@KASSIR = '',--LEFT(ISNULL(dbo.sd_GetEmplName(SD.REF_KASSIR), 0),254),
		@KASS_POST = '',--LEFT(dbo.ku_GetEmplPostName(SD.REF_KASSIR,DEFAULT),254),
		@DIV_NAME = LEFT(ISNULL(F.NAME_FKR_D, ''),254), 
		@DIV_CODE = LEFT(ISNULL(F.CODE_FKR_D, ''),10),
		@TI_NAME = LEFT(ISNULL(F.NAME_FKR_T, ''),254), 
		@TI_CODE = LEFT(ISNULL(F.CODE_FKR_T, ''),0),
		@VR_NAME = LEFT(ISNULL(F.NAME_FKR_E, ''),254), 
		@VR_CODE = LEFT(ISNULL(F.CODE_FKR_E, ''),0),
		@NAME_PAY = '',--LEFT(ISNULL(P.NAME, ''),254), 
		@CODE_PAY = '',--LEFT(ISNULL(P.CODE, ''),10),  
		@NAME_PAYR = LEFT(ISNULL(R.DEP_NAME, ''),254),
		@DATE_BEGIN = dbo.ConvertDMY2Date(1, MONTH(R.[DATE]), YEAR(R.[DATE])),
		@Year = YEAR(R.[DATE]),
		@Month = (SELECT top 1 m.mon FROM MONTHS M WHERE M.NUM = MONTH(R.[DATE])),
		@CARD_LINK = R.CARD_LINK
	FROM dbo.BB_REESTR_DEN_SR R 
	inner join dbo.BB_REESTR_DEN_SR_TABLE T ON R.LINK = T.LINK_UP
		LEFT OUTER JOIN BI_DICTION_VKR F ON T.KBK_LINK = F.LINK_KBK
	WHERE 
		@nLink IS NOT NULL AND R.LINK = @nLink
		OR
		R.LINK = (SELECT TOP 1 LINK FROM @SPISOK_VEDOM)
	
	----
	SET 	@DATE_END = dbo.DateEndOfMonth(@DATE_BEGIN)

/*+*/
--Ищем xml формат по названию, для xml нужна замена кавычек в названии организации на &quot;
declare @isxml bit
if exists (
		select top 1 * FROM
		dbo.SDOC S
		INNER JOIN dbo.SDOC_VEDOM SD ON S.LINK = SD.LINK_UP
		LEFT JOIN dbo.cards C ON SD.LINK_CARD = C.LINK and SD.LINK_CARD = @CARD_LINK
		LEFT JOIN dbo.S_BANK_FORMATS F ON F.LINK = C.FRMT_LINK
		where s.LINK = @nLink and f.NAME like '%xml%'
		)
set @isxml = 1
/*+*/

--Выводить вместо подписи лицевой счёт
DECLARE @VEDOM_OPTIONS_2_12 INT
SET @VEDOM_OPTIONS_2_12 = dbo.SA_GET_OPTION_BY_CODE ('VEDOM_OPTIONS_2_12')

SELECT LINK_EMPL = PERS_LINK, LINK_DOC = LINK_UP, LINK_EKR = EKR_LINK, SUM(SUMMA) AS SUMM
INTO #SUM_EKR
FROM 	dbo.BB_REESTR_DEN_SR_TABLE D
WHERE 
	(D.LINK_UP = @nLink AND @nLink IS NOT NULL
	OR
	D.LINK_UP IN (SELECT LINK FROM @SPISOK_VEDOM))
GROUP BY 
	LINK_UP, PERS_LINK, d.EKR_LINK


	INSERT INTO @res
	(LINK_DOC,DOC_DATE, DOC_DATE1, DOC_NUM, 
  	 KASSIR, KASS_POST,
	 DIV_NAME, DIV_CODE,TI_NAME, TI_CODE,VR_NAME, VR_CODE,
  	 NAME_PAYR,
	 NAME_PAY,CODE_PAY,
  	 DATE_BEGIN, DATE_END, 
	 [MONTH], [YEAR],
  	 LINK_EMPL,TN,FIO, FM, IM, OT, S_FIO,
 	 SUMMA, SUMMA1, 
	 ACCT,ACCT_V, BANK_LINK, BANK_NAME, BIK, DEP_ACCT,
 	 NOSB, NFSB, NDOG_SB, DATE_DOGSB,
	 CARD_LINK, CARD_NAME, CARD_CODE, CARD_POSTF,
 	 POST_CODE,
	 POST,
	 OKLAD ,
	 STAKE ,
	 DAYS_W,
	 HOURS_W,
	 DAYS_H,
	 HOURS_H,
	 SERNUM,
	 DEP_NAME,
	 PASSPORT,
	 ADDRESS,PINDEX,PHONE,
 	 FD_CODE,FD_DATE,FD_ROVD,
	 SUBDIV_CODE,	
	 SUBDIV,
	 BIRTHDAY,
	 ADDR,
	REGION, ABR_REGION, RAION, ABR_RAION, 
	GOROD, ABR_GOROD, NAS_PUNKT, ABR_NAS_PUNKT,
	ULICA, ABR_ULICA, DOM, KORPUS, KVARTIRA,
	DEP_INN, DEP_KPP, DEP_OKPO, DEP_OGRN, 
	EXRT, EXRT_D, LINK_DEP, FRMT_LINK,
	DD, MM, YYYY, CODE_EKR, LINK_EKR, 
	EKR_ANALIT, CODE_KBK, CODE_DT, CODE_KT
/*+*/, RND, [DATE], [TIME]	
)
	

	SELECT 
		@nLink, 
		@DOC_DATE, @DOC_DATE1, LEFT(@DOC_NUM,60), 
		LEFT(@KASSIR,120), LEFT(@KASS_POST,254),
		LEFT(@DIV_NAME,254), LEFT(@DIV_CODE,10),
		LEFT(@TI_NAME,254), LEFT(@TI_CODE,10),
		LEFT(@VR_NAME,254), LEFT(@VR_CODE,10),
		LEFT(@NAME_PAYR,254),
		LEFT(@NAME_PAY,120), LEFT(@CODE_PAY,10),
		@DATE_BEGIN, @DATE_END, 
		@Month, @Year,
		D.LINK_EMPL, 
        '',--LEFT(P.TAB,15),
		LEFT(ISNULL((SELECT LTRIM(RTRIM(P.FM)) + ' ' + LTRIM(RTRIM(P.IM)) + ' ' +  LTRIM(RTRIM(P.OT))),'Не заполнено'),254),
		LEFT(P.FM,50), LEFT(P.IM,50), LEFT(P.OT,50),
		LEFT(ISNULL((SELECT LTRIM(RTRIM(P.FM)) + ' ' + LTRIM(RTRIM(P.IM)) + ' ' +  LTRIM(RTRIM(P.OT))),'Не заполнено'),100),
		ISNULL(EKR.SUMM,ISNULL(DISBURS, 0)),
		LEFT(dbo.sa_convert_numeric_to_char(ISNULL(EKR.SUMM,ISNULL(DISBURS, 0)), 2, '.', ','),18),
		[acct] = LEFT(ISNULL(PE.LIC_SCHET, '0'),254), 
		ACCT_V = CASE WHEN @VEDOM_OPTIONS_2_12 = 0 THEN '0' ELSE LEFT(ISNULL(PE.LIC_SCHET, '0'),254) END, 
		PE.BANK_LINK,
		[BANK_NAME] = (SELECT top 1 LEFT([NAME],254) FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),
		[BANK_BIK] =  (SELECT top 1 LEFT(BIK,9) FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),
		[DEP_ACCT]  = (SELECT TOP 1 LEFT(CODE,30) FROM DICTIONARY_ACCOUNTS 
                      WHERE REF_LINK_B = PE.BANK_LINK 
						AND [TYPE_NAME] = 'РАСЧЕТНЫЙ' 
						AND REF_LINK_D = @DEP_LINK),
		[OSB] = ISNULL((SELECT top 1 LEFT(OSB,4) FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),''),
		[FILIAL] = 
			CASE WHEN NOT LTRIM(RTRIM(ISNULL(PE.FILIAL,''))) = '' 
				THEN PE.FILIAL
				ELSE ISNULL((SELECT top 1 LEFT(FILIAL,5) FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),'')
			END,
		[DOGOVOR] = 
			CASE WHEN NOT LTRIM(RTRIM(ISNULL(PE.DOGOVOR,''))) = '' 
				THEN PE.DOGOVOR
				ELSE ISNULL((SELECT top 1 LEFT(DOGOVOR,20) FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),'')
			END,		
		[DATE_DOG] = ISNULL(PE.DATE_DOG,(SELECT top 1 DATE_DOG FROM dbo.BANKS WHERE LINK = PE.BANK_LINK)),
		PE.CARD_LINK, 
		[CARD_NAME] = (SELECT top 1 LEFT([NAME],254) FROM dbo.CARDS WHERE LINK = PE.CARD_LINK),
		[CARD_CODE] = (SELECT top 1 LEFT(CODE,3) FROM dbo.CARDS WHERE LINK = PE.CARD_LINK),
		[POSTFIX] =  (SELECT top 1 LEFT(POSTFIX,2) FROM dbo.CARDS WHERE LINK = PE.CARD_LINK),
		'', --LEFT(E.POST_CODE,10),
		'', --LEFT(E.POST_NAME,254),
		OKLAD = (select  sum(summa)	
				    FROM KJ_MONEY_PERIOD MP 
					INNER JOIN PAYS P ON MP.PAY_LINK=P.LINK
					where
					convert(datetime,'20120808') between mp.date_begin and isnull(mp.date_end,'20990101')
					and	
					P.WAY_CALC = 1
					and MP.EMPL_LINK = d.link_empl
					group by
					MP.EMPL_LINK
				   )	,
		STAKE =  (select TOP 1 num_stake from DBO.SA_EMPLS_INFO(@DOC_DT_BEG, default) where empl_link = d.link_empl ),
		DAYS_W = (dbo.SA_GET_EMPL_WD (D.LINK_EMPL, 0, DEFAULT, dbo.ConvertDMY2Date(1,month(@DOC_DT_BEG),year(@DOC_DT_BEG)), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,month(@DOC_DT_BEG),year(@DOC_DT_BEG))), DEFAULT, 0)),
		HOURS_W = (dbo.SA_GET_EMPL_WH (D.LINK_EMPL, 0, DEFAULT,  dbo.ConvertDMY2Date(1,month(@DOC_DT_BEG),year(@DOC_DT_BEG)), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,month(@DOC_DT_BEG),year(@DOC_DT_BEG))), DEFAULT, 0)) ,
		DAYS_H = (dbo.SA_GET_EMPL_WD (D.LINK_EMPL, 0, DEFAULT,  dbo.ConvertDMY2Date(1,month(@DOC_DT_BEG),year(@DOC_DT_BEG)), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,month(@DOC_DT_BEG),year(@DOC_DT_BEG))), DEFAULT, @TYPE_DAYS)) ,
		HOURS_H = (dbo.SA_GET_EMPL_WH (D.LINK_EMPL, 0, DEFAULT,  dbo.ConvertDMY2Date(1,month(@DOC_DT_BEG),year(@DOC_DT_BEG)), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,month(@DOC_DT_BEG),year(@DOC_DT_BEG))), DEFAULT, @TYPE_DAYS)),
/*+*/	replace(LEFT(ISNULL(P.DOC_NUM, ''),20),' ',''),
/*+*/	case when @isxml = 1 then replace(LEFT(@ORGNAME,254),'"','&quot;') else LEFT(@ORGNAME,254) end, 
		LEFT(dbo.PrintSalaryGetPassportString(P.DOC_NUM, P.DOC_WHOM, P.DOC_DATE),254),
		LEFT(dbo.GetAddressByFace(P.LINK, 0),254),
		'',
		LEFT(ISNULL(P.PHONE_OFIC, ''),10),
		[FD_CODE] = (CASE WHEN FD.CODE = '21' THEN '8' 
				  WHEN FD.CODE = '01' THEN '1'
					ELSE LEFT(FD.CODE,2) END), 
		[FD_DATE] = LEFT(CONVERT(VARCHAR,P.DOC_DATE,3),8),
		[FD_ROVD] = LEFT(P.DOC_WHOM,254),
		[SUBDIV]  = '',--LEFT(COALESCE(E.SUBDIV_CODE,''),20),
		[SUBDIV]  = '',--LEFT(COALESCE(E.SUBDIV_NAME,''),254),
		[BIRTHDAY] = LEFT(CONVERT(VARCHAR,P.BIRTHDATE,3),8),
		[ADDR]   = LEFT(dbo.GetAddressByKladr2(P.ADR_OFIC_LINK)+ ' '	+ ltrim(rtrim(house_ofic))+'-'+ltrim(rtrim(flat_ofic)),254),
		REGION = LEFT(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,' '))) ) )),120), 
		ABR_REGION = LEFT(RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,3,',')),1,' ')) )), 12),
		RAION = LEFT(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,' '))) ) )), 120),
		ABR_RAION = LEFT(RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,4,',')),1,' ')) )), 12),
		GOROD = LEFT(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,' '))) ) )),50),
		ABR_GOROD = LEFT(RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,5,',')),1,' ')) )), 12),
		NAS_PUNKT = LEFT(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,' '))) ) )), 120),
		ABR_NAS_PUNKT = LEFT(RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,6,',')),1,' ')) )),12),
		ULICA = LEFT(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,' '))) ) )),120),
		ABR_ULICA = LEFT(RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,7,',')),1,' ')) )), 12),
		DOM = LEFT(dbo.SA_GET_WORD_NUM(ADDRESS2,8,','), 5),
		KORPUS = LEFT(dbo.SA_GET_WORD_NUM(ADDRESS2,9,','), 5),
		KVARTIRA = LEFT(dbo.SA_GET_WORD_NUM(ADDRESS2,10,','),5),
		LEFT(@DEP_INN,12), LEFT(@DEP_KPP,9), LEFT(@DEP_OKPO,20), LEFT(@DEP_OGRN,13),
		EXRT = COALESCE(F.LastFileNumber,1),
		EXRT_D = COALESCE(FE.NUM_EXPORT,1),
		G.DEP,
		C.FRMT_LINK,
		DD = RIGHT('0' + CONVERT(VARCHAR(2),DAY(GETDATE())),2),
		MM = RIGHT('0' + CONVERT(VARCHAR(2),MONTH(GETDATE())),2),
		YYYY = CONVERT(VARCHAR(4),YEAR(GETDATE())),
		CODE_EKR = COALESCE(SGU.CODE,''), EKR.LINK_EKR,  --Для вывода итогов по ЭКР
		EKR_ANALIT = D.CODE_EKR,
		D.CODE_KBK,
		D.CODE_DT,
		D.CODE_KT,
/*+*/	RND = convert(varchar(16), left(replace(cast(CONVERT(binary(8), RAND(), 0) as uniqueidentifier),'-',''), 16)),
/*+*/	[DATE] = convert(varchar(8),getdATE(),112), --YYYYMMDD
/*+*/	[TIME] = replace(convert(varchar(8),getdATE(),108),':','') --HHMMSS		
	FROM #SDOC_VEDOM_TABLE1 D
		INNER JOIN dbo.G_PROV G on G.LINK = D.LINK_UP
		--INNER JOIN dbo.SD_EMPL E ON E.LINK = D.LINK_EMPL
		INNER JOIN (Select *, dbo.GET_ADDRESS9PARTS(dbo.PERSON.LINK, 0) ADDRESS2 from dbo.PERSON) P ON D.LINK_EMPL = P.LINK
		LEFT OUTER JOIN dbo.FACE_DOCUMENT FD ON P.DOC_LINK = FD.LINK	
		LEFT OUTER JOIN dbo.SA_PERSON_ECARD_ACTUAL PE ON (PE.PERS_LINK = P.LINK AND PE.CARD_LINK = @CARD_LINK)
		LEFT JOIN dbo.cards C ON PE.CARD_LINK = C.LINK
		LEFT JOIN dbo.S_BANK_FORMATS F ON F.LINK = C.FRMT_LINK
		LEFT JOIN dbo.S_BANK_FORMAT_EXPORT FE ON F.LINK = FE.LINK_UP AND FE.LINK_DEP = G.DEP
		LEFT JOIN #SUM_EKR EKR ON EKR.LINK_EMPL = D.LINK_EMPL AND D.LINK_UP = EKR.LINK_DOC AND EXISTS (SELECT * FROM DBO.S_BANK_FORMAT_FILES FF WHERE GRP_EKR = 1 AND FF.LINK_FMT = F.LINK)
		LEFT JOIN DBO.KOSGU SGU ON SGU.LINK = EKR.LINK_EKR
	WHERE 
		ISNULL(EKR.SUMM,ISNULL(D.DISBURS, 0)) > 0 
	ORDER BY /*CASE 
		WHEN @GroupMode = 1 THEN E.SUBDIV_CODE
		ELSE '' END,
	CASE 	
		WHEN @SortMode = 1 THEN*/ P.FM
		--WHEN @SortMode = 2 THEN P.TAB
		--WHEN @SortMode = 3 THEN P.POST_CODE
		/*ELSE CAST(D.ORDERS AS VARCHAR(10))
	END*/

	UPDATE @res SET 
		PINDEX = LTRIM(RTRIM(LEFT(ADDRESS, 7))),
		ADDRESS= LTRIM(RTRIM(RIGHT(ADDRESS, LEN(ADDRESS)-7)))
	WHERE LEFT(ADDRESS, 1) IN (	'0', '1', '2', '3', '4', '5', '6', '7', '8', '9')

	UPDATE @res SET SUM_ALL = (SELECT SUM(SUMMA) FROM @res)
	UPDATE @res SET COUNT_OP = (SELECT COUNT(*)  FROM @res)

	CREATE TABLE #SUM_EKR1 (LINK_EKR INT, SUMMA NUMERIC(20,2), CNT INT )
	INSERT INTO #SUM_EKR1 (LINK_EKR, SUMMA, CNT)
	SELECT LINK_EKR, SUM(SUMM) AS SUMM, COUNT(LINK_EKR) as CNT_EKR FROM #SUM_EKR
	GROUP BY LINK_EKR

	SELECT R.*, 
		NPP_G= (Case when @GroupMode = 1 then (Select count(NPP) from @res RC where COALESCE(RC.SUBDIV_CODE,'') = COALESCE(R.SUBDIV_CODE,'') and RC.NPP <= R.NPP) else R.NPP end),
		GRP_EKR = CASE WHEN EK.SUMMA IS NULL THEN 0 ELSE 1 END,
		ITOG_EKR = COALESCE(EK.SUMMA,0),
		KOL_ST_EKR = COALESCE(EK.CNT,0)
	FROM 
		@res R LEFT JOIN #SUM_EKR1 EK ON R.LINK_EKR = EK.LINK_EKR
	ORDER BY CODE_EKR, NPP

	SELECT NDOG_SB, NOSB, NFSB, COUNT(*) AS COUNT_OP, SUM(SUMMA) AS SUMMA_ALL 
	INTO #RES1
	FROM @res
	GROUP BY NDOG_SB, NOSB, NFSB
	ORDER BY 1, 2, 3
	
	SELECT @ORGNAME AS ORGNAME, * FROM #RES1
	ORDER BY 1, 2, 3, 4

END


GO


GRANT EXECUTE ON dbo.BB_REESTR_DEN_SR_DATA TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_REP_VEDOM_DGH_PREPARE_DATA]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_REP_VEDOM_DGH_PREPARE_DATA]

GO


CREATE  PROCEDURE dbo.SD_REP_VEDOM_DGH_PREPARE_DATA 
	@nLink INT = NULL,
	@BUFFER_ID VARCHAR(20) = NULL
AS
 BEGIN

DECLARE @SPISOK_VEDOM TABLE (LINK INT)
INSERT INTO @SPISOK_VEDOM (LINK)
SELECT LINK FROM DBO.BUFFER WITH (NOLOCK) WHERE ID = @BUFFER_ID

IF @nLink IS NOT NULL AND NOT EXISTS (SELECT * FROM @SPISOK_VEDOM WHERE LINK = @nLink)
	INSERT INTO @SPISOK_VEDOM (LINK) VALUES (@nLink)

IF @BUFFER_ID IS NOT NULL
	SET @nLink = NULL
IF COALESCE((SELECT COUNT(*) FROM @SPISOK_VEDOM),0) =1
	SET @nLink = (SELECT LINK FROM @SPISOK_VEDOM)




CREATE TABLE #DOCUMENTS_DED_PR_TABLE_DGH1 (LINK INT, PERS_LINK INT, FIO varchar(150), LINK_SFIN INT, LINK_EKR INT, ORDERS INT, DISBURS NUMERIC(18,2), 
		CODE_EKR VARCHAR(3), CODE_KBK VARCHAR(30), CODE_DT VARCHAR(13), CODE_KT VARCHAR(13) , NOTE VARCHAR(254))

INSERT INTO 
	#DOCUMENTS_DED_PR_TABLE_DGH1 (LINK, PERS_LINK, FIO, ORDERS, DISBURS, NOTE)
SELECT 
	D.LINK, D.PERS_LINK, FIO,  ORDERS = MAX(d.ORDERS), DISBURS = SUM(d.DISBURS) , ltrim(rtrim(NOTE))
FROM 
	dbo.DOCUMENTS_DED_PR_TABLE_DGH D
WHERE 
	(D.LINK = @nLink AND @nLink IS NOT NULL
	OR
	D.LINK IN (SELECT LINK FROM @SPISOK_VEDOM))
GROUP BY 
	LINK, PERS_LINK, FIO , NOTE

--	inner join dbo.DOCUMENTS_DED_PR_DGH_TABLE2 d2 on d2.link = d.link and d2.pers_link = d.pers_link 

----Для каждой ведомости определяются КБК и корреспондирующие счета
----Но только если указан конкретный источник и ЭКР в ведомости
DECLARE @CUR_ACC CURSOR, @LINK_VEDOM INT, @KBK_CODE VARCHAR(30), @EKR_CODE VARCHAR(3), @DT_CODE VARCHAR(40), @KT_CODE VARCHAR(40)

SET @CUR_ACC = CURSOR FORWARD_ONLY
FOR SELECT LINK FROM @SPISOK_VEDOM
OPEN @CUR_ACC
FETCH NEXT FROM @CUR_ACC INTO @LINK_VEDOM
WHILE (@@FETCH_STATUS <> -1)
BEGIN
	IF (@@FETCH_STATUS <> -2)
	BEGIN

		EXEC dbo.[SA_VEDOM_ACCOUNTS] @LINK_VEDOM = @LINK_VEDOM, @KBK_CODE = @KBK_CODE OUTPUT, @EKR_CODE = @EKR_CODE OUTPUT, @DT_CODE = @DT_CODE OUTPUT, @KT_CODE = @KT_CODE OUTPUT
		UPDATE #DOCUMENTS_DED_PR_TABLE_DGH1
		SET CODE_KBK = @KBK_CODE ,  CODE_EKR = @EKR_CODE, CODE_DT = @DT_CODE, CODE_KT = @KT_CODE
		WHERE LINK = @LINK_VEDOM
	END
	FETCH NEXT FROM @CUR_ACC INTO @LINK_VEDOM
END

CLOSE @CUR_ACC
DEALLOCATE @CUR_ACC

------------------------------------------------------------------

DECLARE	@res TABLE 
		(
		 LINK_DOC INT, 
		 DOC_DATE DATETIME, 
		 DOC_DATE1 varchar(10), 
		 EXCH_DATE datetime,
		 DOC_NUM VARCHAR(60), 
		 KASSIR VARCHAR(120), 
		 KASS_POST VARCHAR(254),
		 KASS_PHONE VARCHAR(40),
		 DIV_NAME VARCHAR(254), 
		 DIV_CODE VARCHAR(10),
		 TI_NAME VARCHAR(254), 
		 TI_CODE VARCHAR(10),
		 VR_NAME VARCHAR(254), 
		 VR_CODE VARCHAR(10),
	 	 NAME_PAYR VARCHAR(254),
		 NAME_PAY VARCHAR(120), 
		 CODE_PAY VARCHAR(10),
		 DATE_BEGIN DATETIME,
		 DATE_END DATETIME, 
		 [MONTH] VARCHAR(20), 
		 MON int,
		 [YEAR] VARCHAR(4), 
		 NPP INT IDENTITY, 
		 LINK_EMPL INT, 
	 	 TN VARCHAR(15), 
		 FIO VARCHAR(254),
		 S_FIO VARCHAR(100),
		 FM VARCHAR(50), 
		 IM VARCHAR(50), 
		 OT VARCHAR(50), 
		 INN VARCHAR(12),
		 SUMMA NUMERIC(15,2), 
		 SUMMA1 VARCHAR(18), 
		 ACCT VARCHAR(254), 
		 BANK_LINK INT, BANK_NAME VARCHAR(254), BIK VARCHAR(9), DEP_ACCT VARCHAR(30), DEP_ACC_M VARCHAR(20),
		 CARD_LINK INT, CARD_NAME VARCHAR(254), CARD_CODE VARCHAR(3), CARD_POSTF VARCHAR(2),
		 NOSB VARCHAR(4), NFSB VARCHAR(5), NDOG_SB VARCHAR(20), DATE_DOGSB datetime,
		 POST VARCHAR(254),
		 SERNUM VARCHAR(20),
		 SUM_ALL NUMERIC(20,2), 
		 COUNT_OP INT,
		 DEP_NAME VARCHAR(254), FULLNAME VARCHAR(2000),
 		 PASSPORT VARCHAR(254),
		 ADDRESS VARCHAR(254),
		 PINDEX VARCHAR(10),
		 PHONE VARCHAR(20),
		 FD_CODE varchar(2),
		 FD_DATE varchar(8),
		 FD_ROVD varchar(254),
		 SUBDIV_CODE varchar(20),
		 SUBDIV varchar(254),
		 BIRTHDAY varchar(8),
		 ADDR varchar(254),
		 shild int,
		REGION  VARCHAR(120), ABR_REGION  VARCHAR(12),
		RAION   VARCHAR(120), ABR_RAION  VARCHAR(12),
		GOROD	VARCHAR(50), ABR_GOROD  VARCHAR(12),
		NAS_PUNKT   VARCHAR(120), ABR_NAS_PUNKT  VARCHAR(12),
		ULICA	VARCHAR(120), ABR_ULICA  VARCHAR(12),
		DOM	VARCHAR(5), KORPUS VARCHAR(5), KVARTIRA VARCHAR(5),
		DEP_INN VARCHAR(12), DEP_KPP VARCHAR(9), DEP_OKPO VARCHAR(20), DEP_OGRN VARCHAR(13),
		EXRT INT, EXRT_D INT, LINK_DEP INT, FRMT_LINK INT,
		DD VARCHAR(2), MM VARCHAR(2), YYYY VARCHAR(4),
		CODE_EKR VARCHAR(3), LINK_EKR INT,
		EKR_ANALIT VARCHAR(3),
		CODE_KBK VARCHAR(30),
		CODE_DT VARCHAR(13),
		CODE_KT VARCHAR(13),
		NOTE VARCHAR(254),
/*+*/	RND varchar(16), [DATE] varchar(8), [TIME] varchar(8) 		 
)	

	DECLARE 
		@ORGNAME VARCHAR(254), @DEP_LINK INT, @ORGFULLNAME VARCHAR(2000),
		@DOC_DATE DATETIME, @DOC_DATE1 varchar(10),@EXCH_DATE datetime, @DOC_NUM VARCHAR(60), 
		@KASSIR VARCHAR(254), @KASS_POST VARCHAR(254),@KASS_PHONE VARCHAR(40),
		@DIV_NAME VARCHAR(254), @DIV_CODE VARCHAR(10),
		@TI_NAME VARCHAR(254), @TI_CODE VARCHAR(10),
		@VR_NAME VARCHAR(254), @VR_CODE VARCHAR(10),
		@NAME_PAY VARCHAR(254), @CODE_PAY VARCHAR(10), @NAME_PAYR VARCHAR(254),
		@DATE_BEGIN DATETIME, @DATE_END DATETIME,
		@Month VARCHAR(20),@MON int, @Year VARCHAR(4),
		@DEP_ACCT VARCHAR(30),@DEP_ACC_M VARCHAR(20),
		@CARD_LINK int,
		@DEP_INN VARCHAR(12), @DEP_KPP VARCHAR(9), @DEP_OKPO VARCHAR(20), @DEP_OGRN VARCHAR(13)
				

	SELECT top 1
			@ORGNAME 	= DEP.NAME , 
			@ORGFULLNAME  = LEFT(DEP.[FULL_NAME],2000),
			@DEP_LINK 	= DEP.LINK,
			@DEP_INN = INN, @DEP_KPP = KPP, @DEP_OKPO = OKPO, @DEP_OGRN = OGRN, @DEP_ACC_M = DEP.MAIN_LINK,
			@EXCH_DATE = getdate()
	FROM DICTIONARY_DEPARTMENT DEP, USER_DEP UI WHERE DEP.LINK = UI.DEP_LINK

	SELECT top 1
		@DOC_DATE = [DATE], @DOC_DATE1 = convert(varchar(10), [DATE], 103), @DOC_NUM = NUMBER,
		@KASSIR = ISNULL(NAME_EMPL, 0),
		@KASS_POST = (SELECT POST_NAME FROM dbo.KU_EMPL_PLACING EP WHERE EP.LINK = ISNULL(D.REF_EMPL, 0) ),
		@KASS_PHONE = LEFT((SELECT top 1 PHONE_WORK from KU_EMPL_PLACING WHERE LINK = ISNULL(D.REF_EMPL, 0)),40),
		@DIV_NAME = ISNULL(NAME_FKR_D, ''), @DIV_CODE = ISNULL(CODE_FKR_D, ''),
		@TI_NAME = ISNULL(NAME_FKR_T, ''), @TI_CODE = ISNULL(CODE_FKR_T, ''),
		@VR_NAME = ISNULL(NAME_FKR_E, ''), @VR_CODE = ISNULL(CODE_FKR_E, ''),
		@NAME_PAY = ISNULL(NAME_PAY, ''), @CODE_PAY = ISNULL(CODE_PAY, ''),  
		@NAME_PAYR = ISNULL(NAME_PAYROLL, ''),
		@DATE_BEGIN = dbo.ConvertDMY2Date(1, month_base, year_base),
		@Year = YEAR_BASE,
		@Month = (SELECT m.mon FROM MONTHS M WHERE M.NUM = D.month_base),
		@MON  = D.month_base,
		@CARD_LINK = CARD_LINK
 	FROM DOCUMENTS_DED_PR_DGH D LEFT OUTER JOIN BI_DICTION_VKR F ON D.LINK_VKR = F.LINK_KBK
	WHERE 
		@nLink IS NOT NULL AND D.LINK = @nLink
		OR
		D.LINK = (SELECT TOP 1 LINK FROM DBO.BUFFER WHERE ID = @BUFFER_ID)

	SELECT 	@DATE_END = dbo.DateEndOfMonth(@DATE_BEGIN)

	SELECT PERS_LINK, LINK_DOC, LINK_EKR, SUM(SUMMA) AS SUMM
	INTO #SUM_EKR
 	FROM DBO.CALCULATE_JURNAL
	WHERE LINK_DOC = @nLink
	GROUP BY PERS_LINK, LINK_DOC, LINK_EKR 

/*+*/
--Ищем xml формат по названию, для xml нужна замена кавычек в названии организации на &quot;
declare @isxml bit
if exists (
		select top 1 * FROM
		dbo.SDOC S
		INNER JOIN dbo.SDOC_VEDOM SD ON S.LINK = SD.LINK_UP
		LEFT JOIN dbo.cards C ON SD.LINK_CARD = C.LINK and SD.LINK_CARD = @CARD_LINK
		LEFT JOIN dbo.S_BANK_FORMATS F ON F.LINK = C.FRMT_LINK
		where s.LINK = @nLink and f.NAME like '%xml%'
		)
set @isxml = 1
/*+*/

	INSERT INTO @res
	(
		LINK_DOC, 
		DOC_DATE, DOC_DATE1, EXCH_DATE,  DOC_NUM, 
		KASSIR, KASS_POST,KASS_PHONE,
		DIV_NAME, DIV_CODE,
		TI_NAME, TI_CODE,
		VR_NAME, VR_CODE,
		NAME_PAYR,
		name_pay, CODE_PAY,
		DATE_BEGIN, DATE_END, 
		[month], MON, [YEAR], 
		LINK_EMPL, 
		TN, 
		FIO, FM, IM, OT, S_FIO,INN,
		SUMMA, SUMMA1, 
		ACCT, BANK_LINK, BANK_NAME, BIK, DEP_ACCT,DEP_ACC_M,
		NOSB, NFSB, NDOG_SB, DATE_DOGSB,
		CARD_LINK, CARD_NAME, CARD_CODE, CARD_POSTF,
		POST,
		SERNUM,
		DEP_NAME, FULLNAME,
		PASSPORT,
		ADDRESS,
		PINDEX,
		PHONE,
		FD_CODE,
		FD_DATE,
		FD_ROVD,
		SUBDIV_CODE,
		SUBDIV,
		BIRTHDAY,
		ADDR,
	REGION, ABR_REGION, RAION, ABR_RAION, 
	GOROD, ABR_GOROD, NAS_PUNKT, ABR_NAS_PUNKT,
	ULICA, ABR_ULICA, DOM, KORPUS, KVARTIRA,
	DEP_INN, DEP_KPP, DEP_OKPO, DEP_OGRN,
	EXRT, EXRT_D, LINK_DEP, FRMT_LINK,
	DD, MM, YYYY, CODE_EKR, LINK_EKR,
	EKR_ANALIT, CODE_KBK, CODE_DT, CODE_KT, NOTE
	/*+*/, RND, [DATE], [TIME]
	)
	SELECT 
		@nLink, 
		@DOC_DATE, @DOC_DATE1, @EXCH_DATE, @DOC_NUM, 
		@KASSIR, @KASS_POST, LEFT(@KASS_PHONE,40),
		@DIV_NAME, @DIV_CODE,
		@TI_NAME, @TI_CODE,
		@VR_NAME, @VR_CODE,
		@NAME_PAYR,
		@NAME_PAY, @CODE_PAY,
		@DATE_BEGIN, @DATE_END, 
		@Month,@MON, @Year,
		D.PERS_LINK, 
  '',
		dbo.ku_GetPersFIO(D.PERS_LINK),
		P.FM, P.IM, P.OT,
		D.FIO, LEFT(p.INN,12),
		ISNULL(EKR.SUMM,ISNULL(DISBURS, 0)),
		LEFT(dbo.sa_convert_numeric_to_char(ISNULL(EKR.SUMM,ISNULL(DISBURS, 0)), 2, '.', ','),18),
		[acct] = ISNULL(PE.LIC_SCHET, '0'), 
		PE.BANK_LINK,
		[BANK_NAME] = (SELECT NAME FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),
		[BANK_CODE] = (SELECT BIK FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),
		[DEP_ACCT]  = (SELECT TOP 1 CODE FROM DICTIONARY_ACCOUNTS 
                       WHERE REF_LINK_B = PE.BANK_LINK 
						AND [TYPE_NAME] = 'РАСЧЕТНЫЙ' 
						AND REF_LINK_D = @DEP_LINK),
		[DEP_ACC_M]	 = (SELECT TOP 1 LEFT(CODE,20) FROM DICTIONARY_ACCOUNTS 
                      WHERE link = @DEP_ACC_M
						AND REF_LINK_D = @DEP_LINK),				
		[OSB] = ISNULL((SELECT OSB FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),''),
		[FILIAL] = 
			CASE WHEN NOT LTRIM(RTRIM(ISNULL(PE.FILIAL,''))) = '' 
				THEN PE.FILIAL
				ELSE ISNULL((SELECT top 1 LEFT(FILIAL,5) FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),'')
			END,
		[DOGOVOR] = 
			CASE WHEN NOT LTRIM(RTRIM(ISNULL(PE.DOGOVOR,''))) = '' 
				THEN PE.DOGOVOR
				ELSE ISNULL((SELECT top 1 LEFT(DOGOVOR,20) FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),'')
			END,
		[DATE_DOG] = ISNULL(PE.DATE_DOG,(SELECT DATE_DOG FROM dbo.BANKS WHERE LINK = PE.BANK_LINK)),
		PE.CARD_LINK, 
		[CARD_NAME] = (SELECT NAME FROM dbo.CARDS WHERE LINK = PE.CARD_LINK),
		[CARD_CODE] = (SELECT CODE FROM dbo.CARDS WHERE LINK = PE.CARD_LINK),
		[POSTFIX] = (SELECT POSTFIX FROM dbo.CARDS WHERE LINK = PE.CARD_LINK),
		'Внештатный сотрудник',
/*+*/	replace(LEFT(ISNULL(P.DOC_NUM, ''),20),' ',''),
/*+*/	case when @isxml = 1 then replace(LEFT(@ORGNAME,254),'"','&quot;') else LEFT(@ORGNAME,254) end, case when @isxml = 1 then replace(@ORGFULLNAME,'"','&quot;') else @ORGFULLNAME end,
		dbo.PrintSalaryGetPassportString(P.DOC_NUM, P.DOC_WHOM, P.DOC_DATE),
		dbo.GetAddressByFace(P.LINK, 0),
		'',
		ISNULL(P.PHONE_OFIC, ''),
		[FD_CODE] = (CASE WHEN COALESCE(FD.CODE,'') = '21' THEN '8' 
				  WHEN COALESCE(FD.CODE,'') = '01' THEN '1'
					ELSE COALESCE(FD.CODE,'') END), 
		[FD_DATE] = CONVERT(VARCHAR,P.DOC_DATE,3),
		[FD_ROVD] = P.DOC_WHOM,
		[SUBDIV_CODE]  = '',
		[SUBDIV]  = 'Внештатники',
		[BIRTHDAY] = CONVERT(VARCHAR,P.BIRTHDATE,3),
		[ADDR]   = dbo.GetAddressByKladr2(P.ADR_OFIC_LINK)+ ' '	+ ltrim(rtrim(house_ofic))+'-'+ltrim(rtrim(flat_ofic)),
		REGION = RTRIM(LTRIM(Left(dbo.SA_GET_WORD_NUM(ADDRESS2,3,','),len(dbo.SA_GET_WORD_NUM(ADDRESS2,3,','))-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,3,',')),1,' '))) ) )), 
		ABR_REGION = RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,3,',')),1,' ')) )), 
		RAION = RTRIM(LTRIM(Left(dbo.SA_GET_WORD_NUM(ADDRESS2,4,','),len(dbo.SA_GET_WORD_NUM(ADDRESS2,4,','))-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,4,',')),1,' '))) ) )), 
		ABR_RAION = RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,4,',')),1,' ')) )), 
		GOROD = RTRIM(LTRIM(Left(dbo.SA_GET_WORD_NUM(ADDRESS2,5,','),len(dbo.SA_GET_WORD_NUM(ADDRESS2,5,','))-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,5,',')),1,' '))) ) )),
		ABR_GOROD = RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,5,',')),1,' ')) )), 
		NAS_PUNKT = RTRIM(LTRIM(Left(dbo.SA_GET_WORD_NUM(ADDRESS2,6,','),len(dbo.SA_GET_WORD_NUM(ADDRESS2,6,','))-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,6,',')),1,' '))) ) )), 
		ABR_NAS_PUNKT = RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,6,',')),1,' ')) )),
		ULICA = RTRIM(LTRIM(Left(dbo.SA_GET_WORD_NUM(ADDRESS2,7,','),len(dbo.SA_GET_WORD_NUM(ADDRESS2,7,','))-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,7,',')),1,' '))) ) )),
		ABR_ULICA = RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,7,',')),1,' ')) )), 
		DOM = dbo.SA_GET_WORD_NUM(ADDRESS2,8,','), 
		KORPUS = dbo.SA_GET_WORD_NUM(ADDRESS2,9,','), 
		KVARTIRA = dbo.SA_GET_WORD_NUM(ADDRESS2,10,','),
		@DEP_INN, @DEP_KPP, @DEP_OKPO, @DEP_OGRN,
		EXRT = COALESCE(F.LastFileNumber,1),
		EXRT_D = COALESCE(FE.NUM_EXPORT,1),
		DOC.LINK_DEP,
		C.FRMT_LINK,
		DD = RIGHT('0' + CONVERT(VARCHAR(2),DAY(GETDATE())),2),
		MM = RIGHT('0' + CONVERT(VARCHAR(2),MONTH(GETDATE())),2),
		YYYY = CONVERT(VARCHAR(4),YEAR(GETDATE())),
		CODE_EKR = COALESCE(SGU.CODE,''), EKR.LINK_EKR,  -- Для вывода итого в по ЭКР
		EKR_ANALIT = D.CODE_EKR,
		D.CODE_KBK,
		D.CODE_DT ,
		D.CODE_KT,
		REPLACE(D.NOTE,';',' '),
/*+*/	RND = convert(varchar(16), left(replace(cast(CONVERT(binary(8), RAND(), 0) as uniqueidentifier),'-',''), 16)),
/*+*/	[DATE] = convert(varchar(8),getdATE(),112), --YYYYMMDD
/*+*/	[TIME] = replace(convert(varchar(8),getdATE(),108),':','') --HHMMSS		
    FROM 
		dbo.SDOC DOC 
		INNER JOIN #DOCUMENTS_DED_PR_TABLE_DGH1 D ON DOC.LINK = D.LINK
		INNER JOIN (Select *, dbo.GET_ADDRESS9PARTS(dbo.PERSON.LINK, 0) ADDRESS2  from dbo.PERSON) P ON D.PERS_LINK = P.LINK
		LEFT JOIN dbo.FACE_DOCUMENT FD ON P.DOC_LINK = FD.LINK	
		LEFT OUTER JOIN dbo.SA_PERSON_ECARD_ACTUAL PE ON (PE.PERS_LINK = P.LINK AND PE.CARD_LINK = @CARD_LINK)
		LEFT JOIN dbo.cards C ON PE.CARD_LINK = C.LINK
		LEFT JOIN dbo.S_BANK_FORMATS F ON F.LINK = C.FRMT_LINK
		LEFT JOIN dbo.S_BANK_FORMAT_EXPORT FE ON F.LINK = FE.LINK_UP AND FE.LINK_DEP = DOC.LINK_DEP
		LEFT JOIN #SUM_EKR EKR ON EKR.PERS_LINK = D.PERS_LINK AND DOC.link = EKR.LINK_DOC AND EXISTS (SELECT * FROM DBO.S_BANK_FORMAT_FILES F WHERE GRP_EKR = 1 AND F.LINK_FMT = C.FRMT_LINK)
		LEFT JOIN DBO.KOSGU SGU ON SGU.LINK = EKR.LINK_EKR
	WHERE 
		(D.LINK = @nLink AND @nLink IS NOT NULL
		OR
		D.LINK IN (SELECT LINK FROM DBO.BUFFER WHERE ID = @BUFFER_ID))
		AND
		ISNULL(D.DISBURS, 0) > 0 
	ORDER BY D.FIO

	UPDATE @res SET 
		PINDEX = LTRIM(RTRIM(LEFT(ADDRESS, 7))),
		ADDRESS= LTRIM(RTRIM(RIGHT(ADDRESS, LEN(ADDRESS)-7)))
	WHERE LEFT(ADDRESS, 1) IN (	'0', '1', '2', '3', '4', '5', '6', '7', '8', '9')

	UPDATE @res SET SUM_ALL = (SELECT SUM(SUMMA) FROM @res)
	UPDATE @res SET COUNT_OP = (SELECT COUNT(*)  FROM @res)

	CREATE TABLE #SUM_EKR1 (LINK_EKR INT, SUMMA NUMERIC(20,2), CNT INT )
	INSERT INTO #SUM_EKR1 (LINK_EKR, SUMMA, CNT)
	SELECT LINK_EKR, SUM(SUMM) AS SUMM, COUNT(LINK_EKR) as CNT_EKR FROM #SUM_EKR
	GROUP BY LINK_EKR

	SELECT 
		R.*, NPP_G = NPP,
		GRP_EKR = CASE WHEN EK.SUMMA IS NULL THEN 0 ELSE 1 END,
		ITOG_EKR = COALESCE(EK.SUMMA,0),
		KOL_ST_EKR = COALESCE(EK.CNT,0) 
	FROM 
		@res R  LEFT JOIN #SUM_EKR1 EK ON R.LINK_EKR = EK.LINK_EKR
	ORDER BY 
		NPP

	SELECT NDOG_SB, NOSB, NFSB, COUNT(*) AS COUNT_OP, SUM(SUMMA) AS SUMMA_ALL 
	INTO #RES1
	FROM @res
	GROUP BY NDOG_SB, NOSB, NFSB
	ORDER BY 1, 2, 3
	
	SELECT @ORGNAME AS ORGNAME, * FROM #RES1
	ORDER BY 1, 2, 3, 4

END


GO


GRANT EXECUTE ON dbo.[SD_REP_VEDOM_DGH_PREPARE_DATA] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_REP_VEDOM_PREPARE_DATA]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_REP_VEDOM_PREPARE_DATA]

GO

CREATE     PROCEDURE dbo.SD_REP_VEDOM_PREPARE_DATA 
	@nLink INT = NULL, @BUFFER_ID VARCHAR(20) = NULL
AS

BEGIN

DECLARE @str VARCHAR(7000), 
		@nMode INT,
		@SortMode INT,
		@GroupMode INT,
		@WrapMode INT,
		@FIOShort tinyint

DECLARE @SPISOK_VEDOM TABLE (LINK INT)
INSERT INTO @SPISOK_VEDOM (LINK)
SELECT LINK FROM DBO.BUFFER WITH (NOLOCK) WHERE ID = @BUFFER_ID

IF @nLink IS NOT NULL AND NOT EXISTS (SELECT * FROM @SPISOK_VEDOM WHERE LINK = @nLink)
	INSERT INTO @SPISOK_VEDOM (LINK) VALUES (@nLink)

IF @BUFFER_ID IS NOT NULL
	SET @nLink = NULL
IF COALESCE((SELECT COUNT(*) FROM @SPISOK_VEDOM),0) =1
	SET @nLink = (SELECT LINK FROM @SPISOK_VEDOM)
		
/* Читаем настройки сортировки  1 - по фио, 2 - по табельному номеру, 3 - по коду должности */
SELECT top 1 @SortMode = ISNULL(CONVERT(INT,VALUE),1) 
FROM S_OPTIONS 
WHERE OBJECT = (SELECT top 1 LINK FROM S_OBJECTS WHERE CODE = 'VEDOM_OPTIONS_VEDOM_SORT') AND SID IS NULL

/* Читаем настройки переноса */
SELECT top 1 @WrapMode = ISNULL(CONVERT(INT,VALUE),0)
FROM S_OPTIONS 
WHERE OBJECT = (SELECT top 1 LINK FROM S_OBJECTS WHERE CODE = 'VEDOM_OPTIONS_VEDOM_PERENOS') AND SID IS NULL

/* Читаем настройки группировки */
SELECT top 1 @GroupMode = (CASE WHEN ISNULL(CONVERT(INT,VALUE),0) = 0 THEN @WrapMode else ISNULL(CONVERT(INT,VALUE),0) END)
FROM S_OPTIONS 
WHERE OBJECT = (SELECT top 1 LINK FROM S_OBJECTS WHERE CODE = 'VEDOM_OPTIONS_VEDOM_GROUP') AND SID IS NULL

SET @str = DBO.OBJECT_VAR_GET_OBJECT_VALUE('SALARY_QUERY_PAYROLL_N3','QUERY_NASTR_VALUE',1)
/* Выбирается вариант сортировки */
SET @nMode = CASE WHEN @str = 'ФИО' THEN 2 ELSE 1 END 

CREATE TABLE #SDOC_VEDOM_TABLE1 (LINK_UP INT, LINK_EMPL INT, LINK_SFIN INT, LINK_EKR INT, ORDERS INT, DISBURS NUMERIC(18,2), 
		CODE_EKR VARCHAR(3), CODE_KBK VARCHAR(30), CODE_DT VARCHAR(13), CODE_KT VARCHAR(13), NOTE VARCHAR(254))

INSERT INTO 
	#SDOC_VEDOM_TABLE1 (LINK_UP, LINK_EMPL, ORDERS, DISBURS , NOTE )
SELECT 
	LINK_UP, LINK_EMPL, ORDERS = MAX(ORDERS), DISBURS = SUM(DISBURS) , ltrim(rtrim(NOTE))
FROM 
	dbo.SDOC_VEDOM_TABLE1 D
WHERE 
	(D.LINK_UP = @nLink AND @nLink IS NOT NULL
	OR
	D.LINK_UP IN (SELECT LINK FROM @SPISOK_VEDOM))
GROUP BY 
	LINK_UP, LINK_EMPL, NOTE

--Для каждой ведомости определяются КБК и корреспондирующие счета
--Но только если указан конкретный источник и ЭКР в ведомости
DECLARE @CUR_ACC CURSOR, @LINK_VEDOM INT, @KBK_CODE VARCHAR(30), @EKR_CODE VARCHAR(3), @DT_CODE VARCHAR(40), @KT_CODE VARCHAR(40)

SET @CUR_ACC = CURSOR FORWARD_ONLY
FOR SELECT LINK FROM @SPISOK_VEDOM
OPEN @CUR_ACC
FETCH NEXT FROM @CUR_ACC INTO @LINK_VEDOM
WHILE (@@FETCH_STATUS <> -1)
BEGIN
	IF (@@FETCH_STATUS <> -2)
	BEGIN

		EXEC dbo.[SA_VEDOM_ACCOUNTS] @LINK_VEDOM = @LINK_VEDOM, @KBK_CODE = @KBK_CODE OUTPUT, @EKR_CODE = @EKR_CODE OUTPUT, @DT_CODE = @DT_CODE OUTPUT, @KT_CODE = @KT_CODE OUTPUT
		
		UPDATE #SDOC_VEDOM_TABLE1
		SET CODE_KBK = @KBK_CODE ,  CODE_EKR = @EKR_CODE, CODE_DT = @DT_CODE, CODE_KT = @KT_CODE
		WHERE LINK_UP = @LINK_VEDOM
	END
	FETCH NEXT FROM @CUR_ACC INTO @LINK_VEDOM
END

CLOSE @CUR_ACC
DEALLOCATE @CUR_ACC


------------------------------------------------------------------
DECLARE @res TABLE (
		LINK_DOC INT,DOC_DATE DATETIME, DOC_DATE1 varchar(10), EXCH_DATE datetime, DOC_NUM VARCHAR(60), 
		KASSIR VARCHAR(120), KASS_POST VARCHAR(254), KASS_PHONE VARCHAR(40),
		DIV_NAME VARCHAR(254), DIV_CODE VARCHAR(10),
		TI_NAME VARCHAR(254), TI_CODE VARCHAR(10),
		VR_NAME VARCHAR(254), VR_CODE VARCHAR(10),
		NAME_PAYR VARCHAR(254),
		NAME_PAY VARCHAR(120), CODE_PAY VARCHAR(10),
		DATE_BEGIN DATETIME, DATE_END DATETIME, 
		[MONTH] VARCHAR(20) , MON int, [YEAR] VARCHAR(4), 
		NPP INT IDENTITY,
		LINK_EMPL INT, 
		TN VARCHAR(15), 
		FIO VARCHAR(254),
		S_FIO VARCHAR(100),
		FM VARCHAR(50), 
		IM VARCHAR(50), 
		OT VARCHAR(50), 
		INN VARCHAR(12),
		SUMMA NUMERIC(15,2),
		SUMMA1 VARCHAR(18), 
		ACCT VARCHAR(254), 
		ACCT_V VARCHAR(254), 
		BANK_LINK INT, BANK_NAME VARCHAR(254), BIK VARCHAR(9), DEP_ACCT VARCHAR(30), DEP_ACC_M VARCHAR(20),
		CARD_LINK INT, CARD_NAME VARCHAR(254), CARD_CODE VARCHAR(3), CARD_POSTF VARCHAR(2),
		NOSB VARCHAR(4), NFSB VARCHAR(5), NDOG_SB VARCHAR(20), DATE_DOGSB datetime,
		POST_CODE VARCHAR(10),
		POST VARCHAR(254),
		OKLAD NUMERIC(15,0),
		STAKE NUMERIC(5,2),
		DAYS_W numeric (3,0),
		HOURS_W numeric (3,0),
		DAYS_H numeric (3,0),
		HOURS_H numeric (3,0),
		SERNUM VARCHAR(20),
		SUM_ALL NUMERIC(20,2), COUNT_OP INT,
		DEP_NAME VARCHAR(254), FULLNAME VARCHAR(2000),
		PASSPORT VARCHAR(254),
		ADDRESS VARCHAR(254),
		PINDEX VARCHAR(10),
		PHONE VARCHAR(20),
		FD_CODE varchar(2),
		FD_DATE varchar(8),
		FD_ROVD varchar(254),
		SUBDIV_CODE varchar(20),
		SUBDIV varchar(254),
		BIRTHDAY varchar(8),
		ADDR varchar(254),
		shild int,
		REGION  VARCHAR(120), ABR_REGION  VARCHAR(12),
		RAION   VARCHAR(120), ABR_RAION  VARCHAR(12),
		GOROD	VARCHAR(50), ABR_GOROD  VARCHAR(12),
		NAS_PUNKT   VARCHAR(120), ABR_NAS_PUNKT  VARCHAR(12),
		ULICA	VARCHAR(120), ABR_ULICA  VARCHAR(12),
		DOM	VARCHAR(5), KORPUS VARCHAR(5), KVARTIRA VARCHAR(5),
		DEP_INN VARCHAR(12), DEP_KPP VARCHAR(9), DEP_OKPO VARCHAR(20), DEP_OGRN VARCHAR(13),
		EXRT INT, EXRT_D INT, LINK_DEP INT, FRMT_LINK INT,
		DD VARCHAR(2), MM VARCHAR(2), YYYY VARCHAR(4),
		CODE_EKR VARCHAR(3), LINK_EKR INT,
		EKR_ANALIT VARCHAR(3),
		CODE_KBK VARCHAR(30),
		CODE_DT VARCHAR(13),
		CODE_KT VARCHAR(13),
		NOTE VARCHAR(254),
/*+*/	RND varchar(16), [DATE] varchar(8), [TIME] varchar(8) 
	)

	DECLARE 
		@ORGNAME VARCHAR(254), @DEP_LINK INT, @ORGFULLNAME VARCHAR(2000),
		@DOC_DATE DATETIME, @DOC_DATE1 varchar(10) ,@EXCH_DATE datetime, @DOC_NUM VARCHAR(60), 
		@DOC_DT_BEG DATETIME, @DOC_DT_END DATETIME,
		@KASSIR VARCHAR(254), @KASS_POST VARCHAR(254),@KASS_PHONE VARCHAR(40),
		@DIV_NAME VARCHAR(254), @DIV_CODE VARCHAR(10),
		@TI_NAME VARCHAR(254), @TI_CODE VARCHAR(10),
		@VR_NAME VARCHAR(254), @VR_CODE VARCHAR(10),
		@NAME_PAY VARCHAR(254), @CODE_PAY VARCHAR(10), @NAME_PAYR VARCHAR(254),
		@DATE_BEGIN DATETIME, @DATE_END DATETIME,
		@Month VARCHAR(20), @MON int, @Year VARCHAR(4),
		@DEP_ACCT VARCHAR(30),@DEP_ACC_M VARCHAR(20),
		@CARD_LINK int, @DEP_INN VARCHAR(12), @DEP_KPP VARCHAR(9), @DEP_OKPO VARCHAR(20), @DEP_OGRN VARCHAR(13),
		@TYPE_DAYS  int 

	SET @TYPE_DAYS = (select top 1 link  from TYP_DAYS  where name = 'Выходные и праздничные'	)
	SELECT  top 1 
			@ORGNAME 	= LEFT(DEP.[NAME],254),
			@ORGFULLNAME  = LEFT(DEP.[FULL_NAME],2000),
			@DEP_LINK 	= DEP.LINK,
			@DEP_INN = LEFT(INN,12), @DEP_KPP = LEFT(KPP,9), @DEP_OKPO = LEFT(OKPO,20), @DEP_OGRN = LEFT(OGRN,13) , @DEP_ACC_M = DEP.MAIN_LINK,
			@EXCH_DATE = getdate()
	FROM dbo.DICTIONARY_DEPARTMENT DEP, USER_DEP UI WHERE DEP.LINK = UI.DEP_LINK

	---		
	SELECT top 1 
		@DOC_DATE = S.[DATE],
		@DOC_DATE1 = convert(varchar(10), S.[DATE], 103) ,
		@DOC_DT_BEG = S.DATE_CALC, 
		@DOC_DT_END = S.[DATE],
		@DOC_NUM = LEFT(S.NUMBER,60),
		@KASSIR = LEFT(ISNULL(dbo.sd_GetEmplName(SD.REF_KASSIR), 0),254),
		@KASS_POST = LEFT(dbo.ku_GetEmplPostName(SD.REF_KASSIR,DEFAULT),254),
		@KASS_PHONE = LEFT((SELECT top 1 PHONE_WORK from KU_EMPL_PLACING WHERE LINK = SD.REF_KASSIR),40),
		@DIV_NAME = LEFT(ISNULL(F.NAME_FKR_D, ''),254), 
		@DIV_CODE = LEFT(ISNULL(F.CODE_FKR_D, ''),10),
		@TI_NAME = LEFT(ISNULL(F.NAME_FKR_T, ''),254), 
		@TI_CODE = LEFT(ISNULL(F.CODE_FKR_T, ''),0),
		@VR_NAME = LEFT(ISNULL(F.NAME_FKR_E, ''),254), 
		@VR_CODE = LEFT(ISNULL(F.CODE_FKR_E, ''),0),
		@NAME_PAY = LEFT(ISNULL(P.NAME, ''),254), 
		@CODE_PAY = LEFT(ISNULL(P.CODE, ''),10),  
		@NAME_PAYR = LEFT(ISNULL(SD.NAME_PR, ''),254),
		@DATE_BEGIN = dbo.ConvertDMY2Date(1, MONTH(S.DATE_CALC), YEAR(S.DATE_CALC)),
		@Year = YEAR(S.DATE_CALC),
		@Month = (SELECT top 1 m.mon FROM MONTHS M WHERE M.NUM = MONTH(S.DATE_CALC)),
		@MON = MONTH(S.DATE_CALC),
		@CARD_LINK = SD.LINK_CARD
	FROM 
		dbo.SDOC S 
		INNER JOIN dbo.SDOC_VEDOM SD ON S.LINK = SD.LINK_UP
		LEFT JOIN dbo.PAYS P On SD.LINK_PAY = P.LINK
		LEFT JOIN dbo.DICTIONARY_ITEM DI on DI.link = SD.LINK_EKR
		LEFT OUTER JOIN BI_DICTION_VKR F ON SD.LINK_VKR = F.LINK_KBK
	WHERE 
		@nLink IS NOT NULL AND S.LINK = @nLink
		OR
		S.LINK = (SELECT TOP 1 LINK FROM @SPISOK_VEDOM)

	----
	SET 	@DATE_END = dbo.DateEndOfMonth(@DATE_BEGIN)

/*+*/
--Ищем xml формат по названию, для xml нужна замена кавычек в названии организации на &quot;
declare @isxml bit
if exists (
		select top 1 * FROM
		dbo.SDOC S
		INNER JOIN dbo.SDOC_VEDOM SD ON S.LINK = SD.LINK_UP
		LEFT JOIN dbo.cards C ON SD.LINK_CARD = C.LINK and SD.LINK_CARD = @CARD_LINK
		LEFT JOIN dbo.S_BANK_FORMATS F ON F.LINK = C.FRMT_LINK
		where s.LINK = @nLink and f.NAME like '%xml%'
		)
set @isxml = 1
/*+*/
--Выводить вместо подписи лицевой счёт
DECLARE @VEDOM_OPTIONS_2_12 INT
SET @VEDOM_OPTIONS_2_12 = dbo.SA_GET_OPTION_BY_CODE ('VEDOM_OPTIONS_2_12')

SELECT LINK_EMPL, LINK_DOC, LINK_EKR, SUM(SUMMA) AS SUMM
	INTO #SUM_EKR
	FROM DBO.CALCULATE_JURNAL
	WHERE LINK_DOC IN (SELECT LINK_UP FROM #SDOC_VEDOM_TABLE1 )
	GROUP BY LINK_EMPL, LINK_DOC, LINK_EKR 


	INSERT INTO @res
	(LINK_DOC,DOC_DATE, DOC_DATE1, EXCH_DATE, DOC_NUM, 
  	 KASSIR, KASS_POST,KASS_PHONE,
	 DIV_NAME, DIV_CODE,TI_NAME, TI_CODE,VR_NAME, VR_CODE,
  	 NAME_PAYR,
	 NAME_PAY,CODE_PAY,
  	 DATE_BEGIN, DATE_END, 
	 [MONTH], MON, [YEAR],
  	 LINK_EMPL,TN,FIO, FM, IM, OT, S_FIO, INN,
 	 SUMMA, SUMMA1, 
	 ACCT,ACCT_V, BANK_LINK, BANK_NAME, BIK, DEP_ACCT,DEP_ACC_M,
 	 NOSB, NFSB, NDOG_SB, DATE_DOGSB,
	 CARD_LINK, CARD_NAME, CARD_CODE, CARD_POSTF,
 	 POST_CODE,
	 POST,
	 OKLAD ,
	 STAKE ,
	 DAYS_W,
	 HOURS_W,
	 DAYS_H,
	 HOURS_H,
	 SERNUM,
	 DEP_NAME, FULLNAME,
	 PASSPORT,
	 ADDRESS,PINDEX,PHONE,
 	 FD_CODE,FD_DATE,FD_ROVD,
	 SUBDIV_CODE,	
	 SUBDIV,
	 BIRTHDAY,
	 ADDR,
	REGION, ABR_REGION, RAION, ABR_RAION, 
	GOROD, ABR_GOROD, NAS_PUNKT, ABR_NAS_PUNKT,
	ULICA, ABR_ULICA, DOM, KORPUS, KVARTIRA,
	DEP_INN, DEP_KPP, DEP_OKPO, DEP_OGRN, 
	EXRT, EXRT_D, LINK_DEP, FRMT_LINK,
	DD, MM, YYYY, CODE_EKR, LINK_EKR, 
	EKR_ANALIT, CODE_KBK, CODE_DT, CODE_KT, NOTE
/*+*/, RND, [DATE], [TIME]
)
	

	SELECT 
		@nLink, 
		@DOC_DATE, @DOC_DATE1, @EXCH_DATE,  LEFT(@DOC_NUM,60), 
		LEFT(@KASSIR,120), LEFT(@KASS_POST,254),
		LEFT(@KASS_PHONE,40),
		LEFT(@DIV_NAME,254), LEFT(@DIV_CODE,10),
		LEFT(@TI_NAME,254), LEFT(@TI_CODE,10),
		LEFT(@VR_NAME,254), LEFT(@VR_CODE,10),
		LEFT(@NAME_PAYR,254),
		LEFT(@NAME_PAY,120), LEFT(@CODE_PAY,10),
		@DATE_BEGIN, @DATE_END, 
		@Month, @MON,  @Year,
		D.LINK_EMPL, 
        LEFT(E.TAB,15),
		LEFT(ISNULL((SELECT LTRIM(RTRIM(E.FM)) + ' ' + LTRIM(RTRIM(E.IM)) + ' ' +  LTRIM(RTRIM(E.OT))),'Не заполнено'),254),
		LEFT(E.FM,50), LEFT(E.IM,50), LEFT(E.OT,50),
		LEFT(E.FIO,100), LEFT(E.INN,12),
		ISNULL(EKR.SUMM,ISNULL(DISBURS, 0)),
		LEFT(dbo.sa_convert_numeric_to_char(ISNULL(EKR.SUMM,ISNULL(DISBURS, 0)), 2, '.', ','),18),
		[acct] = LEFT(ISNULL(PE.LIC_SCHET, '0'),254), 
		ACCT_V = CASE WHEN @VEDOM_OPTIONS_2_12 = 0 THEN '0' ELSE LEFT(ISNULL(PE.LIC_SCHET, '0'),254) END, 
		PE.BANK_LINK,
		[BANK_NAME] = (SELECT top 1 LEFT([NAME],254) FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),
		[BANK_BIK] =  (SELECT top 1 LEFT(BIK,9) FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),
		[DEP_ACCT]  = (SELECT TOP 1 LEFT(CODE,30) FROM DICTIONARY_ACCOUNTS 
                      WHERE REF_LINK_B = PE.BANK_LINK 
						AND [TYPE_NAME] = 'РАСЧЕТНЫЙ' 
						AND REF_LINK_D = @DEP_LINK),
		[DEP_ACC_M]	 = (SELECT TOP 1 LEFT(CODE,20) FROM DICTIONARY_ACCOUNTS 
                      WHERE link = @DEP_ACC_M
						AND REF_LINK_D = @DEP_LINK),			
						
		[OSB] = ISNULL((SELECT top 1 LEFT(OSB,4) FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),''),
		[FILIAL] = 
			CASE WHEN NOT LTRIM(RTRIM(ISNULL(PE.FILIAL,''))) = '' 
				THEN PE.FILIAL
				ELSE ISNULL((SELECT top 1 LEFT(FILIAL,5) FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),'')
			END,
		[DOGOVOR] = 
			CASE WHEN NOT LTRIM(RTRIM(ISNULL(PE.DOGOVOR,''))) = '' 
				THEN PE.DOGOVOR
				ELSE ISNULL((SELECT top 1 LEFT(DOGOVOR,20) FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),'')
			END,		
		[DATE_DOG] = ISNULL(PE.DATE_DOG,(SELECT top 1 DATE_DOG FROM dbo.BANKS WHERE LINK = PE.BANK_LINK)),
		PE.CARD_LINK, 
		[CARD_NAME] = (SELECT top 1 LEFT([NAME],254) FROM dbo.CARDS WHERE LINK = PE.CARD_LINK),
		[CARD_CODE] = (SELECT top 1 LEFT(CODE,3) FROM dbo.CARDS WHERE LINK = PE.CARD_LINK),
		[POSTFIX] =  (SELECT top 1 LEFT(POSTFIX,2) FROM dbo.CARDS WHERE LINK = PE.CARD_LINK),
		LEFT(E.POST_CODE,10),
		LEFT(E.POST_NAME,254),
		OKLAD = (select  sum(summa)	
				    FROM KJ_MONEY_PERIOD MP 
					INNER JOIN PAYS P ON MP.PAY_LINK=P.LINK
					where
					convert(datetime,'20120808') between mp.date_begin and isnull(mp.date_end,'20990101')
					and	
					P.WAY_CALC = 1
					and MP.EMPL_LINK = d.link_empl
					group by
					MP.EMPL_LINK
				   )	,
		STAKE =  (select TOP 1 num_stake from DBO.SA_EMPLS_INFO(@DOC_DT_BEG, default) where empl_link = d.link_empl ),
		DAYS_W = (dbo.SA_GET_EMPL_WD (D.LINK_EMPL, 0, DEFAULT, dbo.ConvertDMY2Date(1,month(@DOC_DT_BEG),year(@DOC_DT_BEG)), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,month(@DOC_DT_BEG),year(@DOC_DT_BEG))), DEFAULT, 0)),
		HOURS_W = (dbo.SA_GET_EMPL_WH (D.LINK_EMPL, 0, DEFAULT,  dbo.ConvertDMY2Date(1,month(@DOC_DT_BEG),year(@DOC_DT_BEG)), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,month(@DOC_DT_BEG),year(@DOC_DT_BEG))), DEFAULT, 0)) ,
		DAYS_H = (dbo.SA_GET_EMPL_WD (D.LINK_EMPL, 0, DEFAULT,  dbo.ConvertDMY2Date(1,month(@DOC_DT_BEG),year(@DOC_DT_BEG)), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,month(@DOC_DT_BEG),year(@DOC_DT_BEG))), DEFAULT, @TYPE_DAYS)) ,
		HOURS_H = (dbo.SA_GET_EMPL_WH (D.LINK_EMPL, 0, DEFAULT,  dbo.ConvertDMY2Date(1,month(@DOC_DT_BEG),year(@DOC_DT_BEG)), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,month(@DOC_DT_BEG),year(@DOC_DT_BEG))), DEFAULT, @TYPE_DAYS)),
/*+*/	replace(LEFT(ISNULL(P.DOC_NUM, ''),20),' ',''),
/*+*/	case when @isxml = 1 then replace(LEFT(@ORGNAME,254),'"','&quot;') else LEFT(@ORGNAME,254) end, case when @isxml = 1 then replace(@ORGFULLNAME,'"','&quot;') else @ORGFULLNAME end,
		LEFT(dbo.PrintSalaryGetPassportString(P.DOC_NUM, P.DOC_WHOM, P.DOC_DATE),254),
		LEFT(dbo.GetAddressByFace(P.LINK, 0),254),
		'',
		LEFT(ISNULL(P.PHONE_OFIC, ''),10),
		[FD_CODE] = (CASE WHEN FD.CODE = '21' THEN '8' 
				  WHEN FD.CODE = '01' THEN '1'
					ELSE LEFT(FD.CODE,2) END), 
		[FD_DATE] = LEFT(CONVERT(VARCHAR,P.DOC_DATE,3),8),
		[FD_ROVD] = LEFT(P.DOC_WHOM,254),
		[SUBDIV]  = LEFT(COALESCE(E.SUBDIV_CODE,''),20),
		[SUBDIV]  = LEFT(COALESCE(E.SUBDIV_NAME,''),254),
		[BIRTHDAY] = LEFT(CONVERT(VARCHAR,P.BIRTHDATE,3),8),
		[ADDR]   = LEFT(dbo.GetAddressByKladr2(P.ADR_OFIC_LINK)+ ' '	+ ltrim(rtrim(house_ofic))+'-'+ltrim(rtrim(flat_ofic)),254),
		REGION = LEFT(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,' '))) ) )),120), 
		ABR_REGION = LEFT(RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,3,',')),1,' ')) )), 12),
		RAION = LEFT(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,' '))) ) )), 120),
		ABR_RAION = LEFT(RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,4,',')),1,' ')) )), 12),
		GOROD = LEFT(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,' '))) ) )),50),
		ABR_GOROD = LEFT(RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,5,',')),1,' ')) )), 12),
		NAS_PUNKT = LEFT(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,' '))) ) )), 120),
		ABR_NAS_PUNKT = LEFT(RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,6,',')),1,' ')) )),12),
		ULICA = LEFT(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,' '))) ) )),120),
		ABR_ULICA = LEFT(RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,7,',')),1,' ')) )), 12),
		DOM = LEFT(dbo.SA_GET_WORD_NUM(ADDRESS2,8,','), 5),
		KORPUS = LEFT(dbo.SA_GET_WORD_NUM(ADDRESS2,9,','), 5),
		KVARTIRA = LEFT(dbo.SA_GET_WORD_NUM(ADDRESS2,10,','),5),
		LEFT(@DEP_INN,12), LEFT(@DEP_KPP,9), LEFT(@DEP_OKPO,20), LEFT(@DEP_OGRN,13),
		EXRT = COALESCE(F.LastFileNumber,1),
		EXRT_D = COALESCE(FE.NUM_EXPORT,1),
		DOC.LINK_DEP,
		C.FRMT_LINK,
		DD = RIGHT('0' + CONVERT(VARCHAR(2),DAY(GETDATE())),2),
		MM = RIGHT('0' + CONVERT(VARCHAR(2),MONTH(GETDATE())),2),
		YYYY = CONVERT(VARCHAR(4),YEAR(GETDATE())),
		CODE_EKR = COALESCE(SGU.CODE,''), EKR.LINK_EKR,  --Для вывода итогов по ЭКР
		EKR_ANALIT = D.CODE_EKR,
		D.CODE_KBK,
		D.CODE_DT,
		D.CODE_KT,
		REPLACE(D.NOTE,';',' '),
/*+*/	RND = convert(varchar(16), left(replace(cast(CONVERT(binary(8), RAND(), 0) as uniqueidentifier),'-',''), 16)),
/*+*/	[DATE] = convert(varchar(8),getdATE(),112), --YYYYMMDD
/*+*/	[TIME] = replace(convert(varchar(8),getdATE(),108),':','') --HHMMSS

	FROM
		dbo.SDOC DOC 
		INNER JOIN #SDOC_VEDOM_TABLE1 D on DOC.link = D.link_up
		INNER JOIN dbo.SD_EMPL E ON E.LINK = D.LINK_EMPL
		INNER JOIN (Select *, dbo.GET_ADDRESS9PARTS(dbo.PERSON.LINK, 0) ADDRESS2 from dbo.PERSON) P ON E.PERS_LINK = P.LINK
		LEFT OUTER JOIN dbo.FACE_DOCUMENT FD ON P.DOC_LINK = FD.LINK	
		LEFT OUTER JOIN dbo.SA_PERSON_ECARD_ACTUAL PE ON (PE.PERS_LINK = P.LINK AND PE.CARD_LINK = @CARD_LINK)
		LEFT JOIN dbo.cards C ON PE.CARD_LINK = C.LINK
		LEFT JOIN dbo.S_BANK_FORMATS F ON F.LINK = C.FRMT_LINK
		LEFT JOIN dbo.S_BANK_FORMAT_EXPORT FE ON F.LINK = FE.LINK_UP AND FE.LINK_DEP = DOC.LINK_DEP
		LEFT JOIN #SUM_EKR EKR ON EKR.LINK_EMPL = D.LINK_EMPL AND DOC.link = EKR.LINK_DOC AND EXISTS (SELECT * FROM DBO.S_BANK_FORMAT_FILES FF WHERE GRP_EKR = 1 AND FF.LINK_FMT = F.LINK)
		LEFT JOIN DBO.KOSGU SGU ON SGU.LINK = EKR.LINK_EKR
	WHERE 
		ISNULL(EKR.SUMM,ISNULL(D.DISBURS, 0)) > 0 
	ORDER BY CASE 
		WHEN @GroupMode = 1 THEN E.SUBDIV_CODE
		ELSE '' END,
	CASE 	
		WHEN @SortMode = 1 THEN E.FM
		WHEN @SortMode = 2 THEN E.TAB
		WHEN @SortMode = 3 THEN E.POST_CODE
		ELSE CAST(D.ORDERS AS VARCHAR(10))
	END

	UPDATE @res SET 
		PINDEX = LTRIM(RTRIM(LEFT(ADDRESS, 7))),
		ADDRESS= LTRIM(RTRIM(RIGHT(ADDRESS, LEN(ADDRESS)-7)))
	WHERE LEFT(ADDRESS, 1) IN (	'0', '1', '2', '3', '4', '5', '6', '7', '8', '9')

	UPDATE @res SET SUM_ALL = (SELECT SUM(SUMMA) FROM @res)
	UPDATE @res SET COUNT_OP = (SELECT COUNT(*)  FROM @res)

	CREATE TABLE #SUM_EKR1 (LINK_EKR INT, SUMMA NUMERIC(20,2), CNT INT )
	INSERT INTO #SUM_EKR1 (LINK_EKR, SUMMA, CNT)
	SELECT LINK_EKR, SUM(SUMM) AS SUMM, COUNT(LINK_EKR) as CNT_EKR FROM #SUM_EKR
	GROUP BY LINK_EKR

	SELECT R.*, 
		NPP_G= (Case when @GroupMode = 1 then (Select count(NPP) from @res RC where COALESCE(RC.SUBDIV_CODE,'') = COALESCE(R.SUBDIV_CODE,'') and RC.NPP <= R.NPP) else R.NPP end),
		GRP_EKR = CASE WHEN EK.SUMMA IS NULL THEN 0 ELSE 1 END,
		ITOG_EKR = COALESCE(EK.SUMMA,0),
		KOL_ST_EKR = COALESCE(EK.CNT,0)
	FROM 
		@res R LEFT JOIN #SUM_EKR1 EK ON R.LINK_EKR = EK.LINK_EKR
	ORDER BY CODE_EKR, NPP

	SELECT NDOG_SB, NOSB, NFSB, COUNT(*) AS COUNT_OP, SUM(SUMMA) AS SUMMA_ALL 
	INTO #RES1
	FROM @res
	GROUP BY NDOG_SB, NOSB, NFSB
	ORDER BY 1, 2, 3
	
	SELECT @ORGNAME AS ORGNAME, * FROM #RES1
	ORDER BY 1, 2, 3, 4

END



GO


GRANT EXECUTE ON dbo.[SD_REP_VEDOM_PREPARE_DATA] TO PUBLIC

GO
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SZV_K_PACHKA_FILL]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZV_K_PACHKA_FILL]

GO

CREATE  PROCEDURE [dbo].SA_SZV_K_PACHKA_FILL(@y int, @m int, @mode tinyint)
AS


declare @EndYear datetime
Set @EndYear = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@m,@y))

declare @DEP_LINK int
exec dbo.xd_whats_zb @DEP_LINK output

DECLARE @MONTH_END TINYINT, @MONTH_BEG TINYINT


DECLARE @PeriodBegin datetime

IF @y < 2010
BEGIN
	SET @MONTH_BEG = 1
	SET @MONTH_END = (CASE WHEN @MONTH_END < 12 THEN @MONTH_END ELSE 12 END)
END

IF @y = 2010
BEGIN
	--SET @MONTH_BEG = (CASE WHEN @m <= 6 THEN 1 ELSE 7 END)
	SET @MONTH_BEG = 1
	SET @MONTH_END = (CASE WHEN @MONTH_END < (@MONTH_BEG+6-1) THEN @MONTH_END ELSE (@MONTH_BEG+6-1) END)
END

IF @y > 2010
BEGIN
	--SET @MONTH_BEG = (CASE @m WHEN 1 THEN 1 WHEN 2 THEN 1 WHEN 3 THEN 1
	--						WHEN 4 THEN 4 WHEN 5 THEN 4 WHEN 6 THEN 4
	--						WHEN 7 THEN 7 WHEN 8 THEN 7 WHEN 9 THEN 7
	--						WHEN 10 THEN 10 WHEN 11 THEN 10 WHEN 12 THEN 10
	--					END)
	SET @MONTH_BEG = 1
	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)


SELECT 0 as CHECKED, E.pers_link, NAME_EMPL = dbo.ku_getPersFio(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 <= @EndYear
	and
	coalesce(U.DIS_DATE,'20990101') >= @PeriodBegin
	And 
	E.DEP_LINK = @DEP_LINK
	And
	Coalesce(@mode,0) = 1
UNION 
Select 
	0 as CHECKED, pers_link = DFG.link, NAME_EMPL = dbo.ku_getPersFio(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  @PeriodBegin and @EndYear
						or ISNULL(DATE2, '20990101') between  @PeriodBegin and @EndYear
					)
				)
	And 
	DGH.DEP_LINK = @DEP_LINK
	And
	Coalesce(@mode,0) = 2
ORDER BY pers_link

GO


GRANT EXECUTE ON dbo.[SA_SZV_K_PACHKA_FILL] 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(CJ.SUMMA) AS SUMMA 
	FROM 
		DBO.SDOC S 
		INNER JOIN DBO.SDOC_TISP SD ON S.LINK = SD.LINK_UP
		INNER JOIN dbo.CALCULATE_JURNAL CJ ON CJ.LINK_DOC = S.LINK
	WHERE 
		SD.REF_DOC = @REF_DOC
		AND
		S.FLAG_JC = 1
		AND
		(YEAR(S.[DATE]) * 100 + MONTH(S.[DATE])) <= (YEAR(@Date1) * 100 + MONTH(@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
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_CREATE_PP]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_CREATE_PP]

GO

CREATE  PROCEDURE [dbo].[SA_CREATE_PP]
			@LINK_PP int OUTPUT,
			@LINK_DOC int,
			@DATE_DOC DATETIME,
			@P TINYINT = 0 -- Признак для подавления проверки на существование платежек
					-- Проверка выполняется в другом месте
			,@CLEAR_SAL_WORNINGS TINYINT = 1
AS BEGIN

SET NOCOUNT ON

Set @LINK_PP = Coalesce((SELECT TOP 1 LINK_rko FROM dbo.sdoc_vedom_rko WHERE LINK_vedom = @LINK_DOC),0)
IF (@LINK_PP <> 0 AND @P = 0) BEGIN
	Select LINK_RKO, COMMENT from dbo.sdoc_vedom_rko where LINK_VEDOM = @LINK_DOC
	RETURN 0
END

/*Очистить старые сообщения об ошибках*/
IF @CLEAR_SAL_WORNINGS = 1
	DELETE FROM SAL_WORNINGS WHERE SID = SUSER_SID() AND TASK ='SALARY'

DECLARE @iCreatePP INT
SELECT @iCreatePP = dbo.sa_get_option_by_code('XB_NASTR_ZAYAVKA_KR_OR_PP')

/*Определим шаблон с параметрами*/
DECLARE @SHABLON_LINK INT, @OBJ_SNAME VARCHAR(10)
IF @iCreatePP = 0
	SELECT	@SHABLON_LINK = dbo.sa_get_option_by_code('NDFL_OPT4'),
			@OBJ_SNAME = 'ПП'
ELSE
	SELECT	@SHABLON_LINK = dbo.sa_get_option_by_code('NDFL_OPT10'),
			@OBJ_SNAME = 'ЗКР'
	
---
IF NOT EXISTS (SELECT * FROM dbo.G_PROV WHERE LINK = @SHABLON_LINK)
BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление НДФЛ ',
	'Не указан шаблон ' + @OBJ_SNAME + ' в настройках удержания НДФЛ, или ' + @OBJ_SNAME + ', указанное(ая) в качестве шаблона удалена.',
	'Укажите в настройках шаблон ' + @OBJ_SNAME,
	'SALARY'
	RETURN 0
END
	

---
DECLARE @NUM_PP VARCHAR(25), @LINK_EKR INT, @LINK_EMPL INT, @LINK_KBK INT, @DATE_PP DATETIME 

CREATE TABLE #tmp (CODE VARCHAR(254), [TNAME] VARCHAR(254), LINK INT, [ANAME] VARCHAR(254), REF_LINK_B INT, REF_LINK_K INT)

DECLARE
	@pKIND           CHAR(50),
	@pS_LINK         INT,		
	@pS_ACC_LINK     INT,
	@pD_LINK         INT,		
	@pD_ACC_LINK     INT,
	@pORDER          CHAR(1),
	@pPAYKIND        CHAR(5),
	@pREASON         CHAR(5),
	@pSBANK_LINK     INT,	
	@pDBANK_LINK     INT,
	@pNDSKIND        VARCHAR(100),
	@pNDS            INT,
	@pBK_IN_TGT      tinyint,
	@pPRINT_KPP      tinyint,
	@pNDS_LINK       INT,
	@pDOG_LINK       INT,
	@SROK		      Datetime,
	@pTARGETTEXT     VARCHAR(1000),
	--
	@AVANSE TINYINT,
	@SHORT BIT,
	@BO_NUM char(10),
	@NDS_SUM NUMERIC(18,2),
	@UIN VARCHAR(20)


DECLARE @LINK_DEP INT 
SET @LINK_DEP = (SELECT D.LINK_DEP FROM dbo.SDOC D WHERE D.LINK = @LINK_DOC)

IF @iCreatePP = 0
	--Реквизиты ПП
	SELECT  
		@pKIND = PP.KIND, --Вид платежа
		@pD_LINK = PP.D_LINK, -- Получатель
		@pD_ACC_LINK = PP.D_ACC_LINK, --Номер счета получателя 
		@pORDER = PP.[ORDER], --Очередность платежа     
		@pPAYKIND = PP.PAYKIND, --Вид оплаты   
		@pREASON = PP.REASON, --Назначение  
		@pSBANK_LINK = PP.SBANK_LINK, --банк плательщика		
		@pDBANK_LINK = PP.DBANK_LINK,	--банк получателя	
		@pNDSKIND = PP.NDSKIND, --Указание НДС 	
		@pNDS = PP.NDS, --Процент НДС  
		@pBK_IN_TGT = PP.BK_IN_TGT, --Показать БК в назначении платежа  
		@pPRINT_KPP = PP.PRINT_KPP, --Показывать КПП   
		@pNDS_LINK = PP.NDS_LINK, --Шаблон НДС  
		@pDOG_LINK = PP.DOG_LINK, -- Номер договора 
		@SROK 		= PP.SROK, --Срок платежа   
		@pTARGETTEXT = RTRIM(LTRIM(PP.TARGETTEXT)), --Назначение платежа 
		@BO_NUM = ''
	FROM dbo.DOCUMENTS_PAY PP
	WHERE 
		PP.LINK = @SHABLON_LINK
ELSE
	SELECT  
		@AVANSE = ISNULL(AVANSE,0), --Авансовый платеж 
		@pKIND = KIND, --Вид платежа
		@pD_LINK = KOR_LINK, -- Получатель
		@pD_ACC_LINK = KOR_ACC_LINK, --Номер счета получателя 
		@pORDER = [ORDER], --Очередность платежа     
		@pNDS = NDS, --Процент НДС  
		@pNDS_LINK = NDS_LINK, --Шаблон НДС  
		@SROK 		= SROK, --Срок платежа 
		@SHORT = ISNULL(SHORT,0), -- Сокращенная форма заявки
		@pTARGETTEXT = RTRIM(LTRIM(TARGETTEXT)), --Назначение платежа,
		@BO_NUM = ISNULL(BO_NUM,''),
		@UIN = ISNULL(UIN_CODE,'')
	FROM dbo.BB_ZAYAVKA_KR WHERE LINK = @SHABLON_LINK		

SET @BO_NUM = ISNULL(@BO_NUM,'')
SET @AVANSE = ISNULL(@AVANSE,'')
SET @SHORT = ISNULL(@SHORT,0)

DECLARE 
	@pDOH_LINK       INT,
	@pSGU_LINK       INT,
	@pOKATO          VARCHAR(11),
	@pP_REASON       VARCHAR(2),
	@pPERIOD1         VARCHAR(2),
	@pPERIOD         VARCHAR(10),
	@pTREBNUM        VARCHAR(30),
	@pTREBDATE       DATETIME,
	@pZERODATE       BIT,
	@pP_TYPE         VARCHAR(2),
	@pSTATUS         VARCHAR(2),
	@DAY			INT,
	@DT_FULL_CODE_ACC VARCHAR(13),
	@KD_FULL_CODE_ACC VARCHAR(13),
	@ACC_NAME varchar(15)	

--Реквизиты назначения платежа
SELECT
	@pDOH_LINK       = DOH_LINK, --Код дохода
	@pSGU_LINK       = SGU_LINK, --ОСГУ
	@pOKATO          = OKATO, --Код окато
	@pP_REASON       = P_REASON, --Основание платежа
	@pPERIOD1        = LEFT(PERIOD,2), --налоговый период
	@pTREBNUM        = '0', -- Номер требования
	@pTREBDATE       = @DATE_PP, --Дата документа
	@pZERODATE       = ZERODATE, --Дата документа = 0
	@pP_TYPE         = P_TYPE, --Тип платежа
	@pSTATUS         = [STATUS], --Статус плательщика
	@UIN = ISNULL(UIN_CODE,'')
from dbo.DOCUMENTS_PAY_ADD where link = @SHABLON_LINK

DECLARE @LINK_EKR_DEFAULT int
SET @LINK_EKR_DEFAULT = (SELECT TOP 1 LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '211')

IF NOT EXISTS (SELECT * FROM dbo.DEPARTMENT_ACCOUNTS T2 WHERE LINK_UP = @LINK_DEP AND [TYPE] IN (1,2,4) ) BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление НДФЛ',
	'Не указаны счета в настройках организации.',
	'Требуется указать счета в настройках организации.',
	'SALARY'
	RETURN 0
END

declare @DEP_LINK int
exec dbo.xd_whats_zb @DEP_LINK output

DECLARE @BUH_TYPE TINYINT
SET @BUH_TYPE = ISNULL((SELECT BUH_TYPE FROM DBO.DEPARTMENTS WHERE LINK = @DEP_LINK),0)

DECLARE @WORKMODE157N INT
SET @WORKMODE157N = ISNULL((SELECT dbo.XK_GET_NASTR_INT ('XK_WORKMODE157N')),0)
--Если не выполнен переход, то считаем, что тип организации не определён!
SET @BUH_TYPE = CASE WHEN @WORKMODE157N = 0 THEN 0 ELSE @BUH_TYPE END

--IF @BUH_TYPE = 0 BEGIN
--	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
--	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление НДФЛ',
--		'Не определён вид государственного учреждения.',
--		'В реквизитах текущей организации установите реквизит "Вид государственного учреждения".',
--		'SALARY'
--	RETURN 0		
--END

IF NOT EXISTS (SELECT * FROM DBO.SAL_NASTR_PROV WHERE TYPE_OPER = 1 AND TYPE_DEP = @BUH_TYPE) BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление НДФЛ',
		'Не определён счет для выбытия ср-в с лиц. либо расч. счета.',
		'В настройках формирования проводок по зарплате укажите счёта в справочнике "Счета для выбытия ср-в с лиц. либо расч. счета" для данного вида гос. учреждения".',
		'SALARY'
	RETURN 0		
END

DECLARE @GROUP_BY_SUB INT
SET @GROUP_BY_SUB = dbo.sa_get_option_by_code('SALARY_PROV_OPT3')

SELECT LINK, SUBDIV_HEAD, SUBDIV_NAME INTO #EMPL_INFO FROM DBO.SD_EMPL

----
DECLARE @CURSOR_EKR CURSOR, @DATE_PROV DATETIME, @Osnovanie VARCHAR(100), @Add_text VARCHAR(100), @link_pay int, @SUMMA_PP as numeric(19,2), @Fin_Source VARCHAR(1), @KD_CODE_ACC VARCHAR(6), @DT_CODE_ACC VARCHAR(6),
	@Cur CURSOR, @SUM_PROV numeric(18,2), @order int, @Account1 INT, @Account2 INT,	@HOZ_OPER int, @P1 float, @P2 float, @SGU INT, @LINK_KAU INT, @LINK_DOP_KL INT, @PAYS_CODE VARCHAR(10),
	@USER_ACC VARCHAR(4), @CODE_SFIN VARCHAR(20), @ACC_CODE VARCHAR(13),
	@trancount INT, @ERROR as INT, @LINK_ORG int, @LINK_ACC int, @LINK_DOH int, @SUBDIV_HEAD INT, @SUBDIV_NAME VARCHAR(254),
	@LINK_SFIN INT

SET @CURSOR_EKR = CURSOR FORWARD_ONLY
FOR 
SELECT  
	D.[DATE],
	'Перечисление НДФЛ за ' + coalesce((SELECT TOP 1 MON FROM months WHERE NUM = MONTH(CJ.PERIOD_END)),'') + ',' + CONVERT(VARCHAR(4),coalesce(YEAR(CJ.PERIOD_END),0)) + 'г.' + ' по ' + RTRIM(EKR.CODE) + ' ЭКР ' 
		+ ' по ист.фин. "' + RTRIM(LTRIM(F.CODE)) + '" с вид.деят. "' + RTRIM(LTRIM(ISNULL((SELECT TOP 1 FS.CODE + '.' + FS.NAME FROM dbo.BB_FIN_SOURCE FS WHERE FS.CODE = F.SOURCE),''))) +  '"',
	'Расчет №' + RTRIM(LTRIM(COALESCE(D.NUMBER,''))) + ' от ' + COALESCE(convert(VARCHAR(10),D.[DATE], 104),''),
	CJ.LINK_PAYS,
	SUM(SUMMA),
	@pTARGETTEXT + case when dbo.sa_get_option_by_code('SALARY_OPTIONS_OPT9') = 1 then CASE WHEN LEN(@pTARGETTEXT) > 0 THEN ', ' else '' end + P.[NAME]  + ' по ' + RTRIM(EKR.CODE) + ' ЭКР'  ELSE '' END,
	COALESCE(CJ.link_ekr,@LINK_EKR_DEFAULT),
	P.CODE_ACC, 
	COALESCE(CAST (F.SOURCE as CHAR(1)),''),
	T.LINK_ORG,
	T.LINK_ACC,
	T.LINK_DOH,
	CASE WHEN @GROUP_BY_SUB = 1 THEN SUBDIV_HEAD ELSE NULL END,
	CASE WHEN @GROUP_BY_SUB = 1 THEN SUBDIV_NAME ELSE NULL END,
	F.LINK -- зарплатский источник финансирования
FROM 
	dbo.SDOC D INNER JOIN dbo.CALCULATE_JURNAL CJ ON D.LINK = CJ.LINK_DOC
	INNER JOIN dbo.PAYS P ON (CJ.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC = 4)
	INNER JOIN dbo.DICTIONARY_ITEM EKR ON EKR.LINK = COALESCE(CJ.link_ekr,@LINK_EKR_DEFAULT)
	LEFT JOIN  dbo.SAL_SFIN F ON F.LINK = CJ.LINK_VKR
	LEFT JOIN DBO.BB_FIN_SOURCE FUN ON FUN.CODE = F.[SOURCE]	
	LEFT JOIN TAX2_APP T on P.link = T.link_up
	LEFT JOIN #EMPL_INFO E ON E.LINK = CJ.LINK_EMPL
WHERE 
	D.LINK = @LINK_DOC 
GROUP BY 
	D.NUMBER, D.[DATE], CJ.PERIOD_END, CJ.LINK_PAYS, P.[NAME], CJ.link_ekr, EKR.CODE, P.CODE_ACC, F.SOURCE,	F.CODE, T.LINK_ORG,	T.LINK_ACC,	T.LINK_DOH, CASE WHEN @GROUP_BY_SUB = 1 THEN SUBDIV_HEAD ELSE NULL END,
	CASE WHEN @GROUP_BY_SUB = 1 THEN SUBDIV_NAME ELSE NULL END, F.LINK
HAVING 
	SUM(SUMMA) > 0

OPEN @CURSOR_EKR
FETCH NEXT FROM @CURSOR_EKR INTO @DATE_PP, @Osnovanie, @Add_Text, @link_pay, @SUMMA_PP, @pTARGETTEXT, @link_ekr, @DT_CODE_ACC, @Fin_Source, @LINK_ORG, @LINK_ACC, @LINK_DOH, @SUBDIV_HEAD, @SUBDIV_NAME, @LINK_SFIN
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN

		SET @pPERIOD = @pPERIOD1 + RIGHT(CONVERT(VARCHAR(10),@DATE_PP,104),8)
		SET @DAY = (CASE WHEN DAY(@SROK) > DAY(dbo.DateEndOfMonth(DATEADD(m,1,@DATE_PP))) THEN DAY(dbo.DateEndOfMonth(DATEADD(m,1,@DATE_PP))) ELSE DAY(@SROK) END)
		SET @SROK = dbo.ConvertDMY2Date(@DAY, MONTH(DATEADD(m,1,@DATE_PP)), YEAR(DATEADD(m,1,@DATE_PP)))
		SET @DATE_PP = CASE WHEN COALESCE(@DATE_DOC,@DATE_PP) > @DATE_PP THEN @DATE_DOC ELSE @DATE_PP END	
		SET @DATE_PROV = CASE WHEN dbo.sa_get_option_by_code('SALARY_OPTIONS_OPT12') = 1 THEN @DATE_PP ELSE NULL END

		SET @pD_ACC_LINK = COALESCE(@LINK_ACC,@pD_ACC_LINK)
		SET @pDOH_LINK = COALESCE(@LINK_DOH,@pDOH_LINK)
		SET @pD_LINK = COALESCE(@LINK_ORG,@pD_LINK)
		---

			
		IF @pD_ACC_LINK is null OR @pD_ACC_LINK is null OR @pD_LINK is null BEGIN
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
				'Заданы не все сведения о получателе в настройках вида вида удержания для НДФЛ!',
				'Укажите получателя, номер счета получателя, код дохода в настройках вида удержания меню: \СПРАВОЧНИКИ\Операции по зарплате\Виды удержаний.',
				'SALARY'
			GOTO DO_NEXT
		END


		IF @DATE_PROV is not null and not exists(Select * from admin_info Where @DATE_PROV BETWEEN BEGINDATE AND ENDDATE) BEGIN
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
				'Программа формирует дату проводки, равную дате платежки. Но эта дата не попадает в период редактирования!',
				'Укажите другую дату платежки, или отключите в общих настройках по зарплате опцию "В бух. документе автоматически ставить дату" проводки, или измените период редактирования.',
				'SALARY'
			GOTO DO_NEXT
		END
		
		SET @trancount = @@TRANCOUNT
		SET IMPLICIT_TRANSACTIONS ON
		BEGIN TRAN 
		COMMIT TRAN

		-- определим максимальный номер 
		Set @NUM_PP = NULL
		IF @iCreatePP = 0		
			exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'DOCUMENTS_PAY', @NUM_PP output, @LINK_DEP
		ELSE
			exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'BB_ZAYAVKA_KR', @NUM_PP output, @LINK_DEP	

		--вначале поставим любой, потом вычислим точнее и заменим
		SET @pS_ACC_LINK = dbo.SA_GET_DEP_ACC(@LINK_DEP, DEFAULT, DEFAULT, DEFAULT)

		-- Сохраняем ПП 
		Set @LINK_PP = NULL		
		IF @iCreatePP = 0 
		BEGIN
			EXEC dbo.X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_PP, @DATE_PROV, @SUMMA_PP, '',
				@pKIND, @pS_LINK, @pS_ACC_LINK, @pD_LINK, @pD_ACC_LINK,
				@SROK, @pORDER, @pPAYKIND, @pREASON,
				@pTARGETTEXT, @pNDS, @pBK_IN_TGT, @pPRINT_KPP,
				@pNDS_LINK, 'DOCUMENTS_PAY'

			EXEC dbo.X_SAVE_DOCUMENTS_PAY_ADD @LINK_PP OUT, @pDOH_LINK, @pSGU_LINK, @pOKATO, @pP_REASON,
				 @pPERIOD, @pTREBNUM, @DATE_PP, @pZERODATE, @pP_TYPE, @pSTATUS, @UIN
		END		 
		ELSE
		BEGIN
			EXEC dbo.X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_PP, @DATE_PROV, @SUMMA_PP, '',
				@pKIND, @pS_LINK, @pS_ACC_LINK, @pD_LINK, @pD_ACC_LINK,
				@SROK, @pORDER, NULL, DEFAULT, 
				@pTARGETTEXT, @pNDS, @pBK_IN_TGT, NULL,
				@pNDS_LINK, 'BB_ZAYAVKA_KR'

			SET @NDS_SUM = ISNULL(@SUMMA_PP * ISNULL(@pNDS,0) / 100, 0)

			EXEC dbo.X_SAVE_DOCUMENTS_PAY2 @LINK_PP, NULL, @BO_NUM, NULL, @AVANSE, @NDS_SUM, @SHORT

			EXEC dbo.X_SAVE_DOCUMENTS_PAY_ADD @LINK_PP, @pDOH_LINK, @pSGU_LINK, @pOKATO, @pP_REASON,
				 @pPERIOD, @pTREBNUM, @DATE_PP, @pZERODATE, @pP_TYPE, @pSTATUS, @UIN			
					
		END		 

		IF @SUBDIV_HEAD IS NOT NULL
			SET @Osnovanie = @Osnovanie + LEFT(CASE WHEN LEN(@Osnovanie) > 0 THEN ', ' else '' end + LTRIM(RTRIM(COALESCE(@SUBDIV_NAME,''))), 200)

		INSERT INTO dbo.sdoc_vedom_rko (LINK_VEDOM, LINK_RKO, LINK_PAYS, COMMENT) 
		VALUES(@LINK_DOC, @LINK_PP, @link_pay, @Osnovanie  + ' ' + @OBJ_SNAME + ' №' + CONVERT(VARCHAR(8), @NUM_PP)  + ' от ' + CONVERT(VARCHAR(10),@DATE_PP,104))
		
		Set @order = 0

		SET @Cur = CURSOR FORWARD_ONLY
		FOR 
			SELECT 
				LINK_KBK = F.KBK,
				LINK_KAU = F.KAU,
				LINK_DOP_KL = F.DOP_KL,
				USER_ACC = F.USER_ACC,
				CODE_SFIN = F.CODE,
				SUMMA= SUM(CJ.SUMMA),
				PAYS_CODE = P.CODE
			FROM 
				dbo.CALCULATE_JURNAL CJ 
				INNER JOIN dbo.PAYS P ON (CJ.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC = 4)
				LEFT JOIN  dbo.SAL_SFIN F ON F.LINK = CJ.LINK_VKR
				LEFT JOIN #EMPL_INFO E ON E.LINK = CJ.LINK_EMPL
			WHERE 
				LINK_DOC = @LINK_DOC AND COALESCE(CJ.link_ekr,@LINK_EKR_DEFAULT) = @LINK_EKR AND F.SOURCE = @Fin_Source
				AND (@GROUP_BY_SUB = 1 AND SUBDIV_HEAD = @SUBDIV_HEAD OR @GROUP_BY_SUB = 0)
				AND CJ.LINK_VKR = @LINK_SFIN
			GROUP BY 
				F.KBK, F.KAU, F.SOURCE, F.DOP_KL, F.USER_ACC, F.CODE, P.CODE
			HAVING 
				SUM(CJ.SUMMA) >= 0
				
		OPEN @Cur
		FETCH NEXT FROM @Cur INTO @LINK_KBK, @LINK_KAU, @LINK_DOP_KL,  @USER_ACC, @CODE_SFIN, @SUM_PROV, @PAYS_CODE
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN

				IF REPLACE(LTRIM(RTRIM(ISNULL(@DT_CODE_ACC,''))),'.','') = '' BEGIN
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
						'Не указан счет кредита в настройках удержания '+COALESCE(LTRIM(RTRIM(@PAYS_CODE)),''),
						'Укажите в настройках удержания '+COALESCE(LTRIM(RTRIM(@PAYS_CODE)),'')+' счет кредита.',
						'SALARY'
					GOTO DO_NEXT			
				END

				---			
				SET @P1 = NULL
				exec X_UPDATE_G_PROV1 @P1 output, @LINK_PP, NULL, @Osnovanie, 1
		
				Set @order = @order + 1

				---
				SET @Account1 = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @DT_CODE_ACC) AND cUser = RTRIM(LTRIM(COALESCE(@USER_ACC,''))))
				SET @DT_FULL_CODE_ACC = @Fin_Source + '.' + @DT_CODE_ACC + CASE WHEN RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> '' THEN '/' + RTRIM(LTRIM(COALESCE(@USER_ACC,''))) ELSE '' END
				
				IF COALESCE(@Account1,0) = 0 BEGIN 
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
						'В плане счетов не найден счет ' + @DT_FULL_CODE_ACC,
						'Добавьте в план счетов счет ' + @DT_FULL_CODE_ACC,
						'SALARY'
					GOTO DO_NEXT
				END					
			
				---
				SET @ACC_CODE = (select top 1 A2.CODE from dbo.S_ACCOUNTS A1 inner join dbo.S_ACCOUNTS A2 on A1.link_self = A2.link
					WHERE A2.LINK = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @DT_CODE_ACC) ) and A2.cSource <> '')

				IF  RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) <> '' AND RTRIM(LTRIM(COALESCE(@USER_ACC,''))) = '' BEGIN
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
						'У источника финансирования ' + RTRIM(LTRIM(@CODE_SFIN)) + ' не указан пользовательский субсчет, однако у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' есть субсчета',
						'Укажите пользовательский субсчет, либо уберите в плане счетов субсчет у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' с помощью слияния',
						'SALARY'
					GOTO DO_NEXT
				END

				--		
				SET @KD_CODE_ACC = (SELECT TOP 1 CODE_ACC FROM DBO.SAL_NASTR_PROV WHERE TYPE_OPER = 1 AND TYPE_DEP = @BUH_TYPE AND TYPE_FUNC = @Fin_Source)

				IF REPLACE(LTRIM(RTRIM(ISNULL(@KD_CODE_ACC,''))),'.','') = '' BEGIN
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF		
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
						'Не задан счет для выбытия ср-в с лиц. либо расч. счета для вида организации ' 
						+ ISNULL((SELECT TOP 1 BT_NAME FROM DBO.DICTIONARY_BUH_TYPE WHERE BUH_TYPE = @BUH_TYPE),'')
						+ ' для вида деятельности ' + ISNULL((SELECT TOP 1 NAME FROM DBO.BB_FIN_SOURCE WHERE CODE = @Fin_Source),''),
						'В настройках всех режимов задачи выберите раздел "Настройка счетов для проводок по зарплате" и укажите требуемый счёт в настройке "Счет для выбытия ср-в с лиц. либо расч. счета".',
						'SALARY'
					GOTO DO_NEXT
				END	

				SET @Account2 = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @KD_CODE_ACC) AND cUser = RTRIM(LTRIM(COALESCE(@USER_ACC,''))))
				SET @KD_FULL_CODE_ACC = @Fin_Source + '.' + @KD_CODE_ACC + CASE WHEN RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> '' THEN '/' + RTRIM(LTRIM(COALESCE(@USER_ACC,''))) ELSE '' END

				IF COALESCE(@Account2,0) = 0 BEGIN 
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
						'В плане счетов не найден счет ' + @KD_FULL_CODE_ACC,
						'Добавьте в план счетов счет ' + @KD_FULL_CODE_ACC,
						'SALARY'
					GOTO DO_NEXT
				END
		
				---
				SET @ACC_CODE = (select top 1 A2.CODE from dbo.S_ACCOUNTS A1 inner join dbo.S_ACCOUNTS A2 on A1.link_self = A2.link
					WHERE A2.LINK = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @KD_CODE_ACC) ) and A2.cSource <> '')

				IF  RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) <> '' AND RTRIM(LTRIM(COALESCE(@USER_ACC,''))) = '' BEGIN
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
						'У источника финансирования ' + RTRIM(LTRIM(@CODE_SFIN)) + ' не указан пользовательский субсчет, однако у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' есть субсчета',
						'Укажите пользовательский субсчет, либо уберите в плане счетов субсчет у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' с помощью слияния',
						'SALARY'
					GOTO DO_NEXT
				END
				
				IF COALESCE(@Account1,0) > 0 AND COALESCE(@Account2,0) > 0 BEGIN
	
					SET @HOZ_OPER = (SELECT TOP 1 LINK FROM dbo.BX_BPROV_VIBOR_ECON_OPER(@Account1,@Account2))
					IF COALESCE(@HOZ_OPER,0) = 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'Не найдено подходящей хоз. операции для проводки ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account1) + '-' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account2),
							'Вероятно в общих настройках по зарплате указан неправильно счет для выбытия бюдж. или внебюдж средств с лицевого либо расчетного счета',
							'SALARY'
						GOTO DO_NEXT
					END	
			
					set @P2 = null
					exec X_UPDATE_G_PROV2 @P2 output, @P1, NULL, @SUM_PROV, 0, 0, @Osnovanie, @HOZ_OPER, @order

					---
					SET @SGU = (SELECT TOP 1 LINK_SGU FROM S_ACCOUNTS_SGU SGU INNER JOIN KOSGU ON SGU.LINK_SGU = KOSGU.LINK WHERE DB_KR = 0 AND ACCOUNT = @Account1)
					IF EXISTS (SELECT p_KASSA FROM dbo.s_accounts WHERE LINK = @Account1 AND p_KASSA = 1)
						SET @SGU = @LINK_EKR
	
					IF COALESCE(@SGU,0) = 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'У счета ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account1) + ' не задано СГУ',
							'Укажите СГУ в настройках счета в плане счетов',
							'SALARY'
						GOTO DO_NEXT
					END	
					exec X_UPDATE_G_PROV_AP @P2, 0, @Account1, @LINK_KBK, @LINK_EKR, @LINK_ORG /*Получатель*/, NULL, NULL, NULL, NULL, @LINK_KAU, @pD_ACC_LINK /*Счет получателя*/, NULL, NULL, NULL, @LINK_DOP_KL, NULL, @SGU

					---
					SET @SGU = (SELECT TOP 1 LINK_SGU FROM S_ACCOUNTS_SGU SGU INNER JOIN KOSGU ON SGU.LINK_SGU = KOSGU.LINK WHERE DB_KR = 1 AND ACCOUNT = @Account2)
					IF EXISTS (SELECT p_KASSA FROM dbo.s_accounts WHERE LINK = @Account2 AND p_KASSA = 1)
						SET @SGU = @LINK_EKR
	
					IF COALESCE(@SGU,0) = 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'У счета ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account2) + ' не задано СГУ',
							'Укажите СГУ в настройках счета в плане счетов',
							'SALARY'
						GOTO DO_NEXT
					END	
					
					SET @pS_ACC_LINK = dbo.SA_GET_DEP_ACC(@LINK_DEP, @Account2, @LINK_SFIN, DEFAULT)

					UPDATE dbo.G_PROV SET ACC = @pS_ACC_LINK WHERE LINK = @LINK_PP

					exec X_UPDATE_G_PROV_AP @P2, 1, @Account2, @LINK_KBK, @LINK_EKR, @LINK_DEP /*отправитель*/, @SUBDIV_HEAD, NULL, NULL, NULL, @LINK_KAU, @pS_ACC_LINK /*Счет отправителя*/, NULL, NULL, NULL, @LINK_DOP_KL, NULL, @SGU

				END
				
			END
			
			IF @iCreatePP = 1
				EXEC dbo.BB_ZAYAVKA_KR_CREATE_TABLE @LINK_PP
			
			FETCH NEXT FROM @Cur INTO @LINK_KBK, @LINK_KAU, @LINK_DOP_KL,  @USER_ACC, @CODE_SFIN, @SUM_PROV, @PAYS_CODE
		END
		
		CLOSE @Cur
		DEALLOCATE @Cur

		IF @@TRANCOUNT > @trancount BEGIN
			COMMIT TRAN
			SET IMPLICIT_TRANSACTIONS OFF
		END

		---Если надо, то сформировать БО
		DECLARE @TestBO tinyint
		exec @TestBO = dbo.XD_TEST_FORM_BO @LINK_PP 
		IF @TestBO = 0
		BEGIN
			create table #tProtocol1(txt varchar(1000), NEW_ROW tinyint, nSTATUS tinyint, nTAB tinyint, ord int identity(1,1))

			insert into #tProtocol1 (txt, NEW_ROW, nSTATUS, nTAB) 
			Exec dbo.XD_FORM_BO @LINK_PP

			IF EXISTS (SELECT * FROM #tProtocol1 WHERE nSTATUS >=1 )
				INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
				select 'Обнаружены замечания при формирование БО:', CASE WHEN nSTATUS = 1 THEN 'Предупреждение!' ELSE 'Ошибка!' END + SPACE(1) + LEFT(txt,240), 'Устраните замечания!', 'SALARY'
				FROM #tProtocol1	WHERE nSTATUS >= 1
			
			DROP TABLE #tProtocol1
				
		END				

	END

	DO_NEXT:
	FETCH NEXT FROM @CURSOR_EKR INTO @DATE_PP, @Osnovanie, @Add_Text, @link_pay, @SUMMA_PP, @pTARGETTEXT, @link_ekr, @DT_CODE_ACC, @Fin_Source, @LINK_ORG, @LINK_ACC, @LINK_DOH, @SUBDIV_HEAD, @SUBDIV_NAME, @LINK_SFIN
END

CLOSE @CURSOR_EKR
DEALLOCATE @CURSOR_EKR

Select LINK_RKO, COMMENT from dbo.sdoc_vedom_rko where LINK_VEDOM = @LINK_DOC

exec X_SALDO_CommitChanges

SET NOCOUNT OFF
Return 0
END

GO


GRANT EXECUTE ON dbo.[SA_CREATE_PP] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_CREATE_PP_O]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_CREATE_PP_O]

GO

CREATE    PROCEDURE [dbo].[SA_CREATE_PP_O]
	@LINK_PP INT OUTPUT,
	@LINK_DOC INT,
	@DATE_DOC DATETIME
AS BEGIN

SET NOCOUNT ON

/*Очистить старые сообщения об ошибках*/
DELETE FROM SAL_WORNINGS WHERE SID = SUSER_SID() AND TASK ='SALARY'

Set @LINK_PP = Coalesce((SELECT TOP 1 LINK_rko FROM dbo.sdoc_vedom_rko WHERE LINK_vedom = @LINK_DOC),0)
IF @LINK_PP <> 0 BEGIN
	Select LINK_RKO, COMMENT from dbo.sdoc_vedom_rko where LINK_VEDOM = @LINK_DOC
	RETURN 0
END

DECLARE @iCreatePP INT
SELECT @iCreatePP = dbo.sa_get_option_by_code('XB_NASTR_ZAYAVKA_KR_OR_PP')

DECLARE @OBJ_SNAME VARCHAR(10)
SET @OBJ_SNAME = CASE WHEN @iCreatePP = 0 THEN 'ПП' ELSE 'ЗКР' END

--
DECLARE 
	@NUM_PP 	VARCHAR(25),
	@DATE_PP  	DATETIME,
	@DATE_PROV	DATETIME,
	@SUMMA_PP	numeric(19,2),
	@LINK_KBK  	INT,
	@Add_text 	VARCHAR(100),
	@LINK_PAY 	INT,
	@LINK_EKR 	INT,
	@Osnovanie 	VARCHAR(100),
	@Osnovanie2 	VARCHAR(100),
	@pTARGETTEXT VARCHAR(1000)

CREATE TABLE #tmp (CODE VARCHAR(254), [TNAME] VARCHAR(254), LINK INT, [ANAME] VARCHAR(254), REF_LINK_B INT, REF_LINK_K INT)

--Реквизиты шаблона платежки
DECLARE
	@pKIND           CHAR(50),
	@pS_LINK         INT, --Ссылка на свою организацию		
	@pS_ACC_LINK     INT, --Счет своей организации
	@pD_LINK         INT,		
	@pD_ACC_LINK     INT,
	@pORDER          CHAR(1),
	@pPAYKIND        CHAR(5),
	@pREASON         CHAR(5),
	@pSBANK_LINK     INT,	
	@pDBANK_LINK     INT,
	@pNDSKIND        VARCHAR(100),
	@pNDS            INT,
	@pBK_IN_TGT      tinyint,
	@pPRINT_KPP      tinyint,
	@pNDS_LINK       INT,
	@pDOG_LINK       INT,
	@SROK		      Datetime,
	--
	@AVANSE TINYINT,
	@SHORT BIT,
	@BO_NUM char(10),
	@NDS_SUM NUMERIC(18,2)	

--Назначение платежа из шаблона платежки
DECLARE 
	@pDOH_LINK		INT,
	@pSGU_LINK		INT,
	@pOKATO		VARCHAR(11),
	@pP_REASON		VARCHAR(2),
	@pPERIOD1		VARCHAR(2),
	@pPERIOD		VARCHAR(10),
	@pTREBNUM		VARCHAR(30),
	@pTREBDATE		DATETIME,
	@pZERODATE		BIT,
	@pP_TYPE		VARCHAR(2),
	@pSTATUS		VARCHAR(2),
	@DAY			INT,
	@DT_FULL_CODE_ACC VARCHAR(13),
	@KD_FULL_CODE_ACC VARCHAR(13),
	@ACC_NAME varchar(15),
	@UIN VARCHAR(20)

DECLARE @LINK_DEFAULT_EKR int
SELECT @LINK_DEFAULT_EKR = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '213'

DECLARE @LINK_211EKR int
SELECT @LINK_211EKR = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '211'

---
DECLARE @Cur CURSOR, @SUM_PROV numeric(18,2), @ORDER INT, @Account1 INT, @Account2 INT,	
		@HOZ_OPER INT, @P1 float, @P2 float, @SGU INT, @KD_CODE_ACC VARCHAR(6), @DT_CODE_ACC VARCHAR(6), @LINK_KAU INT, @Fin_Source VARCHAR(1),
		@isNALOG INT, @LINK_DOP_KL INT, @USER_ACC VARCHAR(4), @CODE_SFIN VARCHAR(20), @ACC_CODE VARCHAR(13),
		@trancount INT, @ERROR as INT, @REG_NUM VARCHAR(30), @LINK_OBJ INT, @LINK_OBJ_DOCUMENTS_DGH INT, @LINK_ORG INT

SET @LINK_OBJ_DOCUMENTS_DGH = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOCUMENTS_DGH')

DECLARE @Cur1 CURSOR, @LINK_ACC int, @LINK_DOH int, @P_NAME varchar(254), @SHABLON_LINK INT, @LINK_SGU INT, @LINK_SAL_SFIN INT, @LINK_LACC INT

DECLARE @LINK_DEP INT 
SET @LINK_DEP = (SELECT D.LINK_DEP FROM dbo.SDOC D WHERE D.LINK = @LINK_DOC)

DECLARE @BUH_TYPE TINYINT
SET @BUH_TYPE = ISNULL((SELECT BUH_TYPE FROM DBO.DEPARTMENTS WHERE LINK = @LINK_DEP),0)

DECLARE @WORKMODE157N INT
SET @WORKMODE157N = ISNULL((SELECT dbo.XK_GET_NASTR_INT ('XK_WORKMODE157N')),0)
--Если не выполнен переход, то считаем, что тип организации не определён!
SET @BUH_TYPE = CASE WHEN @WORKMODE157N = 0 THEN 0 ELSE @BUH_TYPE END

--IF @BUH_TYPE = 0 BEGIN
--	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
--	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление взносов',
--		'Не определён вид государственного учреждения.',
--		'В реквизитах текущей организации установите реквизит "Вид государственного учреждения".',
--		'SALARY'
--	RETURN 0		
--END

IF NOT EXISTS (SELECT * FROM DBO.SAL_NASTR_PROV WHERE TYPE_OPER = 1 AND TYPE_DEP = @BUH_TYPE) BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление взносов',
		'Не определён счет для выбытия ср-в с лиц. либо расч. счета.',
		'В настройках формирования проводок по зарплате укажите счёта в справочнике "Счета для выбытия ср-в с лиц. либо расч. счета" для данного вида гос. учреждения".',
		'SALARY'
	RETURN 0		
END

IF NOT EXISTS (SELECT * FROM dbo.DEPARTMENT_ACCOUNTS T2 WHERE LINK_UP = @LINK_DEP AND [TYPE] IN (1,2,4) ) BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление взносов',
	'Не указаны счета в настройках организации.',
	'Требуется указать счета в настройках организации.',
	'SALARY'
	RETURN 0
END

DECLARE @SALARY_OPTIONS_OPT9 INT --Добавлять в назначение платежа наименование операции	
SET @SALARY_OPTIONS_OPT9 = dbo.sa_get_option_by_code('SALARY_OPTIONS_OPT9')

DECLARE @SALARY_OPTIONS_OPT11 INT --Добавлять в назначение платежа рег. номер
SET @SALARY_OPTIONS_OPT11 = dbo.sa_get_option_by_code('SALARY_OPTIONS_OPT11')

SET @Cur1 = CURSOR FORWARD_ONLY
FOR 
SELECT  
	D.[DATE],
	'Перечисление ' + RTRIM(P.SNAME) + ' за ' + coalesce((SELECT TOP 1 MON FROM months WHERE NUM = MONTH(CJ.PERIOD_END)),'') + ',' + CONVERT(VARCHAR(4),coalesce(YEAR(CJ.PERIOD_END),0))
		+ ' по вид.деят. "' + ISNULL((SELECT TOP 1 LTRIM(RTRIM(FS.CODE)) + '.' + LTRIM(RTRIM(FS.NAME)) FROM dbo.BB_FIN_SOURCE FS WHERE FS.CODE = F.SOURCE),'') +  '"',
	'Расчет №' + RTRIM(LTRIM(COALESCE(D.NUMBER,''))) + ' от ' + COALESCE(convert(VARCHAR(10),D.[DATE], 104),''),
	CJ.LINK_PAYS,
	SUM(SUMMA),
	T.LINK_ACC,
	T.LINK_DOH,
	COALESCE(CAST (F.SOURCE as CHAR(1)),''),
	P.[NAME],
	/*Определим шаблон с параметрами платежки*/ 
	CASE WHEN P.WAY_CALC <> 5 THEN 
					CASE WHEN @iCreatePP = 0 THEN dbo.sa_get_option_by_code('ESN_OPT2') ELSE dbo.sa_get_option_by_code('ESN_OPT4') END
				ELSE 
					CASE WHEN @iCreatePP = 0 THEN dbo.sa_get_option_by_code('ESNTR_OPT1') ELSE dbo.sa_get_option_by_code('ESNTR_OPT2') END
				END,
	T.LINK_SGU,
	RTRIM(LTRIM(COALESCE(T.REG_NUM,''))),
	D.OBJECT,
	T.LINK_ORG,
	LINK_LACC
FROM dbo.SDOC D INNER JOIN dbo.CALCULATE_JURNAL CJ ON D.LINK = CJ.LINK_DOC
	INNER JOIN dbo.PAYS P ON CJ.LINK_PAYS = P.LINK AND P.[OBJECT] = 3
	INNER JOIN TAX2_APP T on P.link = T.link_up
	LEFT JOIN  dbo.SAL_SFIN F ON F.LINK = CJ.LINK_VKR
	LEFT JOIN DBO.BB_FIN_SOURCE FUN ON FUN.CODE = F.[SOURCE]
WHERE 
	D.LINK = @LINK_DOC
GROUP BY 
	D.NUMBER, D.[DATE], CJ.PERIOD_END, CJ.LINK_PAYS, P.[NAME], P.SNAME, T.LINK_ACC, T.LINK_DOH, F.[SOURCE], 
	FUN.NAME, P.WAY_CALC,T.LINK_SGU,T.REG_NUM, D.OBJECT, T.LINK_ORG, LINK_LACC
HAVING 
	SUM(SUMMA) > 0

------
OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @DATE_PP, @Osnovanie, @Add_Text, @LINK_PAY, @SUMMA_PP, @LINK_ACC, @LINK_DOH, @Fin_Source, @P_NAME, @SHABLON_LINK, @LINK_SGU, @REG_NUM, @LINK_OBJ, @LINK_ORG, @LINK_LACC

WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2) 
	BEGIN

		---
		IF NOT EXISTS (SELECT * FROM G_PROV WHERE LINK = @SHABLON_LINK)
		BEGIN
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформированы ' + @OBJ_SNAME + ' на ' + @Osnovanie,
			'Не указан шаблон ' + @OBJ_SNAME + ' в настройках отчисления взносов, или платежка, указанная в качестве шаблона удалена.',
			'Укажите в настройках шаблон в настройках.',
			'SALARY'
			RETURN 0
		END
	
		IF @iCreatePP = 0
			--Реквизиты шаблона платежки
			SELECT  @pKIND = PP.KIND,
				@pD_LINK = PP.D_LINK,
				@pD_ACC_LINK = PP.D_ACC_LINK,
				@pORDER = PP.[ORDER],
				@pPAYKIND = PP.PAYKIND,
				@pREASON = PP.REASON,
				@pSBANK_LINK = PP.SBANK_LINK,		
				@pDBANK_LINK = PP.DBANK_LINK,		
				@pNDSKIND = PP.NDSKIND,	
				@pNDS = PP.NDS,
				@pBK_IN_TGT = PP.BK_IN_TGT,
				@pPRINT_KPP = PP.PRINT_KPP,
				@pNDS_LINK = PP.NDS_LINK,
				@pDOG_LINK = PP.DOG_LINK,
				@SROK 		= PP.SROK,
				@pTARGETTEXT = RTRIM(LTRIM(PP.TARGETTEXT)),
				@BO_NUM = '',
				@AVANSE = 0,
				@SHORT = 0
			FROM dbo.DOCUMENTS_PAY  PP
			WHERE PP.LINK = @SHABLON_LINK
		ELSE
			SELECT  
				@AVANSE = ISNULL(AVANSE,0), --Авансовый платеж 
				@pKIND = KIND, --Вид платежа
				@pD_LINK = KOR_LINK, -- Получатель
				@pD_ACC_LINK = KOR_ACC_LINK, --Номер счета получателя 
				@pORDER = [ORDER], --Очередность платежа     
				@pNDS = NDS, --Процент НДС  
				@pNDS_LINK = NDS_LINK, --Шаблон НДС  
				@SROK 		= SROK, --Срок платежа 
				@SHORT = ISNULL(SHORT,0), -- Сокращенная форма заявки
				@pTARGETTEXT = RTRIM(LTRIM(TARGETTEXT)), --Назначение платежа,
				@BO_NUM = ISNULL(BO_NUM,''),
				@UIN = ISNULL(UIN_CODE,'')
			FROM dbo.BB_ZAYAVKA_KR WHERE LINK = @SHABLON_LINK			
		
		SET @BO_NUM = ISNULL(@BO_NUM,'')
		SET @AVANSE = ISNULL(@AVANSE,'')
		SET @SHORT = ISNULL(@SHORT,0)
	
		--Назначение платежа из шаблона платежки
		SELECT
			@pDOH_LINK       = DOH_LINK,
			@isNALOG	      = DOH_LINK,
			@pSGU_LINK       = SGU_LINK,
			@pOKATO          = OKATO,
			@pP_REASON  = P_REASON,
			@pPERIOD1         = LEFT(PERIOD,2),
			@pTREBNUM        = '0',
			@pTREBDATE       = @DATE_PP,
			@pZERODATE       = ZERODATE,
			@pP_TYPE         = P_TYPE,
			@pSTATUS         = STATUS,
			@UIN = ISNULL(UIN_CODE,'')
		from dbo.DOCUMENTS_PAY_ADD where link = @SHABLON_LINK
	
		SET @pD_ACC_LINK = COALESCE(@LINK_ACC,@pD_ACC_LINK)
		SET @pDOH_LINK = COALESCE(@LINK_DOH,@pDOH_LINK)
		SET @pTARGETTEXT = @pTARGETTEXT + case when @SALARY_OPTIONS_OPT9 = 1 then CASE WHEN LEN(@pTARGETTEXT) > 0 THEN ', ' else '' end + RTRIM(LTRIM(@P_NAME)) ELSE '' END	
		SET @pTARGETTEXT = @pTARGETTEXT + case when @SALARY_OPTIONS_OPT11 = 1 then CASE WHEN LEN(@pTARGETTEXT) > 0 AND LEN(RTRIM(LTRIM(@REG_NUM))) >0 THEN ', рег.номер ' else '' end + RTRIM(LTRIM(@REG_NUM)) ELSE '' END	
		SET @pSGU_LINK = COALESCE(@LINK_SGU,@pSGU_LINK)
		SET @pPERIOD = @pPERIOD1 + RIGHT(CONVERT(VARCHAR(10),@DATE_PP,104),8)
		SET @DAY = (CASE WHEN @DAY > DAY(dbo.DateEndOfMonth(DATEADD(m,1,@DATE_PP))) THEN DAY(dbo.DateEndOfMonth(DATEADD(m,1,@DATE_PP))) ELSE DAY(@SROK) END)
		SET @SROK = dbo.ConvertDMY2Date(DAY(@SROK), MONTH(DATEADD(m,1,@DATE_PP)), YEAR(DATEADD(m,1,@DATE_PP)))
		SET @DATE_PP = CASE WHEN COALESCE(@DATE_DOC,@DATE_PP) > @DATE_PP THEN @DATE_DOC ELSE @DATE_PP END	
		SET @DATE_PROV = CASE WHEN dbo.sa_get_option_by_code('SALARY_OPTIONS_OPT12') = 1 THEN @DATE_PP ELSE NULL END

		---
		SET @trancount = @@TRANCOUNT
		SET IMPLICIT_TRANSACTIONS ON
		BEGIN TRAN 
		COMMIT TRAN
	
		IF @ERROR <> 0
			RETURN @ERROR

		IF @DATE_PROV is not null and not exists(Select * from admin_info Where @DATE_PROV BETWEEN BEGINDATE AND ENDDATE) BEGIN
			ROLLBACK
			SET IMPLICIT_TRANSACTIONS OFF
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
				'Программа формирует дату проводки, равную дате платежки. Но эта дата не попадает в период редактирования!',
				'Укажите другую дату платежки, или отключите в общих настройках по зарплате опцию "В бух. документе автоматически ставить дату" проводки, или измените период редактирования.',
				'SALARY'
			GOTO DO_NEXT
		END

		IF @pD_ACC_LINK IS NULL
		BEGIN
			ROLLBACK
			SET IMPLICIT_TRANSACTIONS OFF
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
				'Не указан номер счета получателя платежа в настройках вида отчисления или в платежке (заявке) - образце!',
				'В меню СПРАВОЧНИКИ\Операции по зарплате\Виды отчислений укажите реквизиты получателя платежа. Либо укажите данные в платежке (заявке) - образце.',
				'SALARY'
			GOTO DO_NEXT
		END		
	
		-- определим максимальный номер 
		Set @NUM_PP = NULL
	
		IF @iCreatePP = 0
			exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'DOCUMENTS_PAY', @NUM_PP output, @LINK_DEP
		ELSE
			exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'BB_ZAYAVKA_KR', @NUM_PP output, @LINK_DEP				
	
		--вначале поставим любой, потом вычислим точнее и заменим
		SET @pS_ACC_LINK = dbo.SA_GET_DEP_ACC(@LINK_DEP, DEFAULT, DEFAULT, DEFAULT)
	
		-- Сохраняем ПП 
		Set @LINK_PP = NULL
		IF @iCreatePP = 0 BEGIN
			exec X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_PP, @DATE_PROV, @SUMMA_PP, '',
				@pKIND, @pS_LINK, @pS_ACC_LINK, @pD_LINK, @pD_ACC_LINK,
				@SROK, @pORDER, @pPAYKIND, @pREASON, --@pSBANK_LINK, @pDBANK_LINK,
				@pTARGETTEXT, /*@pNDSKIND, */@pNDS, @pBK_IN_TGT, @pPRINT_KPP,
				@pNDS_LINK, /*@pDOG_LINK*/ 'DOCUMENTS_PAY'

			-- Сохраняем назначение платежа
			IF COALESCE(@isNALOG,0) <> 0 
				exec X_SAVE_DOCUMENTS_PAY_ADD @LINK_PP OUT, @pDOH_LINK, @pSGU_LINK, @pOKATO, @pP_REASON,
					 @pPERIOD, @pTREBNUM, @DATE_PP, @pZERODATE, @pP_TYPE, @pSTATUS, @UIN
		END
		ELSE BEGIN
			EXEC dbo.X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_PP, @DATE_PROV, @SUMMA_PP, '',
				@pKIND, @pS_LINK, @pS_ACC_LINK, @pD_LINK, @pD_ACC_LINK,
				@SROK, @pORDER, NULL, DEFAULT, 
				@pTARGETTEXT, @pNDS, @pBK_IN_TGT, NULL,
				@pNDS_LINK, 'BB_ZAYAVKA_KR'

			SET @NDS_SUM = ISNULL(@SUMMA_PP * ISNULL(@pNDS,0) / 100,0)
			EXEC dbo.X_SAVE_DOCUMENTS_PAY2 @LINK_PP, NULL, @BO_NUM, NULL, @AVANSE, @NDS_SUM, @SHORT

			EXEC dbo.X_SAVE_DOCUMENTS_PAY_ADD @LINK_PP, @pDOH_LINK, @pSGU_LINK, @pOKATO, @pP_REASON,
				 @pPERIOD, @pTREBNUM, @DATE_PP, @pZERODATE, @pP_TYPE, @pSTATUS, @UIN		
					
		END					 

		INSERT INTO dbo.sdoc_vedom_rko (LINK_VEDOM, LINK_RKO, LINK_PAYS, COMMENT)
		SELECT @LINK_DOC, @LINK_PP, @LINK_PAY, COALESCE(@Osnovanie,'') + ' ' + @OBJ_SNAME + ' №' + CONVERT(VARCHAR(8), @NUM_PP)  + ' от ' + CONVERT(VARCHAR(10),@DATE_PP,104)
	
		Set @ORDER = 0
		SET @SUMMA_PP = 0

		SET @Cur = CURSOR FORWARD_ONLY
		FOR 
	
			SELECT  
				LINK_KBK = F.KBK,
				LINK_DOP_KL = F.DOP_KL,
				USER_ACC = F.USER_ACC,
				CODE_SFIN = F.CODE,
				(CASE WHEN ISNULL(CJ.link_ekr,@LINK_DEFAULT_EKR) = @LINK_211EKR THEN @LINK_DEFAULT_EKR ELSE ISNULL(CJ.link_ekr,@LINK_DEFAULT_EKR) END), 
				P.CODE_ACC, 
				LINK_KAU = COALESCE(LINK_KAU,F.KAU),
				SUMMA=  (CASE WHEN P.WAY_CALC <> 2 OR @LINK_OBJ_DOCUMENTS_DGH = @LINK_OBJ THEN SUM(SUMMA) 
							ELSE
				
							COALESCE((
							Select  
									SUM((CASE WHEN 
										P1.OBJECT = 3
										THEN 1 ELSE -1 END) * CJ1.SUMMA) 
							from 
								dbo.CALCULATE_JURNAL CJ1 INNER JOIN dbo.PAYS P1 ON CJ1.LINK_PAYS = P1.LINK
							where
								ISNULL(CJ1.link_ekr,@LINK_DEFAULT_EKR) = ISNULL(CJ.link_ekr,@LINK_DEFAULT_EKR)
								AND
								( 
										P1.OBJECT = 3
										OR
										P1.OBJECT = 1 AND ISNULL(CJ1.link_ekr,@LINK_DEFAULT_EKR) = @LINK_DEFAULT_EKR
								)									
								AND
								(P1.[OBJECT] = 1 OR P1.[OBJECT] = 3 AND P1.WAY_CALC = 2)
								AND
								YEAR(CJ1.PERIOD_BEGIN) = YEAR(CJ.PERIOD_BEGIN)
								AND 
								MONTH(CJ1.PERIOD_BEGIN) = MONTH(CJ.PERIOD_BEGIN)
								AND
								CJ1.LINK_VKR = CJ.LINK_VKR
								AND
								CJ1.LINK_DEP = CJ.LINK_DEP
							HAVING 
								SUM((CASE WHEN P1.OBJECT = 3 THEN 1 ELSE -1 END) * CJ1.SUMMA) > 0
							),0)
							
						END),
				F.LINK			
			FROM 
				dbo.CALCULATE_JURNAL CJ 
				INNER JOIN dbo.PAYS P ON CJ.LINK_PAYS = P.LINK
				LEFT JOIN  dbo.SAL_SFIN F ON F.LINK = CJ.LINK_VKR
			WHERE 
				LINK_DOC = @LINK_DOC
				AND CJ.LINK_PAYS = @LINK_PAY
				AND F.SOURCE = @Fin_Source
				AND ISNULL(F.LINK_LACC,0) = ISNULL(@LINK_LACC,0)
			GROUP BY 
				F.KBK,CJ.LINK_VKR, F.DOP_KL,F.USER_ACC,F.CODE, 
				CJ.link_ekr,
				P.CODE_ACC, COALESCE(LINK_KAU,F.KAU), P.WAY_CALC, CJ.PERIOD_BEGIN, CJ.LINK_DEP, F.LINK
		OPEN @Cur
	
		FETCH NEXT FROM @Cur INTO @LINK_KBK, @LINK_DOP_KL, @USER_ACC, @CODE_SFIN, @LINK_EKR, @DT_CODE_ACC, @LINK_KAU, @SUM_PROV, @LINK_SAL_SFIN
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN
				IF COALESCE(@SUM_PROV,0) >= 0 BEGIN

					SET @P1 = NULL
					SET @Osnovanie2 = LEFT(@Osnovanie + ' ' + LTRIM(RTRIM(@CODE_SFIN)), 100)
					exec X_UPDATE_G_PROV1 @P1 output, @LINK_PP, NULL, @Osnovanie2, 1
			
					Set @ORDER = @ORDER + 1
					SET @SUMMA_PP = @SUMMA_PP + @SUM_PROV

					IF REPLACE(LTRIM(RTRIM(ISNULL(@DT_CODE_ACC,''))),'.','') = '' BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'Не указан счет кредита в настройках отчисления '+COALESCE(LTRIM(RTRIM(@P_NAME)),''),
							'Укажите в настройках отчисления '+COALESCE(LTRIM(RTRIM(@P_NAME)),'')+' счет кредита.',
							'SALARY'
						GOTO DO_NEXT			
					END

					---
					SET @Account1 = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @DT_CODE_ACC) AND cUser = RTRIM(LTRIM(COALESCE(@USER_ACC,''))))
					SET @DT_FULL_CODE_ACC = @Fin_Source + '.' + @DT_CODE_ACC + CASE WHEN RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> '' THEN '/' + RTRIM(LTRIM(COALESCE(@USER_ACC,''))) ELSE '' END
					
					IF COALESCE(@Account1,0) = 0 BEGIN 
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'В плане счетов не найден счет ' + @DT_FULL_CODE_ACC,
							'Добавьте в план счетов счет ' + @DT_FULL_CODE_ACC,
							'SALARY'
						GOTO DO_NEXT
					END
											
					---
					SET @ACC_CODE = (select top 1 A2.CODE from dbo.S_ACCOUNTS A1 inner join dbo.S_ACCOUNTS A2 on A1.link_self = A2.link
						WHERE A2.LINK = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @DT_CODE_ACC) ) and A2.cSource <> '')
		
					IF  RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) <> '' AND RTRIM(LTRIM(COALESCE(@USER_ACC,''))) = '' BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'У источника финансирования ' + RTRIM(LTRIM(@CODE_SFIN)) + ' не указан пользовательский субсчет, однако у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' есть субсчета',
							'Укажите пользовательский субсчет, либо уберите в плане счетов субсчет у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' с помощью слияния',
							'SALARY'
						GOTO DO_NEXT
					END
		
					--		
					SET @KD_CODE_ACC = (SELECT TOP 1 CODE_ACC FROM DBO.SAL_NASTR_PROV WHERE TYPE_OPER = 1 AND TYPE_DEP = @BUH_TYPE AND TYPE_FUNC = @Fin_Source)

					IF REPLACE(LTRIM(RTRIM(ISNULL(@KD_CODE_ACC,''))),'.','') = '' BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF		
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'Не задан счет для выбытия ср-в с лиц. либо расч. счета для вида организации ' 
							+ ISNULL((SELECT TOP 1 BT_NAME FROM DBO.DICTIONARY_BUH_TYPE WHERE BUH_TYPE = @BUH_TYPE),'')
							+ ' для вида деятельности ' + ISNULL((SELECT TOP 1 NAME FROM DBO.BB_FIN_SOURCE WHERE CODE = @Fin_Source),''),
							'В настройках всех режимов задачи выберите раздел "Настройка счетов для проводок по зарплате" и укажите требуемый счёт в настройке "Счет для выбытия ср-в с лиц. либо расч. счета".',
							'SALARY'
						GOTO DO_NEXT
					END	

					SET @Account2 = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @KD_CODE_ACC) AND cUser = RTRIM(LTRIM(COALESCE(@USER_ACC,''))))
					SET @KD_FULL_CODE_ACC = @Fin_Source + '.' + @KD_CODE_ACC + CASE WHEN RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> '' THEN '/' + RTRIM(LTRIM(COALESCE(@USER_ACC,''))) ELSE '' END

					IF COALESCE(@Account2,0) = 0 BEGIN 
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформирован документ ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'В плане счетов не найден счет ' + @KD_FULL_CODE_ACC,
							'Добавьте в план счетов счет ' + @KD_FULL_CODE_ACC,
							'SALARY'
						GOTO DO_NEXT
					END

					---
					SET @ACC_CODE = (select top 1 A2.CODE from dbo.S_ACCOUNTS A1 inner join dbo.S_ACCOUNTS A2 on A1.link_self = A2.link
						WHERE A2.LINK = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @KD_CODE_ACC) ) and A2.cSource <> '')
	
					IF  RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) <> '' AND RTRIM(LTRIM(COALESCE(@USER_ACC,''))) = '' BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'У источника финансирования ' + RTRIM(LTRIM(@CODE_SFIN)) + ' не указан пользовательский субсчет, однако у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' есть субсчета',
							'Укажите пользовательский субсчет, либо уберите в плане счетов субсчет у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' с помощью слияния',
							'SALARY'
						GOTO DO_NEXT
					END

					---
					IF COALESCE(@Account1,0) > 0 AND COALESCE(@Account2,0) > 0 BEGIN
		
						SET @HOZ_OPER = (SELECT TOP 1 LINK FROM dbo.BX_BPROV_VIBOR_ECON_OPER(@Account1,@Account2))
						IF COALESCE(@HOZ_OPER,0) = 0 BEGIN
							ROLLBACK
							SET IMPLICIT_TRANSACTIONS OFF
							INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
								'Не найдено подходящей хоз. операции для проводки ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account1) + '-' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account2),
								'Вероятно в общих настройках по зарплате указан неправильно счет для выбытия бюдж. или внебюдж средств с лицевого либо расчетного счета',
								'SALARY'
							GOTO DO_NEXT
						END	
				
						set @P2 = null
						exec X_UPDATE_G_PROV2 @P2 output, @P1, NULL, @SUM_PROV, 0, 0, @Osnovanie, @HOZ_OPER, @ORDER
			
					---
					SET @SGU = (SELECT TOP 1 LINK_SGU FROM S_ACCOUNTS_SGU SGU INNER JOIN KOSGU ON SGU.LINK_SGU = KOSGU.LINK WHERE DB_KR = 0 AND ACCOUNT = @Account1)
					IF EXISTS (SELECT p_KASSA FROM dbo.s_accounts WHERE LINK = @Account1 AND p_KASSA = 1)
						SET @SGU = @LINK_EKR
	
					IF COALESCE(@SGU,0) = 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'У счета ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account1) + ' не задано СГУ',
							'Укажите СГУ в настройках счета в плане счетов',
							'SALARY'
						GOTO DO_NEXT
					END	
					
					exec X_UPDATE_G_PROV_AP @P2, 0, @Account1, @LINK_KBK, @LINK_EKR, @LINK_ORG /*Получатель*/, NULL, NULL, NULL, NULL, @LINK_KAU, @pD_ACC_LINK /*Счет получателя*/, NULL, NULL, NULL, @LINK_DOP_KL, NULL, @SGU

					---
					SET @SGU = (SELECT TOP 1 LINK_SGU FROM S_ACCOUNTS_SGU SGU INNER JOIN KOSGU ON SGU.LINK_SGU = KOSGU.LINK WHERE DB_KR = 1 AND ACCOUNT = @Account2)
					IF EXISTS (SELECT p_KASSA FROM dbo.s_accounts WHERE LINK = @Account2 AND p_KASSA = 1)
						SET @SGU = @LINK_EKR
	
					IF COALESCE(@SGU,0) = 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'У счета ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account2) + ' не задано СГУ',
							'Укажите СГУ в настройках счета в плане счетов',
							'SALARY'
						GOTO DO_NEXT
					END
					
					SET @pS_ACC_LINK = dbo.SA_GET_DEP_ACC(@LINK_DEP, @Account2, @LINK_SAL_SFIN, DEFAULT)

					UPDATE dbo.G_PROV SET ACC = @pS_ACC_LINK WHERE LINK = @LINK_PP

					exec X_UPDATE_G_PROV_AP @P2, 1, @Account2, @LINK_KBK, @LINK_EKR, @LINK_DEP /*отправитель*/, NULL, NULL, NULL, NULL, @LINK_KAU, @pS_ACC_LINK /*Счет отправителя*/, NULL, NULL, NULL, @LINK_DOP_KL, NULL, @SGU
					END

				END
			END

			IF @iCreatePP = 1
				EXEC dbo.BB_ZAYAVKA_KR_CREATE_TABLE @LINK_PP
				
			FETCH NEXT FROM @Cur INTO @LINK_KBK, @LINK_DOP_KL, @USER_ACC, @CODE_SFIN, @LINK_EKR, @DT_CODE_ACC, @LINK_KAU, @SUM_PROV, @LINK_SAL_SFIN
		END
		
		CLOSE @Cur
		DEALLOCATE @Cur
		
		--
		UPDATE dbo.G_PROV SET SUMMA = @SUMMA_PP WHERE LINK = @LINK_PP
		
		--
		IF @@TRANCOUNT > @trancount BEGIN
			COMMIT TRAN
			SET IMPLICIT_TRANSACTIONS OFF
		END

		--Платежку с 0 суммой удалим
		IF (select sum(G2.SUMMA)
				from dbo.G_PROV G
				inner join dbo.G_PROV1 G1 on G1.LINK_UP = G.LINK
				inner join dbo.G_PROV2 G2 on G2.LINK_UP = G1.LINK
				where G.LINK = @LINK_PP) = 0
				
				DELETE FROM dbo.G_PROV WHERE LINK = @LINK_PP

		ELSE
		BEGIN			
		
			---Если надо, то сформировать БО
			DECLARE @TestBO tinyint
			exec @TestBO = dbo.XD_TEST_FORM_BO @LINK_PP 

			IF @TestBO = 0
			BEGIN
				create table #tProtocol1(txt varchar(1000), NEW_ROW tinyint, nSTATUS tinyint, nTAB tinyint, ord int identity(1,1))

				insert into #tProtocol1 (txt, NEW_ROW, nSTATUS, nTAB) 
				Exec dbo.XD_FORM_BO @LINK_PP

				IF EXISTS (SELECT * FROM #tProtocol1 WHERE nSTATUS >=1 )
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Обнаружены замечания при формирование БО:', CASE WHEN nSTATUS = 1 THEN 'Предупреждение!' ELSE 'Ошибка!' END + SPACE(1) + LEFT(txt,240), 'Устраните замечания!', 'SALARY'
					FROM #tProtocol1	WHERE nSTATUS >= 1
				
				DROP TABLE #tProtocol1
					
			END	
				
		END		

	
	END
	DO_NEXT:
	FETCH NEXT FROM @Cur1 INTO @DATE_PP, @Osnovanie, @Add_Text, @LINK_PAY, @SUMMA_PP, @LINK_ACC, @LINK_DOH, @Fin_Source, @P_NAME, @SHABLON_LINK, @LINK_SGU, @REG_NUM, @LINK_OBJ, @LINK_ORG, @LINK_LACC
END

CLOSE @Cur1
DEALLOCATE @Cur1

IF @LINK_OBJ_DOCUMENTS_DGH = @LINK_OBJ BEGIN
	/*Создадим платежку на перечисление НДФЛ*/
	SET @P1 = 0
	EXEC dbo.SA_CREATE_PP @LINK_PP = @P1 OUT, @LINK_DOC = @LINK_DOC, @DATE_DOC = @DATE_DOC, @P = 1, @CLEAR_SAL_WORNINGS = 0
END ELSE
	Select LINK_RKO, COMMENT from dbo.sdoc_vedom_rko where LINK_VEDOM = @LINK_DOC

exec X_SALDO_CommitChanges

SET NOCOUNT OFF
Return 0
END



GO


GRANT EXECUTE ON dbo.[SA_CREATE_PP_O] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_DIS_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_DIS_SAVE]

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE [dbo].[SD_DIS_SAVE]
	@varKSparLINK		int	OUTPUT,
	@varKSparNumber	varchar(15) = null,
	@varKSparDate		datetime = null,
	@varKSparRefArche	int = null,
	@varKSparComments	varchar(100) = '',
	@varKSparREF_EMPL	int = null,
	@varKSparDate1		datetime = null,
	@varKSparDate2		datetime = null,
	@varKSparDAYS		numeric(4,0) = 0,	
	@varKSparSTAGYEAR	numeric(4,0) = 0,
	@varKSparSTAGMONTH	numeric(2,0) = 0,
	@varKSparSTAGDAY	numeric(2,0) = 0,
	@varKSparHours		numeric(10,2) = 0.0,	
	@varKSparREF_DOC int = 0,
	@varKSDEP_LINK int,
	@varKSparREF_PERS_KID int = null,
	@varKSparMDEP_NAME varchar(90) = null,
	@varKSparMDEP_ADDR varchar(254) = null
AS
DECLARE @varKSERROR	int, @varKSstrVALUE	varchar(7000),@varKStrancount	int,  @varKSsoLink int, @varKSRowCount INT

--SET @varKStrancount = @@TRANCOUNT
--SET IMPLICIT_TRANSACTIONS ON
--BEGIN TRAN
--COMMIT TRAN

IF @varKSparREF_DOC = 0
	set @varKSparREF_DOC = null


IF @varKSparNumber IS NULL OR @varKSparNumber = ''  or @varKSparDate IS NULL OR @varKSparDate = ''  or @varKSDEP_LINK is null or @varKSDEP_LINK = 0
BEGIN
	RETURN 5
END

----->> проверка больничного , на случай, если дата выходит за период редактирования

DELETE FROM dbo.SAL_WORNINGS WHERE SID = SUSER_SID()

if @varKSparNumber <> '#1' and @varKSparComments <> 'Расчет пособия' --Не учитывать в проверке фиктивные больничные для расчёта суммы пособия по уходу до 1,5 лет
	AND not exists ( select * from dis where  link = @varKSparLINK)
BEGIN

	IF EXISTS (
				select * 
					from dis d  
					inner join user_info i on  1=1
					where d.ref_empl = @varKSparREF_EMPL and d.link_dep = @varKSDEP_LINK 
					--and d.[date] not between i.BEGINDATE and i.ENDDATE  
					and  D.DATE1 <= ISNULL(@varKSparDate2,'20990101') 
					and  ISNULL(D.DATE2,'20990101') >= @varKSparDate1	
				)
	BEGIN
		SET @varKStrancount = @@TRANCOUNT
		SET IMPLICIT_TRANSACTIONS ON
		BEGIN TRAN
		COMMIT TRAN

		INSERT INTO dbo.SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT 
			'Не сохранён больничный с номером "' + COALESCE((LTRIM(RTRIM(@varKSparNumber))),'') + '". ' + LTRIM(RTRIM(d.NAME_EMPL)) + ' имеет период, который пересекается с периодом другого больничного:',
			'Больничный №' + LTRIM(RTRIM(d.NUMBER)) + ' от ' + CONVERT(VARCHAR(10),d.[DATE],104) + '  период с ' + CONVERT(VARCHAR(10),D.DATE1,104) + ' по ' + CONVERT(VARCHAR(10),ISNULL(D.DATE2,'20991231'),104),   
			'Измените период действия больничного листа.',
			'SALARY'
			from dis d  
			inner join user_info i on  1=1
			where d.ref_empl = @varKSparREF_EMPL and d.link_dep = @varKSDEP_LINK 
			--and d.[date] not between i.BEGINDATE and i.ENDDATE  
			and  D.DATE1 <= ISNULL(@varKSparDate2,'20990101') 
			and  ISNULL(D.DATE2,'20990101') >= @varKSparDate1	

		
		WHILE @@TRANCOUNT > @varKStrancount
			COMMIT TRAN	
		RETURN 8
		--	
		 
	END	
END

---
DECLARE @NUM1 VARCHAR(254), @NUM2 VARCHAR(254), @MSG VARCHAR(4000)
SELECT 
	@MSG = 'Больничный лист №' + LTRIM(RTRIM(D1.NUMBER)) + ' уже является продолжением больничного листа №' + LTRIM(RTRIM(D2.NUMBER)) + '!' 
FROM dbo.DIS_ORDER O
	INNER JOIN dbo.SDOC D1 ON D1.LINK = O.CHILD
	INNER JOIN dbo.SDOC D2 ON D2.LINK = O.PARENT
WHERE CHILD = @varKSparREF_DOC AND PARENT = @varKSparLINK


IF @MSG IS NOT NULL
BEGIN
	RAISERROR(@MSG, 11, 1)
	RETURN 5
END
------>>

--Чтобы избежать конфликта с настоящим больничным
if @varKSparNumber = '#1' and @varKSparComments = 'Расчет пособия'
WHILE EXISTS (SELECT * FROM dbo.SDOC_DIS WHERE LINK_EMPL=@varKSparREF_EMPL AND DATE1=@varKSparDate1)
	SET @varKSparDate1 = @varKSparDate1 + 1
	
--	
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
/*Информация о больничном: прежний период больничного, на случай, если его испраили*/
declare @varKSparDateB datetime, @varKSparDateE datetime

SELECT @varKSsoLink = LINK FROM S_OBJECTS WHERE CODE = 'ORDER_DISABILITY_SHEET'
EXECUTE @varKSERROR = SALARY_UPD_SDOC @varKSparLINK OUTPUT, @varKSsoLink, @varKSparNumber,@varKSparDate,@varKSparComments, 0, null, 0, @varKSDEP_LINK
IF @varKSERROR <> 0
		RETURN @varKSERROR

IF not exists(select link_up from sdoc_dis where link_up =@varKSparLINK)
	BEGIN
		INSERT INTO SDOC_DIS WITH (ROWLOCK) (LINK_UP,LINK_EMPL,DATE1,DATE2,TYPE,DAYS,HOURS,NEPR_YEARS,NEPR_MONTH,NEPR_DAY,REF_DOC, REF_PERS_KID , MDEP_NAME, MDEP_ADDR)
			VALUES (@varKSparLINK, @varKSparREF_EMPL, @varKSparDate1,@varKSparDate2,@varKSparRefArche,@varKSparDAYS,@varKSparHours,@varKSparSTAGYEAR,@varKSparSTAGMONTH,@varKSparSTAGDAY,@varKSparREF_DOC, @varKSparREF_PERS_KID,@varKSparMDEP_NAME, @varKSparMDEP_ADDR)
		SELECT @varKSERROR = @@ERROR
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
ELSE
	BEGIN
		/*Прежний период, на случай, если его поменяли*/
		SELECT @varKSparREF_EMPL = REF_EMPL, @varKSparDateB = DATE1, @varKSparDateE = DATE2 FROM dbo.DIS where link = @varKSparLINK

		UPDATE SDOC_DIS WITH (ROWLOCK) SET LINK_EMPL=@varKSparREF_EMPL, DATE1=@varKSparDate1, DATE2 =@varKSparDate2 , TYPE=@varKSparRefArche,
			DAYS = @varKSparDAYS, HOURS=@varKSparHours, NEPR_YEARS=@varKSparSTAGYEAR, NEPR_MONTH=@varKSparSTAGMONTH, NEPR_DAY=@varKSparSTAGDAY,REF_DOC=@varKSparREF_DOC,
			REF_PERS_KID = @varKSparREF_PERS_KID,  MDEP_NAME = @varKSparMDEP_NAME, MDEP_ADDR = @varKSparMDEP_ADDR
		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
IF (SELECT DEKRET FROM NETRUD WHERE LINK = @varKSparRefArche) = 1
	UPDATE EMPL
	SET NOTWORK = 1
	WHERE LINK = @varKSparREF_EMPL

declare @varKSEventText varchar(200)
SET @varKSEventText = 'Листок нетрудоспособности № ' + RTRIM(LTRIM(convert(varchar(15),@varKSparNumber))) + ' от ' + CONVERT(VARCHAR(10),@varKSparDate,104)
EXECUTE WF_GENERATEEVENT 'Сохранение документа', @varKSEventText, @varKSsoLink, 'SDOC',@varKSparLINK

Set @varKSparDateB = (case when coalesce(@varKSparDateB, @varKSparDate1) < @varKSparDate1 then @varKSparDateB else @varKSparDate1 end)
Set @varKSparDateE = (case when coalesce(@varKSparDateE, @varKSparDate2) > @varKSparDate2 then @varKSparDateE else @varKSparDate2 end)
IF dbo.sa_get_option_by_code('TABEL_OPTIONS_OTP_AVTO_BOL') = 1
	exec dbo.SA_SET_DAYS_IN_TABELS @varKSparREF_EMPL, @varKSparDateB, @varKSparDateE, @varKSEventText

WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN

RETURN 0





GO


GRANT EXECUTE ON dbo.[SD_DIS_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].[BB_SAVE_DICTIONARY_STAVKI_SUM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_SAVE_DICTIONARY_STAVKI_SUM]
GO






/*
© Кейсистемс (Keysystems), 2005
*/




CREATE      PROCEDURE dbo.BB_SAVE_DICTIONARY_STAVKI_SUM
	@iLink	 int output,
	@iLinkUp int,
	@dDateB	 datetime,
	@nStavka numeric(7,4)		
AS

DECLARE 	@varKSSQLError	tinyint,
			@varKStrancount	int,
			@varKSEventText	varchar(254),
			@varKSObjLink		int,
			@varKSRowCount 	int 


SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	select @varKSObjLink = LINK from S_OBJECTS where CODE = 'BB_DICTIONARY_STAVKI_SUM'
	select @varKSEventText = 'Справочник ставок по кредитам' +  RTRIM(CODE)+' '+ RTRIM(NAME) from CREDIT_STAVKI where LINK = @iLinkUp
	set @varKSEventText = @varKSEventText + ' ставка на ' + convert(varchar(10),@dDateB, 104)
	IF @iLink is null OR @iLink = 0
	BEGIN
		INSERT INTO dbo.CREDIT_STAVKI_SUM WITH (ROWLOCK) (LINK_UP, DATE_B, STAVKA) 
		VALUES (@iLinkUp, @dDateB, @nStavka)
		SELECT @varKSSQLError = @@ERROR, @iLink = @@IDENTITY
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	ELSE
	BEGIN
		UPDATE dbo.CREDIT_STAVKI_SUM WITH (ROWLOCK) 
		SET LINK_UP = @iLinkUp, DATE_B = @dDateB, STAVKA = @nStavka
		WHERE LINK =@iLink
		SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END	

	
	EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @varKSEventText, @varKSObjLink, 'CREDIT_STAVKI_SUM', @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.[SA_FOT_NLIST]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_FOT_NLIST]

GO

CREATE  PROC [dbo].[SA_FOT_NLIST] (
	@PERIODBEGIN DATETIME, @PERIODEND DATETIME, /* ПЕРИОД */
	@VNS TINYINT = 1 /* ВКЛЮЧАТЬ ВНЕШНИХ СОВМЕСТИТЕЛЕЙ */,
	--ФИЛЬТРЫ
	@CVAL1 CHAR(1), @NOTBORLINK1 INT	/* ОТБОР СОТРУДНИКОВ */,
	@CVAL2 CHAR(1), @NOTBORLINK2 INT	/* ОТБОР ВИДОВ НАЧИСЛЕНИЙ */--,
	) AS

SET NOCOUNT ON

DECLARE @DEP_LINK INT
SELECT @DEP_LINK = DBO.GETCBDEPLINK()


----------------------------------------------
CREATE TABLE #STO_TAR_EMPL (LINK INT, LINK_EMPL INT, FIO VARCHAR(254), TAB VARCHAR(10), PERS_LINK INT, DATE_BEGIN DATETIME,
	DATE_END DATETIME, LINK_POST INT, POST_NAME VARCHAR(254), INST_CHIEF_ACC TINYINT, LINK_KATEG INT, KATEG_NAME VARCHAR(254),
	RAZR_BASE VARCHAR(10), INC_ETS1 TINYINT, INC_ETS1_NAME  VARCHAR(254), INC_ETS1_VALUE TINYINT, INC_ETS2 TINYINT, INC_ETS2_NAME VARCHAR(254),
	INC_ETS2_VALUE TINYINT, INC_ETS3 TINYINT, INC_ETS3_NAME VARCHAR(254), INC_ETS3_VALUE TINYINT, RAZR VARCHAR(10), IRAZR INT,
	DEP_LINK INT, NUM_STAKE NUMERIC(18,2), LINK_KBK  INT, SUBDIV_HEAD INT, SUBDIV_NAME  VARCHAR(254),[STATUS] TINYINT, LINK_TYPE INT, CODE_TYPE VARCHAR(4))

INSERT INTO #STO_TAR_EMPL ( LINK, LINK_EMPL, FIO, TAB, PERS_LINK, DATE_BEGIN, 
	DATE_END, LINK_POST, POST_NAME, INST_CHIEF_ACC, LINK_KATEG, KATEG_NAME,
	RAZR_BASE, INC_ETS1, INC_ETS1_NAME, INC_ETS1_VALUE, INC_ETS2, INC_ETS2_NAME, 
	INC_ETS2_VALUE, INC_ETS3, INC_ETS3_NAME, INC_ETS3_VALUE, RAZR, IRAZR,
	DEP_LINK, NUM_STAKE, LINK_KBK, SUBDIV_HEAD, SUBDIV_NAME, [STATUS], LINK_TYPE, CODE_TYPE)

SELECT 	LINK, LINK_EMPL, FIO, TAB, PERS_LINK, DATE_BEGIN, 
	DATE_END, LINK_POST, POST_NAME, INST_CHIEF_ACC, LINK_KATEG, KATEG_NAME,
	CONVERT(VARCHAR(10),RAZR_BASE), INC_ETS1, INC_ETS1_NAME, INC_ETS1_VALUE, INC_ETS2, INC_ETS2_NAME, 
	INC_ETS2_VALUE, INC_ETS3, INC_ETS3_NAME, INC_ETS3_VALUE, CONVERT(VARCHAR(10),RAZR), RAZR,
	DEP_LINK, T.NUM_STAKE, LINK_KBK, SUBDIV_HEAD, SUBDIV_NAME, COALESCE([STATUS],1), T.LINK_TYPE, T.CODE_TYPE
FROM 
	DBO.SA_EMPLS_W_FN(DEFAULT, @PERIODBEGIN, DEFAULT, @DEP_LINK) T
	LEFT JOIN DBO.EMPL_STATUS(@PERIODBEGIN) S ON S.EMPL_LINK = LINK_EMPL
WHERE

	DEP_LINK = @DEP_LINK
	--НЕ ВКЛЮЧАТЬ ВНЕШНИХ СОВМЕСТИТЕЛЕЙ,ВКЛЮЧАТЬ ВНЕШНИХ СОВМЕСТИТЕЛЕЙ,ВКЛЮЧАТЬ ТОЛЬКО ВНЕШНИХ СОВМЕСТИТЕЛЕЙ
	AND (@VNS = 1 AND COALESCE([STATUS],1) <> 3 OR @VNS = 2 OR @VNS = 3 AND COALESCE([STATUS],1) = 3 ) 
	AND @PERIODBEGIN BETWEEN T.DATE_BEGIN AND COALESCE(T.DATE_END, @PERIODBEGIN)
	AND (	--ОТБОР СОТРУДНИКОВ
		@CVAL1 <> '' AND LINK_EMPL IN (SELECT RECORD FROM DBO.OBJECT_VAR_EMPL WHERE LINK_UP = @NOTBORLINK1)
		OR
		@CVAL1 = '' )



-------------------------------------------
DECLARE @BUFF_ID VARCHAR(20)
EXEC X_GET_TABLE_NAME @BUFF_ID OUTPUT
	
INSERT INTO DBO.BUFFER (ID, LINK)
SELECT DISTINCT @BUFF_ID, LINK_EMPL
	FROM #STO_TAR_EMPL


----------------------------------------------
CREATE TABLE #ALL_PAYS_TAR_EMPL ( LINK_EMPL INT, LINK_TAR_EMPL INT, LINK_LES INT, LINK_PAY INT, NAME_PAY VARCHAR(254) , PERC NUMERIC(18,4), SUMMA NUMERIC(18,4), LINK_KBK INT, WAY_CALC INT, LINK_ETS INT, ISPERCENT INT , ISPERCENT_NAME VARCHAR(10))	
INSERT INTO #ALL_PAYS_TAR_EMPL ( LINK_EMPL, LINK_TAR_EMPL, LINK_LES, LINK_PAY, NAME_PAY, PERC, SUMMA, LINK_KBK, WAY_CALC, LINK_ETS, ISPERCENT, ISPERCENT_NAME)
SELECT 
	PTE.LINK_EMPL, 
	PTE.LINK_SOVM, 
	LINK_LES = NULL, 
	PTE.LINK_PAY, 
	p.NAME, 
	PTE.PERC,  
	SUM(PTE.SUMMA), 
	PTE.LINK_KBK, 
	P.WAY_CALC , 
	P.LINK_ETS, 
	ISPERCENT =  WC.ISPERCENT,
	ISPERCENT_NAME = CASE  WC.ISPERCENT WHEN 0 THEN 'СУММА' 
										WHEN 1 THEN 'ПРОЦЕНТ' 
										WHEN 2 THEN 'КОЭФ.ЕТС' 
										WHEN 3 THEN 'КОЭФ.ПКГ' 
										WHEN 4 THEN 'КОЭФ.' 
					END
FROM 
	DBO.SA_ALL_PAYS_ALL0(DEFAULT, @PERIODBEGIN, @BUFF_ID, @DEP_LINK, DEFAULT) PTE
	INNER JOIN  DBO.PAYS P ON PTE.LINK_PAY = P.LINK
	INNER JOIN 	DBO.WAY_CALC WC ON WC.CODE = P.WAY_CALC
	
WHERE
	(@CVAL2 <> '' AND PTE.LINK_PAY IN (SELECT RECORD FROM [DBO].[OBJECT_VAR_PAYS] WHERE LINK_UP = @NOTBORLINK2)
	OR
	@CVAL2 = '' )
	and WC.[TYPE] = 1
GROUP BY 
	PTE.LINK_EMPL, PTE.LINK_SOVM, PTE.LINK_PAY, PTE.PERC,  PTE.LINK_KBK, P.WAY_CALC, P.LINK_ETS , P.NAME, WC.ISPERCENT



select TE.LINK, TE.LINK_EMPL, TE.FIO, TE.TAB,TE.PERS_LINK, TE.LINK_POST,te.POST_NAME,SUB_HEAD = te.SUBDIV_HEAD,SUB_NAME = TE.SUBDIV_NAME,SFIN.LINK_PAY,SFIN.NAME_PAY, VALUE = (CASE WHEN SFIN.ISPERCENT <>0 THEN  SFIN.PERC ELSE  SFIN.SUMMA END ), ISPERC = SFIN.ISPERCENT_NAME, SFIN.SUMMA
from
#STO_TAR_EMPL AS TE
LEFT JOIN DBO.PERSON AS PERS ON TE.PERS_LINK = PERS.LINK
inner JOIN ( -- ВСЕ СТОЧНИКИ ЗА ПЕРИОД
			SELECT DISTINCT /*PTE.LINK_EMPL, LINK_SOVM = PTE.LINK_TAR_EMPL, LINK_KBK, LINK_ETS*/ LINK_EMPL, LINK_SOVM = PTE.LINK_TAR_EMPL, LINK_LES, LINK_PAY, NAME_PAY, PERC, SUMMA, LINK_KBK, WAY_CALC, LINK_ETS, ISPERCENT,ISPERCENT_NAME
			FROM #ALL_PAYS_TAR_EMPL AS PTE ) AS SFIN ON SFIN.LINK_EMPL = TE.LINK_EMPL AND SFIN.LINK_SOVM = TE.LINK
AND ((select IS_MEMBER ('Зарплата-КС')) = 1	or (select IS_MEMBER ('db_owner')) = 1)	
ORDER BY SFIN.LINK_PAY,TE.FIO



SET NOCOUNT OFF


RETURN 0


GO


GRANT EXECUTE ON dbo.[SA_FOT_NLIST] TO PUBLIC

GO




GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_CREATE_PROV_N]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_CREATE_PROV_N]

GO

CREATE PROCEDURE [dbo].[SA_CREATE_PROV_N]
	@nMonth INT,
	@nYear INT,
	@DEP_LINK int
AS


DECLARE @varKStrancount int, @varKSERROR int


DECLARE @DATE_CRT DATETIME
SET @DATE_CRT = dbo.ConvertDMY2Date(1,@nMonth, @nYear)
SET @DATE_CRT = dbo.DateEndOfMonth(@DATE_CRT)

DECLARE @LinkEKR211 int,
		@LInkEKR213 int

SELECT @LinkEKR211 = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '211'
SELECT @LinkEKR213 = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '213'

/* Для штатников, кроме НДФЛ и ЕСН*/
SELECT 		
		JC.LINK_PAYS AS [LINK_PAYS],
		 RTRIM(P.NAME) AS [NAME_PAY],
		 RTRIM(P.CODE) AS [CODE_PAY],
		 SUM(JC.SUMMA) AS [SUMMA],
		 JC.PERIOD_END AS [DATE2],
		 [TYP_OPER] = (CASE WHEN P.WAY_CALC = 13 THEN (CASE WHEN JC.LINK_EKR = @LinkEKR213 THEN P.LINK_OPER ELSE P.LINK_OPER3 END) ELSE P.LINK_OPER END),
		 [REF_ORG] = JC.LINK_ORG,
		 [REF_BUD] = JC.LINK_VKR,
		 [REF_EKR] = JC.LINK_EKR
into 
	#tmp
FROM 
	dbo.CALCULATE_JURNAL JC left outer join dbo.PAYS P on P.LINK = JC.LINK_PAYS
WHERE 
	NOT JC.LINK_PAYS IS NULL AND JC.LINK_PAYS<>0  AND 
	MONTH(JC.PERIOD_BEGIN)=@nMonth AND YEAR(JC.PERIOD_BEGIN)=@nYear
	AND NOT(JC.LINK_EMPL IS NULL AND JC.PERS_LINK IS NOT NULL)
	AND P.OBJECT = 1
	AND JC.LINK_DEP = @DEP_LINK
GROUP BY 
	P.LINK_OPER,P.LINK_OPER2,P.LINK_OPER3,P.WAY_CALC,JC.LINK_PAYS, JC.PERIOD_END, JC.LINK_ORG, JC.LINK_VKR, JC.LINK_EKR,P.[NAME], P.CODE
UNION ALL
-- Для внештатников 
SELECT 		
	JC.LINK_PAYS AS [LINK_PAYS],
	 RTRIM(P.NAME) AS [NAME_PAY], 
	 RTRIM(P.CODE) AS [CODE_PAY],
	 SUM(JC.SUMMA) AS [SUMMA],
	 JC.PERIOD_END AS [DATE2],
	 [TYP_OPER] = P.LINK_OPER2,
	 [REF_ORG] = NULL,
	 [REF_BUD] = JC.LINK_VKR,
	 [REF_EKR] = JC.LINK_EKR
FROM dbo.CALCULATE_JURNAL JC left outer join dbo.PAYS P on P.LINK = JC.LINK_PAYS
WHERE NOT JC.LINK_PAYS IS NULL AND JC.LINK_PAYS<>0  AND 
	MONTH(JC.PERIOD_BEGIN)=@nMonth AND YEAR(JC.PERIOD_BEGIN)=@nYear
	AND (JC.LINK_EMPL IS NULL AND JC.PERS_LINK IS NOT NULL) 
	AND P.WAY_CALC NOT IN (13,14) AND P.OBJECT = 1   
	AND JC.LINK_DEP = @DEP_LINK
GROUP BY P.LINK_OPER,P.LINK_OPER2,JC.LINK_PAYS, JC.PERIOD_END,JC.LINK_VKR, JC.LINK_EKR, P.[NAME],P.CODE

------------------

DECLARE @P tinyint
SET @P = dbo.sa_get_option_by_code('SALARY_PROV_OPT1')

declare @O_BI_DICTION_KBK int
set @O_BI_DICTION_KBK = (SELECT top 1 LINK FROM S_OBJECTS WHERE CODE = 'BI_DICTION_KBK')

declare @O_DICTIONARY_ITEM int
set @O_DICTIONARY_ITEM = (SELECT top 1 LINK FROM S_OBJECTS WHERE CODE = 'DICTIONARY_ITEM')

DECLARE @Cur CURSOR, @OSNOVANIE VARCHAR(254), @SUM_PROV NUMERIC(20,2), @LINK_GP1 float, @LINK_TYP_OPER int,
	@LINK_PAYS int, @LINK_KBK int, @REF_EKR int, @LINK_KAU int, @LINK_DOP_KL int, @USER_ACC varchar(4), @USER_ACC1 varchar(4),
	@CODE_SFIN VARCHAR(20)

DECLARE @Cur1 CURSOR, @LINK_GP2 int, @NAME_GP2 varchar(250), @ORD_GP2 tinyint, @LINK_GP2_ECONOM_OPER int,
	@NEW_LINK_GP2 int, @d_acc  as int, @new_d_acc as int, @new_k_acc as int, @k_acc     as int, @d_cSource as char(1),	
		@d_cSinth char(3), @d_cAnalit char(2), @d_pKassa bit, @k_cSource char(1), @k_cSinth char(3),	
		@k_cAnalit char(2), @k_pKassa bit, @nFin_Source int, @DEP_LINK_ACC int, @CODE_PAYS VARCHAR(10)

SET @nFin_Source = 1

DECLARE @KBK int, @EKR int, @DEP int, @SUB int, @EMP int, @NOMEN int, @INV int, @KAU int, @DEP_ACC int, @TMC int, 
	@INDATE datetime, @SGU int, @AP1 int, @AP2 int, @AP3 int, @LINK_SAL_SFIN INT

DECLARE @LINK_DOC_SAL INT, @NUM_DOC_SAL VARCHAR(25), @SUM_DOC_SAL NUMERIC(18,2)

INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
select 'Не сформированы проводки для начисления с кодом "' + COALESCE(LTRIM(RTRIM(CODE_PAY)),'') + '"',
	'Не указана типовая операция в настройках этого вида начисления.',
	'Укажите в настройках этого начисления типовую операцию.',
	'SALARY'
FROM #TMP WHERE TYP_OPER IS NULL

-------
SET @Cur = CURSOR FORWARD_ONLY
FOR 

	Select 
		F.CODE,
		LINK_PAYS= (CASE WHEN @P = 1 AND COALESCE(PE.PAYS_EMPL,0) > 0 THEN 0 ELSE t.LINK_PAYS END), 
		NAME_PAY = (CASE WHEN @P = 1 AND COALESCE(PE.PAYS_EMPL,0) > 0 THEN 'Начисление зарплаты' ELSE NAME_PAY END), 
		CODE_PAY = (CASE WHEN @P = 1 AND COALESCE(PE.PAYS_EMPL,0) > 0 THEN '' ELSE CODE_PAY END), 
		TYP_OPER,
		LINK_KBK = F.KBK, 
		REF_EKR,
		LINK_KAU = F.KAU,
		LINK_DOP_KL = F.DOP_KL,
		COALESCE(CAST (F.SOURCE as CHAR(1)),''),
		F.USER_ACC,
		SUMMA= SUM(SUMMA),
		F.LINK 
	from 
		#tmp t 
		inner join dbo.SAL_SFIN F on t.ref_bud = f.link
		left join 
			(select DISTINCT PAYS_EMPL= LINK_PAYS from dbo.PAYS_EMPL
			WHERE @DATE_CRT BETWEEN [DATE] AND COALESCE(dbo.SalaryPaysEmplEndDate(LINK_EMPL,LINK_PAYS, [DATE]),@DATE_CRT)) PE
			ON PE.PAYS_EMPL = t.LINK_PAYS
	group by
		F.CODE, 
		(CASE WHEN @P = 1 AND COALESCE(PE.PAYS_EMPL,0) > 0 THEN 0 ELSE t.LINK_PAYS END),
		(CASE WHEN @P = 1 AND COALESCE(PE.PAYS_EMPL,0) > 0 THEN 'Начисление зарплаты' ELSE NAME_PAY END),
		(CASE WHEN @P = 1 AND COALESCE(PE.PAYS_EMPL,0) > 0 THEN '' ELSE CODE_PAY END),
		TYP_OPER,
		F.KBK,
		REF_EKR,
		F.KAU,
		F.DOP_KL,
		F.SOURCE,
		F.USER_ACC,
		F.LINK
	order by 2
OPEN @Cur
FETCH NEXT FROM @Cur INTO @CODE_SFIN, @LINK_PAYS,@OSNOVANIE,@CODE_PAYS, @LINK_TYP_OPER,@LINK_KBK,@REF_EKR,@LINK_KAU,@LINK_DOP_KL,@nFin_Source,@USER_ACC1,@SUM_PROV,@LINK_SAL_SFIN
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN
		IF COALESCE(@SUM_PROV,0) <> 0 BEGIN

			SET @varKStrancount = @@TRANCOUNT
			SET IMPLICIT_TRANSACTIONS ON
			BEGIN TRAN 
			COMMIT TRAN

			IF @varKSERROR <> 0
				RETURN @varKSERROR
			--------------------

			IF @LINK_TYP_OPER IS NULL BEGIN
				ROLLBACK
				SET IMPLICIT_TRANSACTIONS OFF
				IF COALESCE(@LINK_PAYS,0) > 0 BEGIN
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформированы проводки для начисления с кодом "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '"',
						'Не указана типовая операция в настройках этого вида начисления.',
						'Укажите в настройках этого начисления типовую операцию.',
						'SALARY'
				END
				GOTO DO_NEXT
			END
			
			-- Сохраняем документ
			SELECT @LINK_DOC_SAL = 0, @NUM_DOC_SAL = NULL
			-- определим максимальный номер
			exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'DOCUMENTS_SALARY', @NUM_DOC_SAL output, @DEP_LINK

			exec X_SAVE_DOCUMENTS_SALARY @LINK_DOC_SAL OUT, @NUM_DOC_SAL, @DATE_CRT, @DATE_CRT, @SUM_PROV, @OSNOVANIE, @DEP_LINK, NULL

			SET @LINK_GP1 = NULL
			exec X_UPDATE_G_PROV1 @LINK_GP1 output, @LINK_DOC_SAL, NULL, @OSNOVANIE, 1
			
			-- Сохраняем проводки (по количеству в типовой операции)
			SET @Cur1 = CURSOR FORWARD_ONLY
			FOR select link, name, orders, econ_oper from dbo.g_prov2 where link_up = @LINK_TYP_OPER
			
			OPEN @Cur1
			FETCH NEXT FROM @Cur1 INTO @LINK_GP2, @NAME_GP2, @ORD_GP2, @LINK_GP2_ECONOM_OPER
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @NEW_LINK_GP2 = 0
				EXEC X_UPDATE_G_PROV2 @NEW_LINK_GP2 output, @LINK_GP1, null, @SUM_PROV, 0, 0, @OSNOVANIE, @LINK_GP2_ECONOM_OPER, @ORD_GP2
				IF @NEW_LINK_GP2 > 0 
				BEGIN
					-- проверим если ли в счете код источника финансирования, если нет - добавим
					SELECT	@d_acc = account
					FROM G_PROV_AP WHERE link_UP = @LINK_GP2 and DB_KR = 0

					IF COALESCE(@d_acc,0)= 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформированы проводки для начисления с кодом "' + CASE WHEN COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') <> '' THEN 
					 				COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') ELSE  (Select TOP 1 CODE_PAY from #tmp WHERE TYP_OPER = @LINK_TYP_OPER) END + '"',
							'В настройках указана типовая операция, в которой отсутствует счет дебета' ,
							'Исправьте типовую операцию, указанную в настройках этого начисления',
							'SALARY'
						GOTO DO_NEXT
					END

					--Пользовательский субсчет может быть задан в типовой операции, но требовать его для дебета не нужно, если он задан в источнике финансирования
					SET @d_cSource = CAST (@nFin_Source as CHAR(1))
					SELECT @d_cSinth=cSinth, @d_cAnalit=cAnalit, @USER_ACC = (CASE WHEN COALESCE(RTRIM(LTRIM(cUser)),'') <> '' THEN cUser ELSE @USER_ACC1 END) 
  					FROM s_accounts 
					WHERE link = @d_acc
					
					SET @d_acc = NULL
					-- выбираем @d_acc с учётом вида деятельности, заданного в настройках источника финансирования
					SELECT top 1 @d_acc=link, @d_pKassa = p_KASSA 
					FROM s_accounts
					WHERE 	cSource = @d_cSource AND @d_cSinth = cSinth AND @d_cAnalit=cAnalit

					--Если в плане счетов стоит пользовательский субсчет, а в источнике финансирования или типовой операции не указан
					IF COALESCE(@USER_ACC,0)= 0 and exists (Select link from s_accounts where cSource = @d_cSource AND @d_cSinth = cSinth AND @d_cAnalit=cAnalit and len(cUser) > 0)
					BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформированы проводки для начисления с кодом "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '"',
								'В типовой операции начисления "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '" или источнике финанансирования "' + COALESCE(LTRIM(RTRIM(@CODE_SFIN)),'') + '" не указан пользовательский субсчет'  
								 + 'но в плане счетов у счета ' + COALESCE(@d_cSource,'') + '.' + COALESCE(@d_cSinth,'') + '.' + COALESCE(@d_cAnalit,'') + ' пользовательский субсчет задан!',
								'Укажите пользовательский субсчет в настройках источника финансирования "' + COALESCE(LTRIM(RTRIM(@CODE_SFIN)),'') + '" или уберите субсчет для счета ' + COALESCE(@d_cSource,'') + '.' + COALESCE(@d_cSinth,'') + '.' + COALESCE(@d_cAnalit,'')+  ' из плана счетов',
								'SALARY'
						GOTO DO_NEXT
					END

					IF COALESCE(@d_acc,0)= 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформированы проводки для начисления с кодом "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '"',
								'В источнике финанансирования "' + COALESCE(LTRIM(RTRIM(@CODE_SFIN)),'') + '" указан вид деятельности "' + ISNULL((SELECT TOP 1 FS.CODE + '.' + FS.NAME FROM dbo.BB_FIN_SOURCE FS WHERE FS.CODE = @nFin_Source),'') +  '", ' 
								 + 'но в плане счетов нет счета ' + COALESCE(@d_cSource,'') + '.' + COALESCE(@d_cSinth,'') + '.' + COALESCE(@d_cAnalit,''),
								'Добавьте в план счетов такой счет, либо измените вид деятельности в настройках источника финансирования',
								'SALARY'
						GOTO DO_NEXT
					END

					IF COALESCE(RTRIM(LTRIM(@USER_ACC)),'') <> ''
					BEGIN
						SET @new_d_acc = NULL
						SELECT top 1 @new_d_acc=link, @d_pKassa = p_KASSA 
						FROM s_accounts
						WHERE 	cSource = @d_cSource AND @d_cSinth = cSinth AND @d_cAnalit=cAnalit AND cUser = @USER_ACC

						IF @new_d_acc is not null 
							SET @d_acc=@new_d_acc
						ELSE BEGIN
							ROLLBACK
							SET IMPLICIT_TRANSACTIONS OFF
							INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформированы проводки для начисления с кодом "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '"',
								'В источнике финанансирования "' + COALESCE(LTRIM(RTRIM(@CODE_SFIN)),'') + '" указана пользовательская часть счета, ' 
								 + 'но в плане счетов нет счета ' + COALESCE(@d_cSource,'') + '.' + COALESCE(@d_cSinth,'') + '.' + COALESCE(@d_cAnalit,'') + '/' + COALESCE(@USER_ACC,''),
								'Добавьте в план счетов такой счет, либо уберите пользовательскую часть счета из настроек источника финансирования',
								'SALARY'
							GOTO DO_NEXT
						END
					END

					--===========================================================
					
					SELECT	@k_acc = account
					FROM G_PROV_AP WHERE link_UP = @LINK_GP2 and DB_KR = 1
					
					IF COALESCE(@k_acc,0) = 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформированы проводки для начисления с кодом "' + CASE WHEN COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') <> '' THEN 
					 				COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') ELSE  (Select TOP 1 CODE_PAY from #tmp WHERE TYP_OPER = @LINK_TYP_OPER) END + '"',
							'В настройках указана типовая операция, в которой отсутствует счет кредита' ,
							'Исправьте типовую операцию, указанную в настройках этого начисления',
							'SALARY'
						GOTO DO_NEXT
					END


					--Пользовательский субсчет может быть задан в типовой операции. Но если он задан в источнике, то должен быть в дебете обязательно
					SET @k_cSource = CAST (@nFin_Source as CHAR(1))
					SELECT @k_cSinth=cSinth, @k_cAnalit=cAnalit, @USER_ACC = (CASE WHEN COALESCE(RTRIM(LTRIM(@USER_ACC1)),'') <> '' THEN @USER_ACC1 ELSE cUser END)
  					FROM s_accounts 
					WHERE link = @k_acc 
 
 					SET @k_acc = NULL
					-- выбираем @@k_acc с учётом вида деятельности, заданного в настройках источника финансирования
					SELECT top 1 @k_acc=link, @k_pKassa = p_KASSA 
					FROM s_accounts
					WHERE 	cSource = @k_cSource AND @k_cSinth = cSinth AND	@k_cAnalit=cAnalit AND cUser = @USER_ACC

					--Если в плане счетов стоит пользовательский субсчет, а в источнике финансирования или типовой операции не указан
					IF COALESCE(@USER_ACC,0)= 0 and exists (Select link from s_accounts where cSource = @k_cSource AND @k_cSinth = cSinth AND @k_cAnalit=cAnalit and len(cUser) > 0)
					BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформированы проводки для начисления с кодом "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '"',
								'В типовой операции начисления "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '" или источнике финанансирования "' + COALESCE(LTRIM(RTRIM(@CODE_SFIN)),'') + '" не указан пользовательский субсчет'  
								 + 'но в плане счетов у счета ' + COALESCE(@k_cSource,'') + '.' + COALESCE(@k_cSinth,'') + '.' + COALESCE(@k_cAnalit,'') + ' пользовательский субсчет задан!',
								'Укажите пользовательский субсчет в настройках источника финансирования "' + COALESCE(LTRIM(RTRIM(@CODE_SFIN)),'') + '" или уберите субсчет для счета ' + COALESCE(@k_cSource,'') + '.' + COALESCE(@k_cSinth,'') + '.' + COALESCE(@k_cAnalit,'')+  ' из плана счетов',
								'SALARY'
						GOTO DO_NEXT
					END

					IF COALESCE(@k_acc,0)= 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформированы проводки для начисления с кодом "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '"',
								'В источнике финанансирования "' + COALESCE(LTRIM(RTRIM(@CODE_SFIN)),'') + '" указан вид деятельности "' + ISNULL((SELECT TOP 1 FS.CODE + '.' + FS.NAME FROM dbo.BB_FIN_SOURCE FS WHERE FS.CODE = @nFin_Source),'') +  '", ' 
								 + 'но в плане счетов нет счета ' + COALESCE(@k_cSource,'') + '.' + COALESCE(@k_cSinth,'') + '.' + COALESCE(@k_cAnalit,''),
								'Добавьте в план счетов такой счет, либо измените вид деятельности в настройках источника финансирования',
								'SALARY'
						GOTO DO_NEXT
					END

					IF COALESCE(RTRIM(LTRIM(@USER_ACC)),'') <> ''
					BEGIN
						SET @new_k_acc = NULL
						SELECT top 1 @new_k_acc=link, @k_pKassa = p_KASSA 
						FROM s_accounts
						WHERE 	cSource = @k_cSource AND @k_cSinth = cSinth AND	@k_cAnalit=cAnalit AND cUser = @USER_ACC

						IF @new_k_acc is not null 
							SET @k_acc = @new_k_acc
						ELSE BEGIN
							ROLLBACK
							SET IMPLICIT_TRANSACTIONS OFF
							INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформированы проводки для начисления с кодом "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '"',
								'В источнике финанансирования "' + COALESCE(LTRIM(RTRIM(@CODE_SFIN)),'') + '" указана пользовательская часть счета, '
								 + 'но в плане счетов нет счета ' + COALESCE(@k_cSource,'') + '.' + COALESCE(@k_cSinth,'') + '.' + COALESCE(@k_cAnalit,'') + '/' + COALESCE(@USER_ACC,''),
								'Добавьте в план счетов такой счет, либо уберите пользоательскую часть счета из настроек источника финансирования',
								'SALARY'
							GOTO DO_NEXT
						END
					END

					IF  COALESCE(@d_acc,0) > 0 AND COALESCE(@k_acc,0) > 0 BEGIN

						SELECT	
							@KBK = COALESCE(KBK,@LINK_KBK), @EKR = COALESCE(EKR,@REF_EKR), @DEP = COALESCE(DEP,@DEP_LINK), 
							@SUB = SUB, @EMP = EMP, @NOMEN = NOMEN, @INV = INV,
							@KAU = COALESCE(KAU,@LINK_KAU), @TMC = TMC, @INDATE = INDATE, @SGU = SGU,
							@AP1 = AP1, @AP2 = COALESCE(AP2,@LINK_DOP_KL), @AP3 = AP3
						FROM G_PROV_AP WHERE link_UP = @LINK_GP2 and DB_KR = 0

						-- Сохранаем Дт проводки
						if @d_pKassa = 1
							set @SGU = @EKR

						SET @DEP_ACC = dbo.SA_GET_DEP_ACC(@DEP_LINK, @k_acc, @LINK_SAL_SFIN, DEFAULT)
						UPDATE dbo.G_PROV SET ACC = @DEP_ACC WHERE LINK = @LINK_DOC_SAL

						EXEC X_UPDATE_G_PROV_AP @NEW_LINK_GP2, 0, @d_acc, @KBK, @EKR, @DEP,
							@SUB, @EMP, @NOMEN, @INV, @KAU, @DEP_ACC, @TMC, 
							@INDATE, @AP1, @AP2, @AP3, @SGU
	
						SELECT	
							@KBK = COALESCE(KBK,@LINK_KBK), @EKR = COALESCE(EKR,@REF_EKR), @DEP = COALESCE(DEP,@DEP_LINK), 
							@SUB = SUB, @EMP = EMP, @NOMEN = NOMEN, @INV = INV,
							@KAU = COALESCE(KAU,@LINK_KAU), @TMC = TMC, @INDATE = INDATE, @SGU = SGU,
							@AP1 = AP1, @AP2 = COALESCE(AP2,@LINK_DOP_KL), @AP3 = AP3
						FROM G_PROV_AP WHERE link_UP = @LINK_GP2 and DB_KR = 1
	
						-- Сохранаем Кт проводки
						if @k_pKassa = 1
							set @SGU = @EKR

						EXEC X_UPDATE_G_PROV_AP @NEW_LINK_GP2, 1, @k_acc, @KBK, @EKR, @DEP,
							@SUB, @EMP, @NOMEN, @INV, @KAU, @DEP_ACC, @TMC, 
							@INDATE, @AP1, @AP2, @AP3, @SGU

					END

				END

				FETCH NEXT FROM @Cur1 INTO @LINK_GP2, @NAME_GP2, @ORD_GP2, @LINK_GP2_ECONOM_OPER
			
			END
			CLOSE @Cur1
			DEALLOCATE @Cur1

			IF @@TRANCOUNT > @varKStrancount BEGIN
				COMMIT TRAN
				SET IMPLICIT_TRANSACTIONS OFF
			END

			---Если надо, то сформировать БО
			DECLARE @TestBO tinyint
			exec @TestBO = dbo.XD_TEST_FORM_BO @LINK_DOC_SAL 
			IF @TestBO = 0
			BEGIN
			
				create table #tProtocol1(txt varchar(1000), NEW_ROW tinyint, nSTATUS tinyint, nTAB tinyint, ord int identity(1,1))

				insert into #tProtocol1 (txt, NEW_ROW, nSTATUS, nTAB) 
				Exec dbo.XD_FORM_BO @LINK_DOC_SAL

				IF EXISTS (SELECT * FROM #tProtocol1 WHERE nSTATUS >=1 )
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Обнаружены замечания при формирование БО:', CASE WHEN nSTATUS = 1 THEN 'Предупреждение!' ELSE 'Ошибка!' END + SPACE(1) + LEFT(txt,240), 'Устраните замечания!', 'SALARY'
					FROM #tProtocol1	WHERE nSTATUS >= 1
				
				DROP TABLE #tProtocol1
					
			END	

		END

	END

	DO_NEXT:

	FETCH NEXT FROM @Cur INTO @CODE_SFIN, @LINK_PAYS,@OSNOVANIE,@CODE_PAYS,@LINK_TYP_OPER,@LINK_KBK,@REF_EKR,@LINK_KAU,@LINK_DOP_KL,@nFin_Source,@USER_ACC1,@SUM_PROV,@LINK_SAL_SFIN
END

CLOSE @Cur
DEALLOCATE @Cur

exec X_SALDO_CommitChanges

Return 0


GO


GRANT EXECUTE ON dbo.[SA_CREATE_PROV_N] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SZV_K_PACHKA_CALC_Buffer]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZV_K_PACHKA_CALC_Buffer]

GO

CREATE   PROCEDURE [dbo].SA_SZV_K_PACHKA_CALC_Buffer (@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.SZV_K_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, @type_sved TINYINT 

SELECT @type_sved = type_sved
FROM dbo.SZV_K_PACHKA WHERE LINK = @link

IF @type_sved = 2
begin  
	SELECT @Year = year(p.[date]), /*@PER = PER_EDT,*/ @MONTH_END = month(p.[date])
	FROM 
	dbo.SZV_K_PACHKA p1 
	INNER JOIN dbo.SZV_K_PACHKA p  ON p.link = p1.link_ishod
	WHERE p1.LINK = @link
end 
else 
begin
	SELECT @Year = year([date])/*, @PER = PER*/, @MONTH_END = month([date])
	FROM dbo.SZV_K_PACHKA WHERE LINK = @link
end 
DECLARE @PeriodBegin datetime, @PeriodEnd datetime

SET @MONTH_BEG = 1
SET @MONTH_END = (CASE WHEN @MONTH_END < (@MONTH_BEG+3-1) THEN @MONTH_END ELSE (@MONTH_BEG+3-1) END)

SELECT @PeriodBegin = null, @PeriodEnd = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,12,'2001'))

--ВЫДЕЛЕНИЕ КАТЕГОРИЙ ФИЗ.ЛИЦ
--ИНВАЛИДЫ
/*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
*/
SELECT * FROM SZV_K_SVEDENIA
--forma в отчётности за 2013 год содержит тип договора (1 трудовой, 2 ГПХ)
insert into dbo.SZV_K_SVEDENIA (link_up, orders, link_pers, dper_vn_m, dper_vn_d,dper_oz_m, dper_oz_d, terr_usl, terr_koef, all_stazh_y, all_stazh_m, all_stazh_d,date_beg,date_end)
Select distinct @link, 0, B.link,  
	DIS_M = 0,
	DIS_D = 0,
	VAC_M = 0,
	VAC_D = 0,
	'', 0,
	0,0,0,
	NULL,
	NULL
from 
	(	SELECT B.LINK, DOG = 1 
		FROM 
			#PERSON B
			INNER JOIN dbo.EMPL E ON E.pers_link = B.LINK AND E.DEP_LINK = @DEP_LINK
		UNION 
		SELECT B.LINK, DOG = 2 
		FROM 
			#PERSON B
			INNER JOIN dbo.SALARY_REESTR_DGH DGH ON DGH.PERS_LINK = B.LINK AND DGH.DEP_LINK = @DEP_LINK
	) B


IF @TYPE_SVED != 3
	begin  
	---СВЕДЕНИЯ О СТАЖЕ
	----------------------------------------------------------------------------
	CREATE TABLE #PERIODY (link int identity(1,1), link_face INT/*, LINK_KATEG INT*/, date1 datetime, date2 datetime, [type] int, NUM_STAKE NUMERIC(5,2), [IS_DOP] VARCHAR(20))

	--/*Стаж сотрудников*/
	INSERT INTO 
		#PERIODY (link_face/*, LINK_KATEG*/, date1, date2, type)
	SELECT 	DISTINCT
		PERS_LINK/*, KAT_LINK*/,
		CASE WHEN S.DATE_BEG < (case when P.DATE_BEGIN <= @PeriodEND then P.DATE_BEGIN else @PeriodBegin end)
			THEN (case when P.DATE_BEGIN <= @PeriodEND 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.SZV_K_SVEDENIA S ON S.LINK_PERS = B.LINK
		INNER JOIN dbo.SD_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 <= @PeriodEnd then DGH.DATE1 else @PeriodBegin end)
				THEN (case when DGH.DATE1 <= @PeriodEND then DGH.DATE1 else @PeriodBegin end)
				ELSE S.DATE_BEG
			END,
		date2 = CASE WHEN S.DATE_END > (case when coalesce(DGH.DATE2,@PeriodEnd) <= @PeriodEnd then coalesce(DGH.DATE2,@PeriodEnd) else @PeriodEnd end)
				THEN (case when coalesce(DGH.DATE2,@PeriodEnd) <= @PeriodEnd then coalesce(DGH.DATE2,@PeriodEnd) else @PeriodEnd end)
				ELSE S.DATE_END
			END,
		[type] = 0
	INTO #DGH	
	FROM
		#PERSON B
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
		INNER JOIN dbo.SALARY_REESTR_DGH DGH ON S.LINK_PERS = DGH.PERS_LINK
	WHERE 
		S.LINK_UP = @link
		AND
		DGH.DEP_LINK = @DEP_LINK
		and
		DGH.DATE1 <= @PeriodEnd
		and
		coalesce(DGH.DATE2,'20990101') >= @PeriodBegin



	-- Периоды в сведениях впишем в периоды работы
	SELECT LINK_FACE, DB = MIN(DATE1), DE = MAX(DATE2)
	INTO #WORK
	FROM #PERIODY
	GROUP BY LINK_FACE

	UPDATE S SET 
		S.DATE_BEG = CASE WHEN W.DB < S.DATE_BEG THEN S.DATE_BEG ELSE W.DB END,
		S.DATE_END = CASE WHEN W.DE > S.DATE_END THEN S.DATE_END ELSE W.DE END
	FROM 
		dbo.SZV4_SVEDENIA S INNER JOIN #WORK W ON S.LINK_PERS = W.LINK_FACE
	WHERE 
		S.LINK_UP = @link

/*	--
	CREATE TABLE #ADD_TYPE (
		[type] INT IDENTITY(1,1),
		[TERR_USL_TRUD] int NULL ,
		[TERR_RK] numeric(3, 2) NULL ,
		[OSOB_USL_TRUD] int NULL ,
		[COD_POS_SPISOK] int NULL ,
		[COD_POS_SPISOK2] int NULL ,
		[USL_DOSROCH_PENS] int NULL ,
		[STAVKA_PED_MED] numeric(3, 2) NULL,
		[VID] VARCHAR(20),
		[IS_DOP] VARCHAR(20),
		[COD_SPO_USL_TRUD] INT NULL
	)	
	--Новые типы
	INSERT INTO #ADD_TYPE 
	SELECT DISTINCT ISNULL(TERR_USL_TRUD,0), ISNULL(TERR_RK,0), ISNULL(OSOB_USL_TRUD,0), ISNULL(COD_POS_SPISOK,0), ISNULL(COD_POS_SPISOK2,0), ISNULL(USL_DOSROCH_PENS,0), ISNULL(STAVKA_PED_MED,0), VID = 'ADD_TYPE', IS_DOP = '', ISNULL([COD_SPO_USL_TRUD],0)
	FROM dbo.staff
	WHERE ISNULL(TERR_USL_TRUD,0) <> 0 OR ISNULL(TERR_RK,0) <> 0 OR ISNULL(OSOB_USL_TRUD,0) <> 0 OR ISNULL(COD_POS_SPISOK,0) <> 0 OR ISNULL(COD_POS_SPISOK2,0) <> 0 OR ISNULL(USL_DOSROCH_PENS,0) <> 0 OR ISNULL(STAVKA_PED_MED,0) <> 0 OR ISNULL([COD_SPO_USL_TRUD],0) <> 0
*/
/*	--
	DECLARE @MAX_TYPE INT
	SET @MAX_TYPE = ISNULL((SELECT MAX(type) FROM #ADD_TYPE),0)

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	VALUES ('TMP_TYPE', '')

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	VALUES ('PERIOD1', 'ДЕКРЕТ')

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	SELECT DISTINCT
		'PERIOD2',
		ISNULL(V.IS_DOP,'ДЕТИ')
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK 
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID V ON V.LINK = IV.TYPE_LINK
		INNER JOIN (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7 AND ISNULL(VV.NOT_LGOT_EXPIR,0) = 0) VV ON VV.LINK = IV.TYPE_LINK
		left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and coalesce(ivb.active,0) = 1
	where 
		S.LINK_UP = @link
		AND		
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	SELECT DISTINCT
		'PERIOD2LS',
		ISNULL(V.IS_DOP,'ДЕТИ')
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK 
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID V ON V.LINK = IV.TYPE_LINK
		INNER JOIN (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7 AND ISNULL(VV.NOT_LGOT_EXPIR,0) = 1) VV ON VV.LINK = IV.TYPE_LINK
		left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and coalesce(ivb.active,0) = 1
	where 
		S.LINK_UP = @link
		AND		
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin		

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	VALUES ('PERIOD3', 'ВРНЕТРУД')

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	Select DISTINCT
		'PERIOD4',
		ISNULL(VV.IS_DOP,'АДМИНИСТР')
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK  
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID VV ON VV.LINK = IV.type_link AND VV.NO_SAL = 1
		left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and coalesce(ivb.active,0) = 1
	where
		S.LINK_UP = @link
		AND		 	
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin

	--ПРОЧИЕ КОДЫ ДЛЯ ВИДОВ ОТПУСКОВ
	INSERT INTO #ADD_TYPE (VID, IS_DOP) 	
	SELECT LEFT('P_' + LTRIM(RTRIM(CODE)),20), IS_DOP
	FROM dbo.VACATION_VID 
	WHERE IS_DOP IS NOT NULL
		AND NOT EXISTS (SELECT * FROM #ADD_TYPE WHERE VID = LEFT('P_' + LTRIM(RTRIM(CODE)),20))

	--Периоды работы на должности c параметрами для персучета
	INSERT INTO 
		#PERIODY (link_face, LINK_KATEG, date1, date2, [type], NUM_STAKE)
	SELECT DISTINCT 
		link_face = E.PERS_LINK, S.LINK_KATEG,
		date1 = CASE WHEN S.DATE_BEG < (case when st.DATE_BEGIN >= @PeriodBegin then st.DATE_BEGIN else @PeriodBegin end)
					THEN (case when st.DATE_BEGIN >= @PeriodBegin then st.DATE_BEGIN else @PeriodBegin end)
					ELSE S.DATE_BEG
				END,
		date2 = CASE WHEN 
						(CASE WHEN S.DATE_END > (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
							THEN (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
							ELSE S.DATE_END
						END)
							> (case when st.DATE_END <= @PeriodEnd then st.DATE_END else @PeriodEnd end)
					THEN 
						(case when st.DATE_END <= @PeriodEnd then st.DATE_END else @PeriodEnd end)
					ELSE 
						(CASE WHEN S.DATE_END > (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
							THEN (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
							ELSE S.DATE_END
						END)
				END,	
		ISNULL(T.[type],0),
		ISNULL(im.NUM_STAKE,0)--, ST.*
	FROM 
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK	
		INNER JOIN dbo.sa_item_move im ON im.EMPL_LINK = e.link
		inner join dbo.staff_head sh on sh.link = STAFF_LINK
		inner join dbo.staff st on st.link_up = sh.link
		LEFT JOIN dbo.ITEM_DIS_FACE U on E.link = U.empl_link AND U.ACTIVE=1	
		left join #ADD_TYPE T on 
				ISNULL(st.TERR_USL_TRUD,0) = ISNULL(T.TERR_USL_TRUD,0) 
				AND ISNULL(st.TERR_RK,0) = ISNULL(T.TERR_RK,0) 
				AND ISNULL(st.OSOB_USL_TRUD,0) = ISNULL(T.OSOB_USL_TRUD,0) 
				AND ISNULL(st.COD_POS_SPISOK,0) = ISNULL(T.COD_POS_SPISOK,0) 
				AND ISNULL(st.COD_POS_SPISOK2,0) = ISNULL(T.COD_POS_SPISOK2,0) 
				AND ISNULL(st.USL_DOSROCH_PENS,0) = ISNULL(T.USL_DOSROCH_PENS,0) 
				AND ISNULL(st.STAVKA_PED_MED,0) = ISNULL(T.STAVKA_PED_MED,0) 
				AND ISNULL(st.[COD_SPO_USL_TRUD],0) = ISNULL(T.[COD_SPO_USL_TRUD],0)
	where 
		S.LINK_UP = @link
		AND
		IM.NUM_STAKE >= 1 
		AND
		IM.[STATUS] <> 2 --Совместителям доп. тариф не считаем
		AND
		im.DATE_BEGIN <= @PeriodEnd and im.DATE_END3 >= @PeriodBegin
		and 
		st.DATE_BEGIN <= @PeriodEnd and st.DATE_END >= @PeriodBegin
		AND
		T.[TYPE] IS NOT NULL AND T.VID = 'ADD_TYPE'
		AND
		COALESCE(U.DIS_DATE,'20990101') >= @PeriodBegin
	order by
		E.PERS_LINK

	---**************************************

	DECLARE @TMP_TYPE INT
	SET @TMP_TYPE = (SELECT TOP 1 TYPE FROM #ADD_TYPE WHERE VID = 'TMP_TYPE')

	/*Перерыв - отпуска без кодов (для корр. льготных периодов)*/
	INSERT INTO 
		#PERIODY (link_face, LINK_KATEG, date1, date2, [type])
	Select DISTINCT 
		E.pers_link, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			THEN (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when ISNULL(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then ISNULL(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			THEN (case when ISNULL(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then ISNULL(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		ISNULL( (SELECT TOP 1 TYPE FROM #ADD_TYPE AT WHERE AT.VID = LEFT('P_' + LTRIM(RTRIM(VV.CODE)),20) AND AT.IS_DOP = VV.IS_DOP ), @TMP_TYPE)
	FROM 
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK	
		inner join dbo.item_vacation iv on E.link = iv.EMPL_LINK 
		inner join dbo.orders o on iv.order_link=o.link
		-- Только отпуск, помеченный как "Не включать в льготный стаж", --Не административный (Для него свой код)
		INNER JOIN dbo.VACATION_VID VV ON VV.LINK = IV.type_link AND ISNULL(VV.NOT_LGOT_EXPIR,0) = 1 AND NO_SAL <> 1
		left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and ISNULL(ivb.active,0) = 1
	--	LEFT JOIN #PERIODY P ON P.link_face = P.LINK AND P.LINK_KATEG = S.LINK_KATEG AND P.[TYPE] = @TMP_TYPE
	where
		S.LINK_UP = @link
		AND 	
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		ISNULL(ISNULL(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin
		and -- Не по уходу за ребенком (Для него свой код)
		IV.type_link not in (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7)
		--AND
		--P.link_face IS NOT NULL AND 

	/*Перерыв - командировки без кодов (для корр. льготных периодов)*/	
	INSERT INTO 
		#PERIODY (link_face, LINK_KATEG, date1, date2, [type])
	SELECT DISTINCT
		E.pers_link, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when T.date_begin >= @PeriodBegin then T.date_begin else @PeriodBegin end)
			THEN (case when T.date_begin >= @PeriodBegin then T.date_begin else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when ISNULL(ITL.NEW_DATE_END,T.date_end) <= @PeriodEnd then ISNULL(ITL.NEW_DATE_END,T.date_end) else @PeriodEnd end)
			THEN (case when ISNULL(ITL.NEW_DATE_END,T.date_end) <= @PeriodEnd then ISNULL(ITL.NEW_DATE_END,T.date_end) else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		@TMP_TYPE
	FROM 
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK	
		inner join dbo.item_travel T on E.link = T.EMPL_LINK
		left join dbo.ITEM_TRAVEL_LONG ITL on ITL.TRAVEL_LINK = T.LINK and ISNULL(ITL.ACTIVE,0) = 1	
	WHERE
		S.LINK_UP = @link
		AND 	
		E.DEP_LINK = @DEP_LINK
		AND 
		T.ACTIVE = 1 
		AND 
		T.DATE_BEGIN <= @PeriodEnd
		AND 
		ISNULL(ISNULL(ITL.NEW_DATE_END,T.date_end),'20990101') >= @PeriodBegin
		
	/*Перерыв - Больничный по Беременности и родам ДЕКРЕТ*/
	SET @TMP_TYPE = (SELECT TOP 1 TYPE FROM #ADD_TYPE WHERE VID = 'PERIOD1')

	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
	SELECT 
		E.PERS_LINK, LINK_KATEG, 
		CASE WHEN S.DATE_BEG < (case when D.date1 >= @PeriodBegin then D.date1 else @PeriodBegin end)
			THEN (case when D.date1 >= @PeriodBegin then D.date1 else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when D.date2 <= @PeriodEnd then D.date2 else @PeriodEnd end)
			THEN (case when D.date2 <= @PeriodEnd then D.date2 else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		@TMP_TYPE
	FROM 
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK
		inner join dbo.SDOC_DIS D on E.LINK = D.LINK_EMPL
		INNER JOIN dbo.NETRUD N ON N.LINK = [TYPE] AND N.DEKRET = 1
	WHERE 
		S.LINK_UP = @link
		AND	
		E.DEP_LINK = @DEP_LINK
		and
		D.date1 <= @PeriodEnd
		and
		coalesce(D.date2,'20990101') >= @PeriodBegin

	/*Перерыв - Больничный ВРНЕТРУД*/
	SET @TMP_TYPE = (SELECT TOP 1 TYPE FROM #ADD_TYPE WHERE VID = 'PERIOD3')

	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
	SELECT 
		E.PERS_LINK, LINK_KATEG, 
		CASE WHEN S.DATE_BEG < (case when D.date1 >= @PeriodBegin then D.date1 else @PeriodBegin end)
			THEN (case when D.date1 >= @PeriodBegin then D.date1 else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when D.date2 <= @PeriodEnd then D.date2 else @PeriodEnd end)
			THEN (case when D.date2 <= @PeriodEnd then D.date2 else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		@TMP_TYPE
	FROM 
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK
		inner join dbo.SDOC_DIS D on E.LINK = D.LINK_EMPL
	WHERE
		S.LINK_UP = @link
		AND	 
		E.DEP_LINK = @DEP_LINK
		and
		D.date1 <= @PeriodEnd
		and
		coalesce(D.date2,'20990101') >= @PeriodBegin
		and
		[TYPE] not in (select LINK from dbo.NETRUD where DEKRET = 1)

	/*Перерыв - Уход за ребенком до 1,5 и до 3 лет*/
	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
	SELECT 
		E.pers_link, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			THEN (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			THEN (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		(SELECT TOP 1 TYPE FROM #ADD_TYPE AT WHERE AT.VID = 'PERIOD2' AND AT.IS_DOP = LTRIM(RTRIM(ISNULL(V.IS_DOP,'ДЕТИ'))))
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK 
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID V ON V.LINK = IV.TYPE_LINK
		INNER JOIN (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7 AND ISNULL(VV.NOT_LGOT_EXPIR,0) = 0) VV ON VV.LINK = IV.TYPE_LINK
		LEFT JOIN DBO.ITEM_VACATION_BREAK IVB ON IVB.VAC_LINK = IV.LINK AND COALESCE(IVB.ACTIVE,0) = 1
	WHERE 
		S.LINK_UP = @link
		AND		
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin

	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
	SELECT 
		E.pers_link, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			THEN (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			THEN (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		(SELECT TOP 1 TYPE FROM #ADD_TYPE AT WHERE AT.VID = 'PERIOD2LS' AND AT.IS_DOP = LTRIM(RTRIM(ISNULL(V.IS_DOP,'ДЕТИ'))))
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK 
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID V ON V.LINK = IV.TYPE_LINK
		INNER JOIN (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7 AND ISNULL(VV.NOT_LGOT_EXPIR,0) = 1) VV ON VV.LINK = IV.TYPE_LINK
		LEFT JOIN DBO.ITEM_VACATION_BREAK IVB ON IVB.VAC_LINK = IV.LINK AND COALESCE(IVB.ACTIVE,0) = 1
	WHERE 
		S.LINK_UP = @link
		AND		
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin

	/*Перерыв - Отпуск без сохранения содержания АДМИНИСТР*/
	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
	Select E.pers_link, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			THEN (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			THEN (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		(SELECT TOP 1 TYPE FROM #ADD_TYPE AT WHERE AT.VID = 'PERIOD4' AND AT.IS_DOP = LTRIM(RTRIM(ISNULL(VV.IS_DOP,'АДМИНИСТР'))))
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK  
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID VV ON VV.LINK = IV.type_link AND VV.NO_SAL = 1
		left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and coalesce(ivb.active,0) = 1
	WHERE
		S.LINK_UP = @link
		AND		 	
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin
		
	--------------------------------------------------------------------------
	-- 2. Выстроим последовательность периодов с учетом их пересечений и приоритетов по полю type.
	--- Предполагается, что на первом шаге однотипные периоды уже нормализованы, т.е. следующие подряд и вложенные объединены
	CREATE TABLE #PERIODY3 (link int identity(1,1), link_face int, LINK_KATEG INT, date1 datetime, date2 datetime, [type] INT, orders int, i int, NUM_STAKE NUMERIC(5,2), TYPE_ADD INT)

	--Все промежутки заполняются типом -1  т.е. несуществующими днями
	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, [type])
	SELECT DISTINCT link_face, LINK_KATEG, @PeriodBegin, @PeriodEnd, [type] = -1  FROM #PERIODY

	CREATE TABLE #DAYS (ID INT IDENTITY(1,1), LINK_FACE INT, LINK_KATEG INT, [DATE] DATETIME, [TYPE] INT, NUM INT, NUM_STAKE NUMERIC(5,2), [TYPE_ADD] INT)

	INSERT INTO #DAYS (LINK_FACE, LINK_KATEG, [DATE], [TYPE], NUM, NUM_STAKE, [TYPE_ADD])
	SELECT P.LINK_FACE, P.LINK_KATEG, [DATE], [TYPE] = MAX([TYPE]), 0, 
		NUM_STAKE = MAX(ISNULL(NUM_STAKE,0)), 
		[TYPE_ADD] = MAX(CASE WHEN [TYPE] <= @MAX_TYPE THEN [TYPE] ELSE 0 END)
	FROM 
		#PERIODY P
		INNER JOIN dbo.days_ex(@PeriodBegin, @PeriodEnd) D ON 1=1
	WHERE
		D.[DATE] BETWEEN P.DATE1 AND P.DATE2
	GROUP BY
		P.LINK_FACE, P.LINK_KATEG, [date]
	ORDER BY	
		P.LINK_FACE, P.LINK_KATEG, [date]

	--Убрать льготы для периодов, в которых не сохраняются льготы
	UPDATE #DAYS SET [TYPE_ADD] = 0 
	WHERE 
		--Тип периода, в котором не сохраняются льготы
		EXISTS (SELECT * FROM #ADD_TYPE AT WHERE VID = 'TMP_TYPE' AND AT.[TYPE] = #DAYS.[TYPE])
		OR --ОТПУСК ПО УХОДУ ЗА РЕБЁНКОМ (ЕСЛИ ВКЛЮЧЕНА НАСТРОЙКА В ВИДЕ ОТПУСКА
		EXISTS (SELECT * FROM #ADD_TYPE AT WHERE AT.VID = 'PERIOD2LS' AND AT.[TYPE] = #DAYS.[TYPE])
		--OR --ДЕКРЕТ (БОЛЬНИЧНЫЙ 140 ДНЕЙ ПО БЕРЕМЕННОСТИ И РОДАМ
		--EXISTS (SELECT * FROM #ADD_TYPE AT WHERE AT.VID = 'PERIOD1' AND AT.[TYPE] = #DAYS.[TYPE])
		

	--Пронумеровать группы
	DECLARE 
		@ID INT, @ID1 INT, @ID2 INT, @LINK_FACE INT, @LINK_KATEG INT, @TYPE INT, @NUM INT,
		@LINK_FACE1 INT, @LINK_KATEG1 INT, @TYPE1 INT

	--Убрать временные периоды, которые заводились для корректировки льготных периодов
	SET @TMP_TYPE = (SELECT TOP 1 TYPE FROM #ADD_TYPE WHERE VID = 'TMP_TYPE')
	UPDATE #DAYS SET [type] = 0 WHERE [type] = @TMP_TYPE

	--	
	SELECT TOP 1 @ID1 = 0, @ID2 = 0, @NUM = 0, @LINK_FACE1 = LINK_FACE, @LINK_KATEG1 =LINK_KATEG, @TYPE1 = [TYPE]
	FROM #DAYS
	order by ID
	--
	DECLARE @Cur1 CURSOR
	SET @Cur1 = CURSOR FORWARD_ONLY
	FOR SELECT ID, LINK_FACE, LINK_KATEG, [TYPE] from #DAYS order by ID
	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @ID, @LINK_FACE, @LINK_KATEG, @TYPE
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN

			IF NOT (@LINK_FACE = @LINK_FACE1 AND @LINK_KATEG = @LINK_KATEG1 AND @TYPE = @TYPE1)
			BEGIN
				
				SELECT @NUM = @NUM + 1, @LINK_FACE1 = @LINK_FACE, @LINK_KATEG1 = @LINK_KATEG, @TYPE1 = @TYPE
				UPDATE #DAYS SET NUM = @NUM WHERE ID BETWEEN @ID1 AND @ID-1
				SELECT @ID1 = @ID 

			END

		END

		FETCH NEXT FROM @Cur1 INTO @ID, @LINK_FACE, @LINK_KATEG, @TYPE
	END

	CLOSE @Cur1
	DEALLOCATE @Cur1
	--
	UPDATE #DAYS SET NUM = @NUM+1 WHERE ID >= @ID1

	--

	INSERT INTO #PERIODY3 (link_face, LINK_KATEG, date1, date2, [type], orders, i, NUM_STAKE, TYPE_ADD)
	SELECT LINK_FACE, LINK_KATEG, DATE_BEG =  MIN([DATE]), DATE_END = MAX([DATE]), [TYPE], 0, 0, NUM_STAKE = MAX(ISNULL(NUM_STAKE,0)), TYPE_ADD
	FROM #DAYS	
	GROUP BY LINK_FACE, LINK_KATEG, NUM, [TYPE], TYPE_ADD
	ORDER BY LINK_FACE, LINK_KATEG, DATE_BEG, DATE_END

	--Удаляем временные промежутки
	DELETE FROM #PERIODY3 WHERE [TYPE] = -1

	/*пронумеруем периоды*/
	DECLARE @uslovie INT
	set @uslovie = 1
	while @uslovie > 0
	begin
		update #PERIODY3 set orders = @uslovie 
		from #PERIODY3 as tt
		where 	coalesce(orders,0) = 0
			and date1 = (select min(t.date1) from #PERIODY3 t where coalesce(orders,0) = 0 and t.link_face = tt.link_face AND T.LINK_KATEG = TT.LINK_KATEG)

		if @@rowcount > 0
			set @uslovie = @uslovie + 1
		else
			set @uslovie = 0
	end

	--СТАХ ПО ТРУДОВОМУ ДОГОВРУ
	insert into dbo.SZV4_STAZH (link_up, orders, date1, date2, ter_usl, ter_koef, osob_usl, osob_k1, osob_k2, osob_k3, is_osnov, is_dop, is_dop_m, is_dop_d, ud_osnov, ud_dop_m, ud_dop_d, ud_dop_k, osob_spo)
	Select S.link, P.orders, P.date1, P.date2, 
		ter_usl = ISNULL(spr1.CODE,spr1A.CODE),
		ter_koef = ISNULL(T.TERR_RK,TA.TERR_RK),
		osob_usl = ISNULL(spr2.CODE,spr2A.CODE),
		osob_k1 = ISNULL(spr6.CODE,spr6A.CODE),
		osob_k2 = ISNULL(spr7.CODE,spr7A.CODE),
		osob_k3 = NULL,
		is_osnov = NULL, 
		is_dop = LTRIM(RTRIM(ISNULL(T.IS_DOP,TA.IS_DOP))),
		is_dop_m = NULL, 
		is_dop_d = NULL, 
		ud_osnov = ISNULL(spr5.CODE,spr5A.CODE), 
		ud_dop_m = NULL, 
		ud_dop_d = NULL, 
		ud_dop_k = ISNULL(T.STAVKA_PED_MED,TA.STAVKA_PED_MED) * P.NUM_STAKE,
		osob_spo = ISNULL(spr9.CODE,spr9A.CODE)
	from
		#PERSON B 
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
		inner join #PERIODY3 P on S.link_pers = P.link_face AND S.LINK_KATEG = P.LINK_KATEG
		
		LEFT JOIN #ADD_TYPE T ON P.[TYPE] = T.[TYPE]
		LEFT JOIN dbo.szv4_spr spr1 on spr1.spr_code = 'TERR_USL' and spr1.LINK = T.TERR_USL_TRUD
		LEFT JOIN dbo.szv4_spr spr2 on spr2.spr_code = 'OSOB_USL_TRUDA' and spr2.LINK = T.OSOB_USL_TRUD
		--left join dbo.szv4_spr spr3 on spr3.spr_code = 'ISCHISL_STAZH_OSNOV' and spr3.code = T.is_osnov
		--left join dbo.szv4_spr spr4 on spr4.spr_code = 'ISCHISL_STAZH_DOP_SV' and spr4.code = T.is_dop
		left join dbo.szv4_spr spr5 on spr5.spr_code = 'DOSR_NAZN_PEN_OSNOV' and spr5.LINK = T.USL_DOSROCH_PENS
		left join dbo.szv4_spr spr6 on spr6.SPR_CODE LIKE 'SPISOK%' and spr6.LINK = T.COD_POS_SPISOK
		left join dbo.szv4_spr spr7 on spr7.SPR_CODE LIKE 'SPISOK%' and spr7.LINK = T.COD_POS_SPISOK2
		--left join dbo.szv4_spr spr8 on spr8.spr_code = 'LGOT_PROFES' and spr8.code = T.osob_k3
		left join dbo.szv4_spr spr9 on spr9.SPR_CODE LIKE 'SPO_USL_TRUDA' and spr9.LINK = T.[COD_SPO_USL_TRUD]

		LEFT JOIN #ADD_TYPE TA ON P.[TYPE_ADD] = TA.[TYPE] AND P.[TYPE_ADD] <> P.[TYPE]
		LEFT JOIN dbo.szv4_spr spr1A on spr1A.spr_code = 'TERR_USL' and spr1A.LINK = TA.TERR_USL_TRUD
		LEFT JOIN dbo.szv4_spr spr2A on spr2A.spr_code = 'OSOB_USL_TRUDA' and spr2A.LINK = TA.OSOB_USL_TRUD
		--left join dbo.szv4_spr spr3 on spr3.spr_code = 'ISCHISL_STAZH_OSNOV' and spr3.code = T.is_osnov
		--left join dbo.szv4_spr spr4 on spr4.spr_code = 'ISCHISL_STAZH_DOP_SV' and spr4.code = T.is_dop
		left join dbo.szv4_spr spr5A on spr5A.spr_code = 'DOSR_NAZN_PEN_OSNOV' and spr5A.LINK = TA.USL_DOSROCH_PENS
		left join dbo.szv4_spr spr6A on spr6A.SPR_CODE LIKE 'SPISOK%' and spr6A.LINK = TA.COD_POS_SPISOK
		left join dbo.szv4_spr spr7A on spr7A.SPR_CODE LIKE 'SPISOK%' and spr7A.LINK = TA.COD_POS_SPISOK2
		--left join dbo.szv4_spr spr8 on spr8.spr_code = 'LGOT_PROFES' and spr8.code = T.osob_k3	
		left join dbo.szv4_spr spr9A on spr9A.SPR_CODE LIKE 'SPO_USL_TRUDA' and spr9A.LINK = TA.[COD_SPO_USL_TRUD]
	where
		S.link_up = @link
		AND
		S.FORMA = 1
	order by
		S.link, P.orders

	--СТАХ ПО ГПХ
	CREATE TABLE #STAGE_DOG (
		LINK_PERS INT, 
		KATEG TINYINT,
		BERIOD_BEG DATETIME,
		BERIOD_END DATETIME
		)

	INSERT INTO #STAGE_DOG (LINK_PERS, KATEG, BERIOD_BEG, BERIOD_END)
	SELECT LINK_FACE, LINK_KATEG, MIN(date1), MAX(date2) 
	FROM #DGH A
	GROUP BY LINK_FACE, LINK_KATEG

	insert into dbo.SZV4_STAZH (link_up, orders, date1, date2)
	Select S.link, 1, P.BERIOD_BEG, P.BERIOD_END
	from
		#PERSON B 
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
		INNER JOIN #STAGE_DOG P on S.link_pers = P.LINK_PERS AND S.LINK_KATEG = P.KATEG
	where
		S.link_up = @link
		AND
		S.FORMA = 2
	order by
		S.link
*/		
END
--------------------------------------------------------------------------
exec dbo.SZV_k_NUMERATOR @link




GO


GRANT EXECUTE ON dbo.[SA_SZV_K_PACHKA_CALC_Buffer] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SZV_K_NUMERATOR]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SZV_K_NUMERATOR]

GO


CREATE   PROCEDURE [dbo].SZV_K_NUMERATOR (@link int)
AS

declare @DEP_LINK int
exec dbo.xd_whats_zb @DEP_LINK output

EXEC dbo.SZV_K_NUMERATOR2 @link	


GO


GRANT EXECUTE ON dbo.[SZV_K_NUMERATOR] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SZV_K_NUMERATOR2]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SZV_K_NUMERATOR2]

GO

CREATE   PROCEDURE [dbo].SZV_K_NUMERATOR2 (@link int)
AS

declare @DEP_LINK int
exec dbo.xd_whats_zb @DEP_LINK output

--DECLARE @Year INT, @PER TINYINT, @MONTH_END TINYINT, @MONTH_BEG TINYINT, @INSUR1 NUMERIC(20,2), @GAIN1 NUMERIC(20,2)
--SELECT @Year = YEAR_BEGIN, @PER = PER, @MONTH_END = MONTH_END, @INSUR1 = ISNULL(INSUR1,0),  @GAIN1 = ISNULL(GAIN1,0) FROM dbo.SZV_K_PACHKA WHERE LINK = @link

DECLARE /*@PeriodBegin datetime,*/ @PeriodEnd datetime

--SET @MONTH_BEG = (CASE @PER WHEN 1 THEN 1 WHEN 2 THEN 4 WHEN 3 THEN 7 WHEN 4 THEN 10 END)
--SET @MONTH_END = (CASE WHEN @MONTH_END < (@MONTH_BEG+3-1) THEN @MONTH_END ELSE (@MONTH_BEG+3-1) END)

SELECT /*@PeriodBegin = dbo.ConvertDMY2Date(1,@MONTH_BEG,@Year),*/ @PeriodEnd = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,12,'2001'))

--пачки формируются в зависимости от территориальных условий проживания на 31.12.2001 , указанных в сведениях  
CREATE TABLE #EMPT(LINK INT)
INSERT INTO #EMPT(LINK)
Select DISTINCT SV.link  from dbo.SZV_K_svedenia SV 
	where SV.link_up = @link 
		and coalesce(terr_usl,'') = ''

CREATE TABLE #MKS(LINK INT)
INSERT INTO #MKS(LINK)
Select DISTINCT SV.link  from dbo.SZV_K_svedenia SV 
	where SV.link_up = @link 
		and coalesce(terr_usl,'') = 'МКС' 
		
--and SV.link not in (select tbl.link from #TBL tbl)

--Пачки в зависимости от территориальных условий проживания на 31.12.2001
CREATE TABLE #MKSR (LINK INT)
INSERT INTO #MKSR(LINK)
Select DISTINCT SV.link  from dbo.SZV_K_svedenia SV 
	where SV.link_up = @link 
		and coalesce(terr_usl,'') = 'МКСР' 
CREATE TABLE #RKS (LINK INT)
INSERT INTO #RKS(LINK)
Select DISTINCT SV.link  from dbo.SZV_K_svedenia SV 
	where SV.link_up = @link 
		and coalesce(terr_usl,'') = 'РКС' 
CREATE TABLE #RKSM (LINK INT)
INSERT INTO #RKSM(LINK)
Select DISTINCT SV.link  from dbo.SZV_K_svedenia SV 
	where SV.link_up = @link 
		and coalesce(terr_usl,'') = 'РКСM' 
CREATE TABLE #CHZ31 (LINK INT)
INSERT INTO #CHZ31(LINK)
Select DISTINCT SV.link  from dbo.SZV_K_svedenia SV 
	where SV.link_up = @link 
		and coalesce(terr_usl,'') = 'ЧЗ31'
CREATE TABLE #CHZ33 (LINK INT)
INSERT INTO #CHZ33(LINK)
Select DISTINCT SV.link  from dbo.SZV_K_svedenia SV 
	where SV.link_up = @link 
		and coalesce(terr_usl,'') = 'ЧЗ33'
CREATE TABLE #CHZ34 (LINK INT)
INSERT INTO #CHZ34(LINK)
Select DISTINCT SV.link  from dbo.SZV_K_svedenia SV 
	where SV.link_up = @link 
		and coalesce(terr_usl,'') = 'ЧЗ34'
CREATE TABLE #CHZ35 (LINK INT)
INSERT INTO #CHZ35(LINK)
Select DISTINCT SV.link  from dbo.SZV_K_svedenia SV 
	where SV.link_up = @link 
		and coalesce(terr_usl,'') = 'ЧЗ35'
CREATE TABLE #CHZ36 (LINK INT)
INSERT INTO #CHZ36(LINK)
Select DISTINCT SV.link  from dbo.SZV_K_svedenia SV 
	where SV.link_up = @link 
		and coalesce(terr_usl,'') = 'ЧЗ36' 		
-----------------------------------------------------
--exec SZV_K_NUMERATOR2 2 
select * from SZV_K_SVEDENIA
/*Нумерация строк в пачке*/
UPDATE dbo.SZV_K_SVEDENIA SET ORDERS = 0 WHERE link_up = @link

DECLARE @MAXNUM int, @Forma tinyint
SET @MAXNUM = dbo.sa_get_option_by_code('SA_SZV_K_OPT1')

IF COALESCE(@MAXNUM,0) <=0
	SET @MAXNUM = 200

declare @nextOrd int, @pachNum int, @newForm tinyint, @oldForm tinyint
Set @pachNum = Coalesce((select numer from dbo.szv_K_pachka where link = @link),0) 
Set @pachNum = (case when @pachNum = 0 then 1 else @pachNum end)
Set @pachNum = COALESCE(@pachNum,0) -- + (CASE WHEN COALESCE(dbo.sa_get_option_by_code('SA_SZV_K_OPT3'),0) = 1 THEN 1 ELSE 0 END)


CREATE TABLE #ORDERS (ID INT, LINK INT, FORMA varchar(10), EMPT tinyint,  MKS tinyint, MKSR tinyint, RKS tinyint, RKSM tinyint, CHZ31 tinyint, CHZ33 tinyint, CHZ34 tinyint, CHZ35 tinyint, CHZ36 TINYINT, ORD INT )
INSERT INTO #ORDERS (LINK, FORMA,EMPT, MKS, MKSR, RKS, RKSM, CHZ31, CHZ33, CHZ34, CHZ35, CHZ36)
Select 
	S.link, terr_usl,
	EMPT  = (CASE WHEN ISNULL(e.LINK,0) = 0 THEN 0 ELSE 1 END),
	MKS  = (CASE WHEN ISNULL(m.LINK,0) = 0 THEN 0 ELSE 1 END), 
	MKSR = (CASE WHEN ISNULL(mr.LINK,0) = 0 THEN 0 ELSE 1 END), 
	RKS = (CASE WHEN ISNULL(r.LINK,0) = 0 THEN 0 ELSE 1 END), 
	RKSM = (CASE WHEN ISNULL(rm.LINK,0) = 0 THEN 0 ELSE 1 END), 
	CHZ31 = (CASE WHEN ISNULL(c1.LINK,0) = 0 THEN 0 ELSE 1 END), 
	CHZ33 = (CASE WHEN ISNULL(c3.LINK,0) = 0 THEN 0 ELSE 1 END), 
	CHZ34 = (CASE WHEN ISNULL(c4.LINK,0) = 0 THEN 0 ELSE 1 END), 
	CHZ35 = (CASE WHEN ISNULL(c5.LINK,0) = 0 THEN 0 ELSE 1 END), 
	CHZ36 = (CASE WHEN ISNULL(c6.LINK,0) = 0 THEN 0 ELSE 1 END)
from dbo.SZV_K_SVEDENIA S
	LEFT JOIN #EMPT   e ON e.LINK = S.LINK 
	LEFT JOIN #MKS   m ON m.LINK = S.LINK 
	LEFT JOIN #MKSR  mr ON mr.LINK = S.LINK 
	LEFT JOIN #RKS   r ON r.LINK = S.LINK 
	LEFT JOIN #RKSM  rm ON rm.LINK = S.LINK 
	LEFT JOIN #CHZ31 c1 ON c1.LINK = S.LINK 
	LEFT JOIN #CHZ33 c3 ON c3.LINK = S.LINK 
	LEFT JOIN #CHZ34 c4 ON c4.LINK = S.LINK 
	LEFT JOIN #CHZ35 c5 ON c5.LINK = S.LINK 
	LEFT JOIN #CHZ36 c6 ON c6.LINK = S.LINK
where link_up = @link
ORDER BY
	terr_usl, 
	(CASE WHEN ISNULL(e.LINK,0) = 0 THEN 0 ELSE 1 END),
	(CASE WHEN ISNULL(m.LINK,0) = 0 THEN 0 ELSE 1 END), 
	(CASE WHEN ISNULL(mr.LINK,0) = 0 THEN 0 ELSE 1 END), 
	(CASE WHEN ISNULL(r.LINK,0) = 0 THEN 0 ELSE 1 END), 
	(CASE WHEN ISNULL(rm.LINK,0) = 0 THEN 0 ELSE 1 END), 
	(CASE WHEN ISNULL(c1.LINK,0) = 0 THEN 0 ELSE 1 END), 
	(CASE WHEN ISNULL(c3.LINK,0) = 0 THEN 0 ELSE 1 END), 
	(CASE WHEN ISNULL(c4.LINK,0) = 0 THEN 0 ELSE 1 END), 
	(CASE WHEN ISNULL(c5.LINK,0) = 0 THEN 0 ELSE 1 END), 
	(CASE WHEN ISNULL(c6.LINK,0) = 0 THEN 0 ELSE 1 END),
	dbo.ku_GetPersFIO(S.link_pers)




--Пометим группы, которые должны быть в разных пачках
CREATE TABLE #ORDERS1 (ID1 INT IDENTITY(1,1), FORMA varchar(10),EMPT tinyint, MKS tinyint, MKSR tinyint, RKS tinyint, RKSM tinyint, CHZ31 tinyint, CHZ33 tinyint, CHZ34 tinyint, CHZ35 tinyint, CHZ36 tinyint)

INSERT INTO #ORDERS1 (FORMA,EMPT, MKS, MKSR, RKS, RKSM, CHZ31, CHZ33, CHZ34, CHZ35, CHZ36)
SELECT DISTINCT FORMA,EMPT, MKS, MKSR, RKS, RKSM, CHZ31, CHZ33, CHZ34, CHZ35, CHZ36
FROM #ORDERS
ORDER BY FORMA,EMPT, MKS, MKSR, RKS, RKSM, CHZ31, CHZ33, CHZ34, CHZ35, CHZ36

UPDATE O
SET ID = ID1
FROM #ORDERS O INNER JOIN #ORDERS1 O1 ON O.FORMA = O1.FORMA and o.EMPT = o1.EMPT AND O.MKS = O1.MKS AND O.MKSR= O1.MKSR 
AND O.RKS = O1.RKS AND O.RKSM= O1.RKSM  AND O.CHZ31 = O1.CHZ31 AND O.CHZ33= O1.CHZ33 AND O.CHZ34 = O1.CHZ34 AND O.CHZ35= O1.CHZ35 
AND O.CHZ36 = O1.CHZ36 


CREATE TABLE #ORDERS_N (ID INT, LINK INT, FORMA varchar(10), EMPT tinyint, MKS tinyint, MKSR tinyint, RKS tinyint, RKSM tinyint, CHZ31 tinyint, CHZ33 tinyint, CHZ34 tinyint, CHZ35 tinyint, CHZ36 TINYINT , ORD INT)
INSERT INTO #ORDERS_N (ID, LINK, FORMA,EMPT, MKS, MKSR, RKS, RKSM, CHZ31, CHZ33, CHZ34, CHZ35, CHZ36, ORD)
SELECT ID, LINK, FORMA,EMPT, MKS, MKSR, RKS, RKSM, CHZ31, CHZ33, CHZ34, CHZ35, CHZ36, ORD FROM #ORDERS ORDER BY ID

--Пронумеруем внутри будущих пачек
DECLARE @ORD INT, @ID INT
SELECT @ORD = 0, @ID = 0

UPDATE #ORDERS_N
SET
	@ORD = CASE WHEN @ID <> ID THEN 1 ELSE @ORD + 1 END,
	ORD = @ORD,
	@ID = ID

--Пронумеруем сами пачки
CREATE TABLE #ORDERS2 (ID1 INT IDENTITY(1,1), FORMA varchar(10),EMPT tinyint, MKS tinyint, MKSR tinyint, RKS tinyint, RKSM tinyint, CHZ31 tinyint, CHZ33 tinyint, CHZ34 tinyint, CHZ35 tinyint, CHZ36 TINYINT, PART INT )

INSERT INTO #ORDERS2 (FORMA,EMPT, MKS, MKSR, RKS, RKSM, CHZ31, CHZ33, CHZ34, CHZ35, CHZ36, PART)	
SELECT DISTINCT FORMA,EMPT, MKS, MKSR, RKS, RKSM, CHZ31, CHZ33, CHZ34, CHZ35, CHZ36, PART = CEILING(CAST(ord AS FLOAT) /@MAXNUM)
FROM #ORDERS_N
ORDER BY FORMA, MKS, MKSR, RKS, RKSM, CHZ31, CHZ33, CHZ34, CHZ35, CHZ36, CEILING(CAST(ord AS FLOAT) /@MAXNUM)


UPDATE O
SET ID = ID1
FROM #ORDERS_N O INNER JOIN #ORDERS2 O1 
	ON O.FORMA = O1.FORMA 
		--AND O.KATEG = O1.KATEG
		AND O.EMPT= O1.EMPT
		AND O.MKS = O1.MKS 
		AND O.MKSR = O1.MKSR 
		AND O.RKS = O1.RKS 
		AND O.RKSM = O1.RKSM 
		AND O.CHZ31 = O1.CHZ31 
		AND O.CHZ33 = O1.CHZ33 
		AND O.CHZ34 = O1.CHZ34 
		AND O.CHZ35 = O1.CHZ35 
		AND O.CHZ36 = O1.CHZ36
		AND CEILING(CAST(O.ord AS FLOAT) /@MAXNUM) = O1.PART

UPDATE S
Set 
	PACHKA = T.ID + @pachNum - 1,
	orders = (T.ord-1) % @MAXNUM + 1--,
from dbo.SZV_k_SVEDENIA S inner join #ORDERS_N T on S.link = T.link
WHERE S.link_up = @link




GO


GRANT EXECUTE ON dbo.[SZV_K_NUMERATOR2] TO PUBLIC

GO



GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BB_EXPORT_PAY_BANK]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BB_EXPORT_PAY_BANK]

GO


/*
© Кейсистемс (Keysystems), 2005
*/

CREATE           
PROCEDURE dbo.BB_EXPORT_PAY_BANK
	@cBuffId	varchar(30) = ''

AS

declare @tTemp table([text] varchar(8000), ord int identity(1,1))
insert into @tTemp([text])
select top 1 
'1CClientBankExchange
ВерсияФормата=1.01
Кодировка=Windows
Отправитель=' + rtrim(P.S_NAME) + ' 
Получатель=Клиент банка InterBank v.5.1 R-Style Software Lab
ДатаСоздания=' + convert(char(10),getdate(),104) + '
ВремяСоздания=' + convert(char(10),getdate(),108) + '
ДатаНачала=' + convert(char(10), min(P.[DATE]),104) + '
ДатаКонца=' + convert(char(10),max(P.[DATE]),104) + '
РасчСчет=' + ltrim(rtrim(isnull(S_SCH_K, S_ACC_NUM))) + '
Документ=Платежное поручение'
from dbo.DOCUMENTS_PAY P
inner join dbo.BufferGetTableByID(@cBuffId) B on B.LINK = P.LINK
group by P.S_NAME, ltrim(rtrim(isnull(S_SCH_K, S_ACC_NUM)))

insert into @tTemp([text])
select
'СекцияДокумент=Платежное поручение
Номер=' + ltrim(rtrim(NUMBER)) + '
Дата=' + convert(char(10),getdate(),104) + '
Сумма=' + rtrim(convert(char(20), SUMMA)) + '
ПлательщикСчет=' + ltrim(rtrim(isnull(S_ACC_NUM, ''))) + '
ПлательщикИНН=' + ltrim(rtrim(isnull(S_INN, ''))) + '
ПлательщикКПП=' + ltrim(rtrim(isnull(S_KPP, ''))) + '
Плательщик=ИНН ' + ltrim(rtrim(isnull(S_INN, ''))) + '\' + ltrim(rtrim(isnull(S_KPP, '')))+ ' ' + ltrim(rtrim(isnull(S_FNAME, ''))) + '
Плательщик1=' + ltrim(rtrim(isnull(S_FNAME, ''))) + '
ПлательщикРасчСчет=' + ltrim(rtrim(isnull(S_SCH_K, S_ACC_NUM))) + '
ПлательщикБанк1=' + ltrim(rtrim(isnull(S_BANK, ''))) + '
ПлательщикБанк2=' + ltrim(rtrim(isnull(S_BANK_CITY, ''))) + '
ПлательщикБИК=' + ltrim(rtrim(isnull(S_BIK, ''))) + '
ПлательщикКорсчет=' + ltrim(rtrim(isnull(S_SCH_B, ''))) + '
ПолучательСчет=' + ltrim(rtrim(isnull(D_ACC_NUM, ''))) + '
ПолучательИНН=' + ltrim(rtrim(isnull(D_INN, ''))) + '
ПолучательКПП=' + ltrim(rtrim(isnull(D_KPP, ''))) + '
Получатель=ИНН ' + ltrim(rtrim(isnull(D_INN, ''))) + '\' + + ltrim(rtrim(isnull(D_KPP, '')))+ ' ' + ltrim(rtrim(isnull(D_FNAME, ''))) + '
Получатель1=' + ltrim(rtrim(isnull(D_FNAME, ''))) + '
ПолучательРасчСчет=' + ltrim(rtrim(isnull(D_SCH_K, D_ACC_NUM))) + '
ПолучательБанк1=' + ltrim(rtrim(isnull(D_BANK, ''))) + '
ПолучательБанк2=' + ltrim(rtrim(isnull(D_BANK_CITY, ''))) + '
ПолучательБИК=' + ltrim(rtrim(isnull(D_BIK, ''))) + '
ПолучательКорсчет=' + ltrim(rtrim(isnull(D_SCH_B, ''))) + '
ВидПлатежа=' + ltrim(rtrim(isnull(KIND, ''))) + '
ВидОплаты=' + ltrim(rtrim(isnull(PAYKIND, ''))) + '
Код='+ LTRIM(RTRIM(ISNULL(pA.UIN_CODE,'')))+'
Очередность=' + ltrim(rtrim(isnull([ORDER], ''))) + case when PA.DOH_CODE is not null and PA.[STATUS] is not null then '
СтатусСоставителя=' + ltrim(rtrim(PA.[STATUS])) else '' end + case when PA.DOH_CODE is not null and PA.[STATUS] is not null then '
ПлательщикКПП=' + isnull(ltrim(rtrim(S_KPP)), '0') else '' end + case when PA.DOH_CODE is not null and PA.[STATUS] is not null then '
ПолучательКПП=' + isnull(ltrim(rtrim(D_KPP)), '0') else '' end + case when PA.DOH_CODE is not null and PA.[STATUS] is not null then '
ПоказательКБК=' + ltrim(rtrim(replace(PA.DOH_CODE,'.',''))) + ltrim(rtrim(PA.SGU_CODE)) else '' end + case when PA.DOH_CODE is not null and PA.[STATUS] is not null then '
ОКАТО=' + isnull(ltrim(rtrim(PA.OKATO)),'0') else '' end + case when PA.DOH_CODE is not null and PA.[STATUS] is not null then '
ПоказательОснования=' + isnull(ltrim(rtrim(PA.P_REASON)), '0') else '' end + case when PA.DOH_CODE is not null and PA.[STATUS] is not null then '
ПоказательПериода=' + isnull(ltrim(rtrim(PA.PERIOD)), '0') else '' end + case when PA.DOH_CODE is not null and PA.[STATUS] is not null then '
ПоказательНомера=' +isnull( ltrim(rtrim(PA.TREBNUM)), '0') else '' end + case when PA.DOH_CODE is not null and PA.[STATUS] is not null then '
ПоказательДаты=' + isnull(ltrim(rtrim(convert(char(10),PA.TREBDATE,104))), '0') else '' end + case when PA.DOH_CODE is not null and PA.[STATUS] is not null then '
ПоказательТипа=' + isnull(ltrim(rtrim(PA.P_TYPE)), '0') else '' end + dbo.BB_EXPORT_PAY_BANK_NASN(TARGETTEXT) + ' 
КонецДокумента'
from dbo.DOCUMENTS_PAY P
inner join dbo.BufferGetTableByID(@cBuffId) B on B.LINK = P.LINK
left join dbo.DOCUMENTS_PAY_ADD PA on P.LINK =PA.LINK

insert into @tTemp([text]) values('КонецФайла')

select [text] from @tTemp order by ord




GO


GRANT EXECUTE ON dbo.[BB_EXPORT_PAY_BANK] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SZV_K_SVEDENIA_DELETE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZV_K_SVEDENIA_DELETE]

GO

CREATE PROCEDURE dbo.SA_SZV_K_SVEDENIA_DELETE
	@varKSintLINK	int
AS
DECLARE @varKStrancount	int,
		@varKSObjectLink	int,
		@varKSEventText	varchar(254),
		@LinkPach int

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN


	Set @LinkPach = (select top 1 link_up from dbo. SZV_K_SVEDENIA where LINK = @varKSintLINK)

	SELECT @varKSEventText = 'Сотрудник в пачке: ' + ' ' + FIO + ' ' FROM dbo.SA_SZV_K_SVEDENIA 
			WITH (UPDLOCK) WHERE LINK1 = @varKSintLINK
	IF @@RowCount = 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 2
	END
	DELETE FROM dbo.SZV_K_SVEDENIA WHERE LINK = @varKSintLINK

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END

	exec dbo.SZV_K_NUMERATOR @LinkPach
	
	UPDATE dbo.SZV_K_PACHKA SET PROVERKA = 0 WHERE LINK = @LinkPach

IF @@TRANCOUNT > @varKStrancount
	BEGIN
		SELECT @varKSObjectLink = LINK FROM S_OBJECTS WHERE CODE = 'SA_SZV_K_SVEDENIA'
		EXECUTE WF_GENERATEEVENT 'Удаление из справочника', @varKSEventText, @varKSObjectLink, 'SA_SZV_K_SVEDENIA', @varKSintLINK

		COMMIT TRAN
	END
RETURN 0




GO


GRANT EXECUTE ON dbo.[SA_SZV_K_SVEDENIA_DELETE] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_NZP_PREPARE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_NZP_PREPARE]

GO

CREATE PROCEDURE DBO.SA_NZP_PREPARE
	@OUT_VAL 	VARCHAR(20) OUTPUT,
	@BDATE		DATETIME,
	@ENDDATE	DATETIME,
	@DEP_LINK	INT,
	@VARILSF	INT
AS BEGIN
	DECLARE @PEOPLE_COUNT VARCHAR(100)
	EXEC DBO.X_GET_TABLE_NAME @PEOPLE_COUNT OUTPUT
	EXEC DBO.I_REPORT_FORMULA_ERASE_TABLES 0

DECLARE @FILTER_SUBDIV_NAME VARCHAR(254), @FILTER_SUBDIV_LINK INT
DECLARE @SUBDIV TABLE (LINK INT)

SET @FILTER_SUBDIV_NAME = (SELECT DBO.RN_GET_ATR_VALUE(@VARILSF, 'REPORTS_FILTER_SUBDIV'))


IF @FILTER_SUBDIV_NAME IS NOT NULL
	SET @FILTER_SUBDIV_LINK = 
		( SELECT TOP 1 LINK FROM DBO.REPORT_KBK 
		WHERE ('№' + CONVERT(VARCHAR(3),PROPERTY) + ' - ' + NAME) = @FILTER_SUBDIV_NAME
			AND CODE_FORM='FILTER_NABOR' AND CODE='REPORTS_FILTER_SUBDIV')


DECLARE @BUFFER_SUBDIV VARCHAR(20)

IF @FILTER_SUBDIV_LINK IS NOT NULL 
BEGIN

	EXEC DBO.GETRANDSTR 20, @BUFFER_SUBDIV OUT

	INSERT INTO @SUBDIV (LINK) 
	SELECT LINK FROM DBO.RN_VIEW_FILTER WHERE LINK_SELF = @FILTER_SUBDIV_LINK

END

DECLARE @ATR_INCR_ITOG TINYINT
SET @ATR_INCR_ITOG = (case when (SELECT DBO.RN_GET_ATR_VALUE(@VARILSF, 'REPORTS_ATR_INCR_ITOG')) = 'НЕТ' THEN 2 ELSE 1 END)



/**********************************************************************************************************************/
/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/
DECLARE @D1	DATETIME,
	@D2	DATETIME,
	@DBYEAR DATETIME

/* ДАЖЕ ЕСЛИ КВАРТАЛЬНАЯ ФОРМА, МЕСЯЧНЫЕ ДАНЫЕ БЕРУТСЯ ЗА ПОСЛЕДНИЙ МЕС. КВАРТАЛА */
SET @D1 = DBO.DATEBEGINOFMONTH (@ENDDATE) 
SET @D2 = DATEADD(MONTH,1,@D1)-1
SET @DBYEAR = DBO.DATEBEGINOFYEAR(@BDATE)

DECLARE @SALARY_OPTIONS_OPT8_1 INT 
SET @SALARY_OPTIONS_OPT8_1 =  dbo.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPT8_1')

DECLARE @NAME VARCHAR(100)

INSERT INTO DBO.BUFFER (ID, LINK)
SELECT @BUFFER_SUBDIV, LINK FROM @SUBDIV WHERE @BUFFER_SUBDIV IS NOT NULL

DECLARE @CNT INT
SET @CNT = CONVERT(NUMERIC(18,1), DBO.SA_SCH_EMPLS(@D2, @DEP_LINK, 0, 0, 0, @BUFFER_SUBDIV))

DECLARE @CODE_FORM varchar(10)
SET @CODE_FORM  = (select top 1 Ltrim(code) from RN_REPORT_SAVED_FORMS_ARH where link_SAVED_form = @VARILSF)

/*** НАЧАЛЬНЫЕ УСТАНОВКИ ***/
/* ТАБЛИЦА РЕЗУЛЬТАТОВ РАСЧЕТА (СТОЛБЕЦ/ЗНАЧЕНИЕ) */
CREATE  TABLE #NZP_PART1(CODE_STR VARCHAR(10) , COL	INT, VAL NUMERIC(18,2), VAL_STR VARCHAR(20))

/*********************************************************************************************/
--- Таблица категорий для формы
CREATE TABLE #CAT_CODES (link int, code varchar (10), name_cat varchar (256) )
declare @STR varchar(8000),
		@SPHERE tinyint 
	set @STR  = ' insert #CAT_CODES
					select link , code, name_cat
					from PERS_CATEGORY_BY_SPHERE 
				 where '

	set @STR  =  @STR  + CASE when @CODE_FORM = '0606045'  then ' ZDRAV = 1' 
						  when @CODE_FORM = '0606046'  then ' KULT = 1' 
						  when @CODE_FORM = '0606047'  then ' SCIENCE = 1' 
						  when @CODE_FORM = '0606048'  then ' EDUC = 1'
						  when @CODE_FORM = '0606049'  then ' SOC = 1' end
	exec(@str)

	--- Определим сферу деятельности
	SET @SPHERE = CASE WHEN @CODE_FORM = '0606045' then  (select link from STO_SPHERES where NAME = 'Медицина')
					   WHEN @CODE_FORM = '0606046' then  (select link from STO_SPHERES where NAME = 'Культура')
					   WHEN @CODE_FORM = '0606047' then  (select link from STO_SPHERES where NAME = 'Наука')
					   WHEN @CODE_FORM = '0606048' then  (select link from STO_SPHERES where NAME = 'Образование')
					   WHEN @CODE_FORM = '0606049' then  (select link from STO_SPHERES where NAME = 'Социальная сфера') end 

--- Обновим одинаковые коды в зависимости от наименования категории
update #CAT_CODES
	set code = '3011'
	where code = '301' and name_cat = 'Научные работники учреждений ВПО'
update #CAT_CODES
	set code = '3012'
	where code = '301' and name_cat = 'Научные работники учреждений дополнительного профессионального образования'	
update #CAT_CODES
	set code = '3013'
	where code = '301' and name_cat = 'Научные работники'	
update #CAT_CODES
	set code = '3014'
	where code = '301' and name_cat = 'научные работники (исследователи)'	
update #CAT_CODES
	set code = '3111'
	where code = '311' and name_cat = 'Научные сотрудники (ВПО)'	
update #CAT_CODES
	set code = '3112'
	where code = '311' and name_cat = 'Научные сотрудники (ДПО)'	
update #CAT_CODES
	set code = '3113'
	where code = '311' and name_cat = 'Научные сотрудники '	


-- КОД КАТЕГОРИИ '100' - ВСЕГО  
/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */
--- Списочность считаем с начала года
/*
declare  @OUT_VAL varchar (20)
set @OUT_VAL = ''
exec DBO.SA_NZP_PREPARE @OUT_VAL OUTPUT, '20140101', '20140331',74592,2888
*/


IF @ATR_INCR_ITOG =2 
begin
	IF  @CODE_FORM = '0606048'
		-- Если отчет по Образованию , то считаем за средне списочный состав по нагрузкам
		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_N(@D1, @D2, @DEP_LINK, 0, 1, 0, @BUFFER_SUBDIV))
	ELSE 
		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@D1, @D2, @DEP_LINK, 0, 1, 0, @BUFFER_SUBDIV)) 
end		
ELSE	
BEGIN
	IF  @CODE_FORM = '0606048'
		-- Если отчет по Образованию , то считаем за средне списочный состав по нагрузкам
		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_N(@DBYEAR, @D2, @DEP_LINK, 0, 1, 0, @BUFFER_SUBDIV))
	ELSE 
		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@D1, @D2, @DEP_LINK, 0, 1, 0, @BUFFER_SUBDIV))
	

END 
/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */
IF @ATR_INCR_ITOG =2 
BEGIN
	IF  @CODE_FORM = '0606048'
		-- Если отчет по Образованию , то считаем за средне списочный состав по нагрузкам
		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 5, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_N(@D1, @D2, @DEP_LINK, 0, 3, 0, @BUFFER_SUBDIV))
	else
		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 5, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@D1, @D2, @DEP_LINK, 0, 3, 0, @BUFFER_SUBDIV))
	
end
ELSE 
BEGIN
	IF  @CODE_FORM = '0606048'
		-- Если отчет по Образованию , то считаем за средне списочный состав по нагрузкам
		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 5, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_N(@DBYEAR, @D2, @DEP_LINK, 0, 3, 0, @BUFFER_SUBDIV))
	else 
		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 5, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@DBYEAR, @D2, @DEP_LINK, 0, 3, 0, @BUFFER_SUBDIV))

end

CREATE TABLE #ssch_empls_nzp_ALL(SSCH NUMERIC(18,6), CAT_NZP_LINK INT,CODE VARCHAR(4),SPHERE_LINK int,[STATUS] TINYINT,NAME_CAT VARCHAR(254),STAFF_HEAD int) 
IF @ATR_INCR_ITOG =2
BEGIN 
	IF  @CODE_FORM = '0606048' 
		INSERT INTO #ssch_empls_nzp_ALL(SSCH, CAT_NZP_LINK,CODE,SPHERE_LINK,[STATUS],NAME_CAT,STAFF_HEAD) 
		SELECT SSCH, CAT_NZP_LINK,CODE,SPHERE_LINK,[STATUS],NAME_CAT,STAFF_HEAD
		FROM sa_ssch_empls_nzp_N_ALL(@DBYEAR, @D2, @DEP_LINK, @BUFFER_SUBDIV)
	ELSE 	
		INSERT INTO #ssch_empls_nzp_ALL(SSCH, CAT_NZP_LINK,CODE,SPHERE_LINK,[STATUS],NAME_CAT,STAFF_HEAD) 
		SELECT SSCH, CAT_NZP_LINK,CODE,SPHERE_LINK,[STATUS],NAME_CAT,STAFF_HEAD
		FROM sa_ssch_empls_nzp_ALL(@DBYEAR, @D2, @DEP_LINK, @BUFFER_SUBDIV)
END 
ELSE
BEGIN 	
	IF  @CODE_FORM = '0606048' 
		INSERT INTO #ssch_empls_nzp_ALL(SSCH, CAT_NZP_LINK,CODE,SPHERE_LINK,[STATUS],NAME_CAT,STAFF_HEAD) 
		SELECT SSCH, CAT_NZP_LINK,CODE,SPHERE_LINK,[STATUS],NAME_CAT,STAFF_HEAD
		FROM sa_ssch_empls_nzp_N_ALL(@D1, @D2, @DEP_LINK, @BUFFER_SUBDIV)
	ELSE
		INSERT INTO #ssch_empls_nzp_ALL(SSCH, CAT_NZP_LINK,CODE,SPHERE_LINK,[STATUS],NAME_CAT,STAFF_HEAD) 
		SELECT SSCH, CAT_NZP_LINK,CODE,SPHERE_LINK,[STATUS],NAME_CAT,STAFF_HEAD
		FROM sa_ssch_empls_nzp_ALL(@D1, @D2, @DEP_LINK, @BUFFER_SUBDIV)
	 	
END 	

/* Разбивка по категориям */
DECLARE @Cur1 CURSOR, @LINK_CAT INT , @CODE_CAT varchar(10), @NAME_CAT varchar(254)
SET @Cur1 = CURSOR FORWARD_ONLY

FOR SELECT LINK, CODE, NAME_CAT FROM #CAT_CODES order by link

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @LINK_CAT, @CODE_CAT, @NAME_CAT
WHILE (@@fetch_status <> -1)
BEGIN

	IF (@@fetch_status <> -2)
	BEGIN
		
		SET @CODE_CAT = LTRIM(@CODE_CAT)
		SET @NAME_CAT = LTRIM(@NAME_CAT)
		
		IF @CODE_CAT like ('%301%') 
		BEGIN
			/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */
			/*IF @CNT > 15 
				INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 1, 0,@SPHERE, @BUFFER_SUBDIV,'301',@NAME_CAT))
			ELSE*/
				INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4,  ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 1 AND SPHERE_LINK = @SPHERE AND CODE = '301' and NAME_CAT = @NAME_CAT),0)
			/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */
			/*IF @CNT > 15 
				INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 5, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 3, 0,@SPHERE, @BUFFER_SUBDIV,'301',@NAME_CAT))
			ELSE*/
				INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 5,  ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 3 AND SPHERE_LINK = @SPHERE AND CODE = '301' and NAME_CAT = @NAME_CAT ),0)
		END
		ELSE BEGIN
			IF @CODE_CAT like ('%311%') 
			BEGIN
				/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */
				/*IF @CNT > 15 
					INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 1, 0,@SPHERE, @BUFFER_SUBDIV,'311',@NAME_CAT))
				ELSE*/
					INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4, ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 1 AND SPHERE_LINK = @SPHERE AND CODE = '311' and NAME_CAT = @NAME_CAT ),0)
				/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */
				/*IF @CNT > 15 
					INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 5, CONVERT(NUMERIC(18,1),DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 3, 0,@SPHERE, @BUFFER_SUBDIV,'311',@NAME_CAT))
				ELSE*/
					INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 5, ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 3 AND SPHERE_LINK = @SPHERE AND CODE = '311' and NAME_CAT = @NAME_CAT ),0)
			END
			ELSE BEGIN
				IF @CODE_CAT like ('103%') 
				BEGIN
					
					/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */
					/*IF @CNT > 15 
						INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 1, 0,@SPHERE, @BUFFER_SUBDIV,@CODE_CAT,null))
					ELSE*/
						INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4, ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 1 AND SPHERE_LINK = @SPHERE and CODE = @CODE_CAT),0)
					/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */
					/*IF @CNT > 15 
						INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 5, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 3, 0,@SPHERE, @BUFFER_SUBDIV,@CODE_CAT,null))
					ELSE*/
						INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 5, ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 3 AND SPHERE_LINK = @SPHERE and CODE = @CODE_CAT),0)
		
					/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */ -- добавляем необозначенных работников к прочему персоналу
					/*IF @CNT > 15 
						UPDATE  #NZP_PART1 
							set VAL = VAL + CONVERT(NUMERIC(18), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 1, 0,NULL, @BUFFER_SUBDIV,null,null))
						where CODE_STR = '103' and COL = 4
					ELSE */
						UPDATE  #NZP_PART1 
							set VAL = isnull(VAL,0) +	ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 1 AND staff_head is not null and isnull(cat_nzp_link,0) = 0),0)
						where CODE_STR = '103' and COL = 4
					/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */ -- добавляем необозначенных работников к прочему персоналу
					/*IF @CNT > 15 
						UPDATE  #NZP_PART1 
							set VAL = VAL + CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 3, 0,NULL, @BUFFER_SUBDIV,null,null))
						where CODE_STR = '103' and COL = 5
					ELSE */
						UPDATE  #NZP_PART1 
							set VAL = ISNULL(VAL,0) + ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 3 AND staff_head is not null and isnull(cat_nzp_link,0) = 0),0)
						where CODE_STR = '103' and COL = 5	
				END
				ELSE BEGIN
					/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */
					/*IF @CNT > 15 
						INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 1, 0,@SPHERE, @BUFFER_SUBDIV,@CODE_CAT,null))
					ELSE*/
						INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4, ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 1 AND SPHERE_LINK = @SPHERE AND CODE = @CODE_CAT ),0) 
					/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */
					/*IF @CNT > 15 
						INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 5, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 3, 0,@SPHERE, @BUFFER_SUBDIV,@CODE_CAT,null))
					ELSE*/
						INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 5, ISNULL((SELECT CONVERT(NUMERIC(18,1),sum(ssch)) FROM #ssch_empls_nzp_ALL WHERE [STATUS] = 3 AND SPHERE_LINK = @SPHERE AND CODE = @CODE_CAT ),0) 
				END
			END 
		END
	END

	FETCH NEXT FROM @Cur1 INTO @LINK_CAT, @CODE_CAT,@NAME_CAT
END

CLOSE @Cur1
DEALLOCATE @Cur1


if @SALARY_OPTIONS_OPT8_1 = 1 
begin 
	update  p 
		set val = ceiling(val)  
	from #NZP_PART1 p where p.col = 4
end 

if @SALARY_OPTIONS_OPT8_1 = 2 
begin 
	update  p 
		set val = ceiling(val)  
	from #NZP_PART1 p where p.col = 4
	update  p 
		set val = ceiling(val)
	from #NZP_PART1 p where p.col = 5
end 


DROP TABLE #ssch_empls_nzp_ALL



/*Для каждой формы просуммируем количество работников ИЗ которых выделяются сотрудники в другие строки*/
IF @CODE_FORM = '0606045'
BEGIN
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '282' and COL = 4)	
	where CODE_STR = '281' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '282' and COL = 5)	
	where CODE_STR = '281' and COL = 5	
	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = 4)	
	where CODE_STR = '3013' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = 5)	
	where CODE_STR = '3013' and COL = 5	
END


IF @CODE_FORM = '0606046'  
BEGIN

	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = 4)			
	where CODE_STR = '3013' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = 5)	
	where CODE_STR = '3013' and COL = 5	

	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '401'  and COL = 4) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '291'  and COL = 4)	+ (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '3013'  and COL = 4)			
	where CODE_STR = '621' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '401'  and COL = 5) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '291'  and COL = 5)	+ (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '3013' and COL = 5)	
	where CODE_STR = '621' and COL = 5	

END

IF @CODE_FORM = '0606047' 
BEGIN
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('312','313') and COL = 4)			
	where CODE_STR = '3113' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('312','313') and COL = 5)	
	where CODE_STR = '3113' and COL = 5	


	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('3113','102','101','302') and COL = 4)			
	where CODE_STR = '3014' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('3113','102','101','302') and COL = 5)	
	where CODE_STR = '3014' and COL = 5	
END 

IF @CODE_FORM = '0606048'  
BEGIN
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '212' and COL = 4)			
	where CODE_STR = '211' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '212' and COL = 5)	
	where CODE_STR = '211' and COL = 5	


	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('232','233') and COL = 4)			
	where CODE_STR = '231' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('232','233') and COL = 5)	
	where CODE_STR = '231' and COL = 5	

	UPDATE  #NZP_PART1 
	set VAL = ISNULL(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('242','243') and COL = 4)			
	where CODE_STR = '241' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = ISNULL(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('242','243') and COL = 5)	
	where CODE_STR = '241' and COL = 5		

	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('252','253') and COL = 4)			
	where CODE_STR = '251' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT SUM(VAL) FROM #NZP_PART1 WHERE CODE_STR IN ('252','253') and COL = 5)	
	where CODE_STR = '251' and COL = 5		

	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR ='3111' and COL = 4)			
	where CODE_STR = '3011' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR ='3111' and COL = 5)	
	where CODE_STR = '3011' and COL = 5		

	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR ='3112' and COL = 4)			
	where CODE_STR = '3012' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR ='3112' and COL = 5)	
	where CODE_STR = '3012' and COL = 5		
END

IF @CODE_FORM = '0606049'
BEGIN
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '282' and COL = 4)	
	where CODE_STR = '281' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '282' and COL = 5)	
	where CODE_STR = '281' and COL = 5	
	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = 4)	
	where CODE_STR = '3013' and COL = 4	
	UPDATE  #NZP_PART1 
	set VAL = isnull(VAL,0) + (SELECT VAL FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = 5)	
	where CODE_STR = '3013' and COL = 5	
END


/*********************************************************************************************/

/*INSERT INTO #NZP_PART1 (COL, VAL_STR)
SELECT TOP 1 1 AS COL, OKVED FROM dbo.DEPARTMENTS WHERE LINK = @DEP_LINK
*/

DELETE FROM DBO.BUFFER WHERE ID = @BUFFER_SUBDIV AND @BUFFER_SUBDIV IS NOT NULL	

CREATE TABLE #EMPL (LINK INT, PERS_LINK INT, DEP_LINK INT, [STATUS] TINYINT, CAT_NZP_LINK int , CAT_NZP_CODE varchar(3), PERIOD_BEG DATETIME, PERIOD_END DATETIME)
INSERT INTO #EMPL
SELECT 
	i.EMPL_LINK, i.PERS_LINK, i.DEP_LINK, i.[STATUS], st.CAT_NZP_LINK, pc.CODE ,i.PERIOD_BEG, i.PERIOD_END 
FROM 
	DBO.SA_EMPLS_INFO_PERIOD(@D1, @D2, DEFAULT, @DEP_LINK) i
	inner join sd_empl se on se.link = i.EMPL_LINK
	left join staff st on st.link_up = se.staff_head and  st.link = se.staff_link and (st.SPHERE_LINK = @sphere or  st.SPHERE_LINK is null)
	left join PERS_CATEGORY_BY_SPHERE pc on pc.link = st.cat_nzp_link 	
WHERE 
	(
	@BUFFER_SUBDIV IS NULL 
		OR 
	@BUFFER_SUBDIV IS NOT NULL AND i.SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
	)
	
ORDER BY 
	i.DEP_LINK, i.EMPL_LINK

CREATE TABLE #EMPL1 (LINK INT, PERS_LINK INT, DEP_LINK INT, [STATUS] TINYINT, CAT_NZP_LINK int , CAT_NZP_CODE varchar(3), PERIOD_BEG DATETIME, PERIOD_END DATETIME)
INSERT INTO #EMPL1
SELECT 
	i.EMPL_LINK, i.PERS_LINK, i.DEP_LINK, i.[STATUS], st.CAT_NZP_LINK, pc.CODE , i.PERIOD_BEG, i.PERIOD_END 
FROM 
	DBO.SA_EMPLS_INFO_PERIOD(@DBYEAR, @D2, DEFAULT, @DEP_LINK) i
	inner join sd_empl se on se.link = i.EMPL_LINK
	left join staff st on st.link_up = se.staff_head and  st.link = se.staff_link and (st.SPHERE_LINK = @sphere or  st.SPHERE_LINK is null)
	left join PERS_CATEGORY_BY_SPHERE pc on pc.link = st.cat_nzp_link 	
WHERE 
	(
	@BUFFER_SUBDIV IS NULL 
		OR 
	@BUFFER_SUBDIV IS NOT NULL AND i.SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
	)
ORDER BY 
	i.DEP_LINK, i.EMPL_LINK



--ПОДКОРРЕКТИРУЕМ КОНЕЧНУЮ ДАТУ ДЛЯ ТЕХ, КТО ПЕРЕВОДИЛСЯ, ДЛЯ ТОГО ЧТОБЫ ОПРЕДЕЛИТЬ СУММЫ НАЧИСЛЕНИЙ, НАЧИСЛЕННЫХ ПОСЛЕ ДАТЫ ИХ УВОЛЬНЕНИЯ
UPDATE E
SET E.PERIOD_END = @D2
FROM 
	#EMPL E
	INNER JOIN (SELECT LINK, MAX_PERIOD_END = MAX(PERIOD_END) FROM  #EMPL E1 GROUP BY LINK HAVING COUNT(*) > 1) A 
		ON E.LINK = A.LINK AND E.PERIOD_END = A.MAX_PERIOD_END
WHERE
	A.MAX_PERIOD_END < @D2

--ПОДКОРРЕКТИРУЕМ КОНЕЧНУЮ ДАТУ ДЛЯ ТЕХ, КТО ПЕРЕВОДИЛСЯ, ДЛЯ ТОГО ЧТОБЫ ОПРЕДЕЛИТЬ СУММЫ НАЧИСЛЕНИЙ, НАЧИСЛЕННЫХ ПОСЛЕ ДАТЫ ИХ УВОЛЬНЕНИЯ

UPDATE E
SET E.PERIOD_END = @D2
FROM 
	#EMPL1 E
	INNER JOIN (SELECT LINK, MAX_PERIOD_END = MAX(PERIOD_END) FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1) A 
		ON E.LINK = A.LINK AND E.PERIOD_END < A.MAX_PERIOD_END
WHERE
	A.MAX_PERIOD_END <= @D2	


/* ДОГОВОРНИКИ */
DECLARE @M NUMERIC(18,2) 

IF @ATR_INCR_ITOG =2 
	SELECT --За месяц
		@M=SUM(CASE 
			WHEN DGH.DATE1<=@D1 AND COALESCE(DGH.DATE2,@D2)>=@D2 THEN DATEDIFF(DAY,@D1,@D2)		-- РАБОТАЛ ВЕСЬ ПЕРИОД
			WHEN DGH.DATE1<=@D1 AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE2>@D1 THEN DATEDIFF(DAY,@D1,DGH.DATE2)+1	-- УВОЛЕН В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@D1  AND COALESCE(DGH.DATE2,@D2)>=@D2 AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,@D2) 		-- ПРИНЯТ В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@D1  AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,DGH.DATE2)+1	-- ПРИНЯТ И УВОЛЕН В РАБОЧИЙ ПЕРИОД
			 ELSE 0
		END)
	FROM 
		dbo.REESTR_DGH DGH
	WHERE
			DEP_LINK = @DEP_LINK 
		AND
			DGH.DATE1 <= @D2 AND DGH.DATE2 >= @D1
		AND
		NOT EXISTS (
			SELECT E.PERS_LINK FROM DBO.SD_EMPL_FN(DEFAULT,@D2,DEFAULT,@DEP_LINK) E
			WHERE DGH.PERS_LINK = E.PERS_LINK AND DGH.DATE1 <= ISNULL(E.DATE_END,ISNULL(DGH.DATE2,@D2)) AND ISNULL(DGH.DATE2,@D2) >= E.DATE_BEGIN 
			)
ELSE
	SELECT --С начала года
		@M=SUM(CASE 
			WHEN DGH.DATE1<=@DBYEAR AND COALESCE(DGH.DATE2,@D2)>=@D2 THEN DATEDIFF(DAY,@DBYEAR,@D2)		-- РАБОТАЛ ВЕСЬ ПЕРИОД
			WHEN DGH.DATE1<=@DBYEAR AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE2>@DBYEAR THEN DATEDIFF(DAY,@DBYEAR,DGH.DATE2)+1	-- УВОЛЕН В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@DBYEAR  AND COALESCE(DGH.DATE2,@D2)>=@D2 AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,@D2) 		-- ПРИНЯТ В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@DBYEAR  AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,DGH.DATE2)+1	-- ПРИНЯТ И УВОЛЕН В РАБОЧИЙ ПЕРИОД
			 ELSE 0
		END)
	FROM 
		dbo.REESTR_DGH DGH
	WHERE
			DEP_LINK = @DEP_LINK 
		AND
			DGH.DATE1 <= @D2 AND DGH.DATE2 >= @DBYEAR
		AND
		NOT EXISTS (
			SELECT E.PERS_LINK FROM DBO.SD_EMPL_FN(DEFAULT,@D2,DEFAULT,@DEP_LINK) E
			WHERE DGH.PERS_LINK = E.PERS_LINK AND DGH.DATE1 <= ISNULL(E.DATE_END,ISNULL(DGH.DATE2,@D2)) AND ISNULL(DGH.DATE2,@D2) >= E.DATE_BEGIN 
			)				

DECLARE	@NDAYSFEBR	INT
IF @ATR_INCR_ITOG =2 
	SET @NDAYSFEBR = DAY(DBO.DATEENDOFMONTH(@D1))
ELSE
	SET @NDAYSFEBR = ISNULL((SELECT SUM(DAY(DBO.DATEENDOFMONTH(DATE_BEGIN))) FROM dbo.MONTHS_EX(@DBYEAR, @D2)),99999999)


----INSERT INTO #NZP_PART1 (COL, VAL)
----SELECT 4 AS COL, ROUND(@M/@NDAYSFEBR,0)

---- ВСЕГО (СУММА ГРАФ 2,3,4)
--INSERT INTO #P4_PART1
--SELECT 1 AS COL, SUM(VAL) FROM #P4_PART1 WHERE COL > 1

/* КОЛ-ВО ОТРАБОТ. ЧАСОВ */
DECLARE @ISMINUTES TINYINT
SET @ISMINUTES = DBO.SA_GET_OPTION_BY_CODE('TABEL_OPT10') --УЧЕТ ВРЕМЕНИ В ЧАСАХ И МИНУТАХ

/*КОЛИЧЕСТВО ОТРАБОТАННЫХ ЧЕЛОВЕКО-ЧАСОВ С НАЧАЛА ГОДА РАБОТНИКАМИ СПИСОЧНОГО СОСТАВА*/
/*INSERT INTO #P4_PART1 (COL, VAL)
SELECT [STATUS],  DBO.MINUTES_TO_NUM(SUM(DBO.NUM_TO_MINUTES([HOURS],@ISMINUTES)),@ISMINUTES)
FROM
(
	SELECT 
		[STATUS] = (CASE WHEN F.[STATUS] <> 3 THEN 5 ELSE 6 END),
		[HOURS] = DBO.SA_GET_EMPL_WH(LINK, DEFAULT,DEFAULT,PERIOD_BEG,PERIOD_END,DEFAULT,DEFAULT) 
	FROM 
		#EMPL1 F
) A
GROUP BY [STATUS]
*/
-- очистка лишних задвоений для тех у кого перевод, и дальнейшая работа происходила в течении месяца
delete FROM 
	#EMPL1 
WHERE
	LINK in (SELECT LINK FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1 ) 
	AND PERIOD_beg not in (SELECT min(PERIOD_beg) FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1 /*and  min(PERIOD_END) = @D2*/ ) 

/* ФОНД НАЧИСЛ З/ПЛАТЫ */
CREATE  TABLE #NZP_S_J_C ( SUMMA NUMERIC(20,1), STAT_OTCHET TINYINT, DEP_TYPE TINYINT, COL TINYINT,  CAT_NZP_LINK int, [SOURCE] TINYINT,  PERIOD_END DATETIME)

DECLARE @LINKEKR213 INT
SELECT @LINKEKR213 = LINK FROM DBO.DICTIONARY_ITEM WHERE CODE = '213'

CREATE TABLE #CJ (PERS_LINK INT, LINK_EMPL INT, LINK_PAYS INT, PERIOD_END DATETIME, SUMMA NUMERIC(18,2), STAT_OTCHET TINYINT, WAY_CALC TINYINT, DEP_TYPE TINYINT, CAT_NZP_LINK int , LINK_VKR int , [SOURCE] TINYINT)

INSERT INTO #CJ (PERS_LINK, LINK_EMPL, LINK_PAYS, PERIOD_END, SUMMA, STAT_OTCHET, WAY_CALC, DEP_TYPE , CAT_NZP_LINK, LINK_VKR , [SOURCE])
SELECT 
	PERS_LINK, LINK_EMPL, LINK_PAYS, 
	CASE WHEN WAY_CALC <> 15 THEN JC.PERIOD_BEGIN ELSE JC.DATE_BEGIN END, 
	SUMMA, STAT_OTCHET, WAY_CALC,
	CASE WHEN PERS_LINK IS NULL THEN 0 ELSE 5 END /* 5 - ФИЗ ЛИЦО */,
	null,
	JC.LINK_VKR,
	S.[SOURCE]
FROM
	DBO.CALCULATE_JURNAL JC 
	INNER JOIN DBO.PAYS P ON JC.LINK_PAYS = P.LINK 
	inner join SALARY_SRC_FIN S on S.LINK = JC.LINK_VKR
WHERE
	P.[OBJECT] = 1 /* ТОЛЬКО НАЧИСЛЕНИЯ */
	AND (P.WAY_CALC <> 15 AND YEAR(JC.PERIOD_BEGIN)=  YEAR(@D1) AND MONTH(JC.PERIOD_BEGIN) <= MONTH(@D1)
		OR P.WAY_CALC = 15 AND YEAR(JC.DATE_BEGIN)=  YEAR(@D1) AND MONTH(JC.DATE_BEGIN) <= MONTH(@D1))	
	AND P.STAT_OTCHET <> 3
	AND JC.LINK_DEP = @DEP_LINK


----------- суммы договорников, которые являются сотрудниками помеячаем считать как для сотрудников
UPDATE J
SET LINK_EMPL = E.LINK , dep_type = 1
FROM #CJ J INNER JOIN #EMPL1 E ON J.PERS_LINK = E.PERS_LINK AND J.[PERIOD_END] BETWEEN E.PERIOD_BEG AND E.PERIOD_END
----------- определим для всех имеющихся link_empl , категорию к которой они относятся 
UPDATE J
SET CAT_NZP_LINK = E.CAT_NZP_LINK 
FROM #CJ J INNER JOIN #EMPL1 E ON j.LINK_EMPL = E.link  


--- Для сотрудников которые были уволены, и выплаты для них были в следующем месяце входящем в период расчета, проставим конец периода как период последней оплаты  
UPDATE E
SET E.PERIOD_END = A.MAX_PERIOD_END
FROM 
	#EMPL1 E
	INNER JOIN (SELECT LINK_EMPL, MAX_PERIOD_END = MAX(PERIOD_END) FROM  #CJ  GROUP BY LINK_EMPL ) A 
		ON E.LINK = a.LINK_EMPL AND E.PERIOD_END < A.MAX_PERIOD_END
WHERE
	A.MAX_PERIOD_END <= @D2	
------------

INSERT INTO #NZP_S_J_C 
SELECT  SUMMA, STAT_OTCHET, DEP_TYPE, COALESCE(F.COL,0) , j.CAT_NZP_LINK, j.[SOURCE], J.[PERIOD_END]
FROM #CJ J INNER JOIN (SELECT LINK, (CASE WHEN STATUS=3 THEN 8 WHEN STATUS=2 THEN 7 ELSE 6 END) AS COL,PERIOD_BEG, PERIOD_END FROM #EMPL1) F 
		ON J.LINK_EMPL = F.LINK AND YEAR(j.[PERIOD_END]) * 100 + MONTH(J.[PERIOD_END]) 
				BETWEEN YEAR(F.PERIOD_BEG) * 100 + MONTH(F.PERIOD_BEG) AND YEAR(F.PERIOD_END) * 100 + MONTH(F.PERIOD_END)

------договорников , которые являются сотрудниками , пометим как внутренних совместителей------------------------------
update j
	set col = 7 
	from #NZP_S_J_C j where j.dep_type = 1
--------------------------------------
INSERT INTO #NZP_S_J_C
SELECT SUMMA, STAT_OTCHET, DEP_TYPE, 0,null, [SOURCE], PERIOD_END
FROM #CJ WHERE LINK_EMPL IS NULL


/*Фонд начисленной заработной платы работников за отчетный период*/
	/*списочного состава (без внешних совместителей)*/
	/* ВСЕГО */
	/* COL6!  ВСЕ код 100 */
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT '100' , 6, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C
	--	WHERE COL <>(8) AND STAT_OTCHET=1 AND DEP_TYPE<>5
	--		AND CAT_NZP_LINK IS NOT NULL
	--		AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			
	/* COL6! ВСЕ код 100  */		
	INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	SELECT '100' , 6, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C 
	WHERE COL <>(8) AND STAT_OTCHET=1 AND DEP_TYPE<>5
			AND CAT_NZP_LINK IS NOT NULL
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)	


		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 6, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL <>(8) AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG <> 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)	
																	
																		
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 6

    /*в том числе по внутреннему совместительству*/	
	/* COL7! ВСЕ  - код 100 */
	INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT '100', 7, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C 
		WHERE COL=7 AND STAT_OTCHET=1 AND DEP_TYPE<>5
			AND CAT_NZP_LINK IS NOT NULL
			--AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)			

	
		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 7, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL=7 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG != 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)	
																		
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 7
	
	/*внешних совместителей*/	

	/* COL8! ВСЕ  - код 100 */
	INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT '100',8, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C
		WHERE COL=8 AND STAT_OTCHET=1 AND DEP_TYPE<>5
			AND CAT_NZP_LINK IS NOT NULL
			--AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)	
			
	/* COL8! РАЗБИВКА ПО КОДАМ*/
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT c.code,8, isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
	--	inner join #CAT_CODES c on  s.CAT_NZP_LINK = c.link
	--	WHERE s.COL=8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5
	--		AND s.CAT_NZP_LINK IS NOT NULL
	--		AND
	--		(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
	--			OR
	--			@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
	--		)	
	--	GROUP BY c.code		

		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 8, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL=8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG <> 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)	
																																
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 8


	/*Фонд начисленной заработной платы работников по источникам финансирования*/
	/*из гр. 3 списочного состава (без внешних совместителей) col6 */
	/*за счет средств бюджетов всех уровней (субсидий)*/
	/* COL9! Все - код 100*/
	INSERT INTO #NZP_PART1 (CODE_STR,COL, VAL)
		SELECT '100', 9, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C
		WHERE COL<>8 AND STAT_OTCHET=1 AND DEP_TYPE<>5 and [SOURCE] not in (2,7)
			AND CAT_NZP_LINK IS NOT NULL
			--AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)	
			
			
	/* COL9! Разбивка по кодам*/
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT c.code,9, isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
	--	inner join #CAT_CODES c on  s.CAT_NZP_LINK = c.link
	--	WHERE s.COL<>8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] not in (2,7)
	--		AND s.CAT_NZP_LINK IS NOT NULL
	--		AND
	--		(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
	--			OR
	--			@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
	--		)	
	--	GROUP BY c.code		


		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 9, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL<>8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] not in (2,7)
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG <> 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)	
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 9


	/*Фонд начисленной заработной платы работников по источникам финансирования*/
	/*из гр. 3 списочного состава (без внешних совместителей) col6 */
	/*ОМС*/
	/* COL10! Все - код 100*/
	INSERT INTO #NZP_PART1 (CODE_STR,COL, VAL)
		SELECT '100', 10, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C
		WHERE COL<>8 AND STAT_OTCHET=1 AND DEP_TYPE<>5 and [SOURCE]= 7
			AND CAT_NZP_LINK IS NOT NULL
			--AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)
			
	/* COL10! Разбивка по кодам*/
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT c.code,10, isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
	--	inner join #CAT_CODES c on  s.CAT_NZP_LINK = c.link
	--	WHERE s.COL<>8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] =7
	--		AND s.CAT_NZP_LINK IS NOT NULL
	--		AND
	--		(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
	--			OR
	--			@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
	--		)	
	--	GROUP BY c.code	

		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 10, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL<>8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] =7
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG <> 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)	
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 10


	/*Фонд начисленной заработной платы работников по источникам финансирования*/
	/*из гр. 3 списочного состава (без внешних совместителей) col6 */
	/*средства от приносящей доход деятельности*/
	/* COL11! Все - код 100*/
	INSERT INTO #NZP_PART1 (CODE_STR,COL, VAL)
		SELECT '100', 11, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C
		WHERE COL<>8 AND STAT_OTCHET=1 AND DEP_TYPE<>5 and [SOURCE]= 2
			AND CAT_NZP_LINK IS NOT NULL
			--AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)
	/* COL11! Разбивка по кодам*/
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT c.code,11, isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
	--	inner join #CAT_CODES c on  s.CAT_NZP_LINK = c.link
	--	WHERE s.COL<>8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] =2
	--		AND s.CAT_NZP_LINK IS NOT NULL
	--		AND
	--		(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
	--			OR
	--			@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
	--		)	
	--	GROUP BY c.code	

		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 11, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL<>8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] =2
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG <> 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)																		
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 11


	/*Фонд начисленной заработной платы работников по источникам финансирования*/
	/*из гр.5 внешних совместителей col8 */
	/*за счет средств бюджетов всех уровней (субсидий)*/
	/* COL12! Все - код 100*/
	INSERT INTO #NZP_PART1 (CODE_STR,COL, VAL)
		SELECT '100', 12, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C
		WHERE COL=8 AND STAT_OTCHET=1 AND DEP_TYPE<>5 and [SOURCE] not in (2,7)
			AND CAT_NZP_LINK IS NOT NULL
			--AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)			
	/* COL12! Разбивка по кодам*/
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT c.code,12, isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
	--	inner join #CAT_CODES c on  s.CAT_NZP_LINK = c.link
	--	WHERE s.COL=8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] not in (2,7)
	--		AND s.CAT_NZP_LINK IS NOT NULL
	--		AND
	--		(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
	--			OR
	--			@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
	--		)	
	--	GROUP BY c.code	
		
		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 12, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL=8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] not in (2,7)
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG <> 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)																		
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 12	

	/*Фонд начисленной заработной платы работников по источникам финансирования*/
	/*из гр.5 внешних совместителей col8 */
	/*ОМС*/
	/* COL13! Все - код 100*/
	INSERT INTO #NZP_PART1 (CODE_STR,COL, VAL)
		SELECT '100', 13, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C
		WHERE COL=8 AND STAT_OTCHET=1 AND DEP_TYPE<>5 and [SOURCE]=7
			AND CAT_NZP_LINK IS NOT NULL
			--AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)			
	/* COL13! Разбивка по кодам*/
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT c.code,13, isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
	--	inner join #CAT_CODES c on  s.CAT_NZP_LINK = c.link
	--	WHERE s.COL=8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] =7
	--		AND s.CAT_NZP_LINK IS NOT NULL
	--		AND
	--		(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
	--			OR
	--			@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
	--		)	
	--	GROUP BY c.code	

		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 13, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL=8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE] =7
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG <> 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)																		
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 13	


	/*Фонд начисленной заработной платы работников по источникам финансирования*/
	/*из гр.5 внешних совместителей col8 */
	/*средства от приносящей доход деятельности*/
	/* COL14! Все - код 100*/
	INSERT INTO #NZP_PART1 (CODE_STR,COL, VAL)
		SELECT '100', 14, isnull((SUM(SUMMA)/1000),0) FROM #NZP_S_J_C
		WHERE COL=8 AND STAT_OTCHET=1 AND DEP_TYPE<>5 and [SOURCE]=2
			AND CAT_NZP_LINK IS NOT NULL
			--AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
			AND  
			(	@ATR_INCR_ITOG <> 2  AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@ATR_INCR_ITOG =2  AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)			
	/* COL14! Разбивка по кодам*/
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT c.code,14, isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
	--	inner join #CAT_CODES c on  s.CAT_NZP_LINK = c.link
	--	WHERE s.COL=8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE]=2
	--		AND s.CAT_NZP_LINK IS NOT NULL
	--		AND
	--		(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
	--			OR
	--			@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
	--		)	
	--	GROUP BY c.code							

		INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
		SELECT c.code, 14, 0 FROM #CAT_CODES c 
		
		UPDATE N
			set  VAL = isnull((SELECT isnull((SUM(s.SUMMA)/1000),0) FROM #NZP_S_J_C s
																WHERE  s.CAT_NZP_LINK = c1.link and  s.COL=8 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5 and S.[SOURCE]=2
																	AND s.CAT_NZP_LINK IS NOT NULL
																	--AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																	AND  
																	(	@ATR_INCR_ITOG <> 2  AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
																		OR
																		@ATR_INCR_ITOG =2  AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
																	)																		
																GROUP BY s.CAT_NZP_LINK),0)
		FROM #NZP_PART1 n  inner join #CAT_CODES c1 on c1.code = n.CODE_STR and n.COL = 14


/*Для каждой формы просуммируем строки ИЗ которых выделяются другие строки*/
IF @CODE_FORM = '0606045'
BEGIN
	declare @i int
	set @i = 6 
	WHILE @i <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '282' and COL = @i),0)	
		where CODE_STR = '281' and COL = @i	
		set @i = @i+1 
	END 	

	set @i = 6 
	WHILE @i <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = @i),0)	
		where CODE_STR = '3013' and COL = @i	
		set @i = @i + 1
	END 	

END
IF @CODE_FORM = '0606046'  
BEGIN
	declare @i1 int
	set @i1 = 6 
	WHILE @i1 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = @i1),0)			
		where CODE_STR = '3013' and COL = @i1	
		set @i1 = @i1 +1 	
	END

	set @i1 = 6 
	WHILE @i1 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + ISNULL((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '401'  and COL = @i1),0) + ISNULL((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '291'  and COL = @i1),0) + ISNULL((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '3013'  and COL = @i1),0)			
		where CODE_STR = '621' and COL = @i1	
		set @i1 = @i1 +1 	
	END

END


IF @CODE_FORM = '0606047' 
BEGIN
	declare @i2 int
	set @i2 = 6 
	WHILE @i2 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT SUM(isnull(VAL,0)) FROM #NZP_PART1 WHERE CODE_STR IN ('312','313') and COL = @i2),0)			
		where CODE_STR = '3113' and COL = @i2
		set @i2 = @i2+1 
	END 
	
	set @i2 = 6 
	WHILE @i2 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT SUM(isnull(VAL,0)) FROM #NZP_PART1 WHERE CODE_STR IN ('3113','102','101','302') and COL = @i2),0)			
		where CODE_STR = '3014' and COL = @i2
		set @i2 = @i2+1 
	END 

END 
IF @CODE_FORM = '0606048'  
BEGIN
	declare @i3 int
	set @i3 = 6 
	WHILE @i3 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '212' and COL = @i3),0)			
		where CODE_STR = '211' and COL = @i3
		set @i3 = @i3+1 
	END 	

	set @i3 = 6 
	WHILE @i3 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT SUM(isnull(VAL,0)) FROM #NZP_PART1 WHERE CODE_STR IN ('232','233') and COL = @i3),0)			
		where CODE_STR = '231' and COL = @i3	
		set @i3 = @i3+1 
	END 	

	set @i3 = 6 
	WHILE @i3 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT SUM(isnull(VAL,0)) FROM #NZP_PART1 WHERE CODE_STR IN ('242','243') and COL = @i3),0)			
		where CODE_STR = '241' and COL = @i3	
		set @i3 = @i3+1 
	END 		

	set @i3 = 6 
	WHILE @i3 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT SUM(isnull(VAL,0)) FROM #NZP_PART1 WHERE CODE_STR IN ('252','253') and COL = @i3),0)			
		where CODE_STR = '251' and COL = @i3	
		set @i3 = @i3+1 
	END 

	set @i3 = 6 
	WHILE @i3 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR ='3111' and COL = @i3),0)			
		where CODE_STR = '3011' and COL = @i3	
		set @i3 = @i3+1 
	END 	

	set @i3 = 6 
	WHILE @i3 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR ='3112' and COL = @i3),0)			
		where CODE_STR = '3012' and COL = @i3	
		set @i3 = @i3+1 
	END 	

END

IF @CODE_FORM = '0606049'
BEGIN
	
	declare @i4 int
	set @i4 = 6 
	WHILE @i4 <= 14
	begin
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '282' and COL = @i4),0)	
		where CODE_STR = '281' and COL = @i4	
		set @i4 = @i4+1 
	END 			

	set @i4 = 6 
	WHILE @i4 <= 14
	begin	
		UPDATE  #NZP_PART1 
		set VAL = VAL + isnull((SELECT isnull(VAL,0) FROM #NZP_PART1 WHERE CODE_STR = '3113' and COL = @i4),0)	
		where CODE_STR = '3013' and COL = @i4
		set @i4 = @i4+1 
	END 	

END




DROP TABLE #NZP_S_J_C
DROP TABLE #CAT_CODES

/**********************************************************************************************************************/
/* СОЗДАЕМ ВРЕМЕНННУЮ ТАБЛИЦУ */
DECLARE @RESULT_TABLE VARCHAR(100)
EXEC DBO.X_GET_TABLE_NAME @RESULT_TABLE OUTPUT

EXEC DBO.I_REPORT_FORMULA_ERASE_TABLES 0
EXEC ('SELECT * INTO ' + @RESULT_TABLE + ' FROM #NZP_PART1 ')
EXEC DBO.BUFFERPUSH -151, @RESULT_TABLE
	SET @OUT_VAL = ''


DROP TABLE #NZP_PART1

END









GO


GRANT EXECUTE ON dbo.[SA_NZP_PREPARE] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SZV_K_PACHKA_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZV_K_PACHKA_SAVE]

GO
CREATE   PROCEDURE dbo.SA_SZV_K_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_SVED		tinyint = null,
	@LINK_ISHOD 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 @type_sved  IS NULL 
BEGIN
	ROLLBACK
	RETURN 5
END

SELECT @varKSsoLink = LINK FROM s_objects  WHERE CODE = 'SA_SZV_K_PACHKA'

IF @LINK is null OR @LINK = 0
	BEGIN  
		INSERT INTO dbo.SZV_K_PACHKA WITH (ROWLOCK) (Numer,[Date],type_sved, link_dep,LINK_ISHOD)  
			VALUES (@Numer, @Date ,@type_sved, @DEP_LINK,@LINK_ISHOD)

		SELECT @varKSERROR = @@ERROR, @LINK = @@IDENTITY
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
ELSE
	BEGIN
		UPDATE dbo.SZV_K_PACHKA WITH (ROWLOCK) 
		SET 	Numer = @Numer, [Date] = @Date, type_sved = @type_sved , LINK_ISHOD = @LINK_ISHOD
		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_SZV_K_PACHKA',@LINK
WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN

RETURN 0





GO


GRANT EXECUTE ON dbo.[SA_SZV_K_PACHKA_SAVE] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SS_PROV_EXPORT]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SS_PROV_EXPORT]

GO

CREATE PROCEDURE [dbo].SS_PROV_EXPORT (
@buffer varchar(20) /*Ссылка на расчет*/
) AS




CREATE TABLE #OUTPUT (ID int identity(1,1), F_NAME VARCHAR(254), OUT_TEXT TEXT)

SET NOCOUNT ON

CREATE TABLE #DOC(LINK INT)


INSERT INTO #DOC (LINK)
SELECT LINK FROM dbo.BUFFER WITH (NOLOCK) WHERE ID = @BUFFER AND SID = SUSER_SID()

--ЗАПИСИ по проводкам

CREATE TABLE #PROV_DOC (	
GP_LINK INT ,
GP_GUID UNIQUEIDENTIFIER,
GP_NUMBER VARCHAR (25),
GP_DATE DATETIME,
GP_OBJ INT,
GP_OBJ_CODE CHAR(30), 
GP_OBJ_NAME VARCHAR(254),
GP_DATE_PROV DATETIME,
GP_SUMMA NUMERIC(19,2),
GP_COMMENT VARCHAR(254),
GP_GET_STORE TINYINT,
GP_DEP INT,
GP_ACC INT,
GP_ACC_CODE VARCHAR(20),
GP_ACC_TYPE TINYINT, 

GP1_LINK INT,
GP1_LINK_UP INT,
GP1_OPER INT,
GP1_NAME_OPER VARCHAR(250),
GP1_ORDERS INT,

GP2_LINK INT,
GP2_LINK_UP INT,
GP2_SUMMA NUMERIC (19,2) ,
GP2_QUANTITY NUMERIC (19,4) ,
GP2_STORNO TINYINT,
GP2_LINK_SELF INT,
GP2_NAME VARCHAR(254),
GP2_ORDERS SMALLINT,
GP2_EC_OPER INT,
GP2_EC_OPER_CODE CHAR(5),
GP2_EC_OPER_NAME VARCHAR(254),


GPAP_D_LINK_UP INT,
GPAP_D_DB_KR TINYINT,
GPAP_D_ACC INT,
GPAP_D_KBK INT,
GPAP_D_EKR INT,
GPAP_D_DEP INT,
GPAP_D_SUB INT,
GPAP_D_EMP INT,
GPAP_D_NOMEN INT,
GPAP_D_INV INT,
GPAP_D_KAU INT,
GPAP_D_DEP_ACC INT,
GPAP_D_TMC INT,
GPAP_D_INDATE DATETIME,
GPAP_D_SGU INT,
GPAP_D_AP1 INT,
GPAP_D_AP2 INT,
GPAP_D_AP3 INT,


GPAP_K_LINK_UP INT,
GPAP_K_DB_KR INT,
GPAP_K_ACC INT,
GPAP_K_KBK INT,
GPAP_K_EKR INT,
GPAP_K_DEP INT, 
GPAP_K_SUB INT,
GPAP_K_EMP INT,
GPAP_K_NOMEN INT,
GPAP_K_INV INT,
GPAP_K_KAU INT,
GPAP_K_DEP_ACC INT,
GPAP_K_TMC INT,
GPAP_K_INDATE DATETIME,
GPAP_K_SGU INT,
GPAP_K_AP1 INT,
GPAP_K_AP2 INT,
GPAP_K_AP3 INT)





CREATE TABLE #DEP_INFO (
	DEP_LINK INT,
	DEP_CODE VARCHAR(10),
	DEP_NAME varchar(256),
	DEP_FNAME varchar(256),
	INN VARCHAR(12),
	KPP VARCHAR(9))


CREATE TABLE #G_PROV_AP_FULL	( GP_LINK INT,
	GPAP_D_LINK_UP INT,
	GPAP_D_DB_KR TINYINT,
	GPAP_D_ACC INT,
	GPAP_D_name VARCHAR(150),
	GPAP_D_CODE VARCHAR(13),
	GPAP_D_cSource VARCHAR(1),
	GPAP_D_cSinth VARCHAR(3),
	GPAP_D_cAnalit VARCHAR(2),
	
	GPAP_D_KBK INT,
	GPAP_D_KBK_type TINYINT,GPAP_D_KBK_code CHAR(20),GPAP_D_KBK_NAME VARCHAR(250),
	
	GPAP_D_EKR INT,
	GPAP_D_EKR_code CHAR(3),	GPAP_D_EKR_NAME VARCHAR(250), GPAP_D_EKR_ls_ekr TINYINT,

	GPAP_D_DEP INT,
	GPAP_D_DEP_CODE VARCHAR(10),
	GPAP_D_DEP_NAME varchar(256),
	GPAP_D_DEP_FNAME varchar(256),
	GPAP_D_DEP_INN VARCHAR(12),
	GPAP_D_DEP_KPP VARCHAR(9),
	
	GPAP_D_SUB INT,
	GPAP_D_SUB_code VARCHAR(5), 
	GPAP_D_SUB_NAME VARCHAR(254), 
	GPAP_D_SUB_lim int , 
	GPAP_D_SUB_obosob TINYINT, 
	GPAP_D_SUB_okato VARCHAR(14), 
	GPAP_D_SUB_okpp VARCHAR(9), 
	GPAP_D_SUB_oktmo  VARCHAR(11),
	
	GPAP_D_EMP INT,
	GPAP_D_EMP_tab VARCHAR(10), 
	GPAP_D_EMP_fm VARCHAR(100), 
	GPAP_D_EMP_im VARCHAR(100), 
	GPAP_D_EMP_ot VARCHAR(100), 
	GPAP_D_EMP_FIO VARCHAR(105), 
	GPAP_D_EMP_INSUR_NUM VARCHAR(14), 
	GPAP_D_EMP_INN VARCHAR(12), 
	GPAP_D_EMP_date_begin datetime, 
	GPAP_D_EMP_date_end DATETIME, 
	
	GPAP_D_NOMEN INT,
	GPAP_D_NOMEN_CODE VARCHAR(20),GPAP_D_NOMEN_NAME VARCHAR(254),
	
	GPAP_D_INV INT,
	GPAP_D_INV_code VARCHAR(20),	GPAP_D_INV_NAME VARCHAR(254),
	
	GPAP_D_KAU INT,
	GPAP_D_KAU_code VARCHAR(20), GPAP_D_KAU_name VARCHAR(100), GPAP_D_KAU_thema VARCHAR(50),
	
	GPAP_D_DEP_ACC INT,
	GPAP_D_DEP_ACC_code VARCHAR(20), GPAP_D_DEP_ACC_TYPE TINYINT,
	
	GPAP_D_TMC INT,
	GPAP_D_TMC_NAME VARCHAR(254),GPAP_D_TMC_code VARCHAR(20) ,
	
	GPAP_D_INDATE DATETIME,
	GPAP_D_SGU INT,
	GPAP_D_SGU_code CHAR(3) , GPAP_D_SGU_NAME VARCHAR(250), GPAP_D_SGU_ls_ekr tinyint , 
	
	GPAP_D_AP1 INT,
	GPAP_D_AP1_TYPE_LINK int , GPAP_D_AP1_doc_link  INT , GPAP_D_AP1_NUMBER VARCHAR (25), GPAP_D_AP1_DATE DATETIME, GPAP_D_AP1_CODE CHAR(30), GPAP_D_AP1_NAME VARCHAR(254),
					GPAP_D_AP1_DATE_PROV DATETIME, GPAP_D_AP1_SUMMA NUMERIC(19,2),
	
	GPAP_D_AP2 INT,
	GPAP_D_AP2_code VARCHAR(20), GPAP_D_AP2_NAME VARCHAR(150),
	GPAP_D_AP3 INT,


	GPAP_K_LINK_UP INT,
	GPAP_K_DB_KR TINYINT,
	GPAP_K_ACC INT,
	GPAP_K_name VARCHAR(150),
	GPAP_K_CODE VARCHAR(13),
	GPAP_K_cSource VARCHAR(1),
	GPAP_K_cSinth VARCHAR(3),
	GPAP_K_cAnalit VARCHAR(2),
	
	GPAP_K_KBK INT,
	GPAP_K_KBK_type TINYINT,GPAP_K_KBK_code CHAR(20),GPAP_K_KBK_NAME VARCHAR(250),
	
	GPAP_K_EKR INT,
	GPAP_K_EKR_code CHAR(3),	GPAP_K_EKR_NAME VARCHAR(250), GPAP_K_EKR_ls_ekr TINYINT,

	GPAP_K_DEP INT,
	GPAP_K_DEP_CODE VARCHAR(10),
	GPAP_K_DEP_NAME varchar(256),
	GPAP_K_DEP_FNAME varchar(256),
	GPAP_K_DEP_INN VARCHAR(12),
	GPAP_K_DEP_KPP VARCHAR(9),
	
	GPAP_K_SUB INT,
	GPAP_K_SUB_code VARCHAR(5), 
	GPAP_K_SUB_NAME VARCHAR(254), 
	GPAP_K_SUB_lim int , 
	GPAP_K_SUB_obosob TINYINT, 
	GPAP_K_SUB_okato VARCHAR(14), 
	GPAP_K_SUB_okpp VARCHAR(9), 
	GPAP_K_SUB_oktmo  VARCHAR(11),
	
	GPAP_K_EMP INT,
	GPAP_K_EMP_tab VARCHAR(10), 
	GPAP_K_EMP_fm VARCHAR(100), 
	GPAP_K_EMP_im VARCHAR(100), 
	GPAP_K_EMP_ot VARCHAR(100), 
	GPAP_K_EMP_FIO VARCHAR(105), 
	GPAP_K_EMP_INSUR_NUM VARCHAR(14), 
	GPAP_K_EMP_INN VARCHAR(12), 
	GPAP_K_EMP_date_begin datetime, 
	GPAP_K_EMP_date_end DATETIME, 
	
	GPAP_K_NOMEN INT,
	GPAP_K_NOMEN_CODE VARCHAR(20),GPAP_K_NOMEN_NAME VARCHAR(254),
	
	GPAP_K_INV INT,
	GPAP_K_INV_code VARCHAR(20),	GPAP_K_INV_NAME VARCHAR(254),
	
	GPAP_K_KAU INT,
	GPAP_K_KAU_code VARCHAR(20), GPAP_K_KAU_name VARCHAR(100), GPAP_K_KAU_thema VARCHAR(50),
	
	GPAP_K_DEP_ACC INT,
	GPAP_K_DEP_ACC_code VARCHAR(20), GPAP_K_DEP_ACC_TYPE TINYINT,
	
	GPAP_K_TMC INT,
	GPAP_K_TMC_NAME VARCHAR(254), GPAP_K_TMC_code VARCHAR(20) ,
	
	GPAP_K_INDATE DATETIME,
	GPAP_K_SGU INT,
	GPAP_K_SGU_code CHAR(3) , GPAP_K_SGU_NAME VARCHAR(250), GPAP_K_SGU_ls_ekr tinyint , 
	
	GPAP_K_AP1 INT,
	GPAP_K_AP1_TYPE_LINK int , GPAP_K_AP1_doc_link int  , GPAP_K_AP1_NUMBER VARCHAR (25), GPAP_K_AP1_DATE DATETIME, GPAP_K_AP1_CODE CHAR(30), GPAP_K_AP1_NAME VARCHAR(254),
	GPAP_K_AP1_DATE_PROV DATETIME, GPAP_K_AP1_SUMMA NUMERIC(19,2),
	
	GPAP_K_AP2 INT,
	GPAP_K_AP2_code VARCHAR(20), GPAP_K_AP2_NAME VARCHAR(150),
	GPAP_K_AP3 INT) 
	
INSERT into #PROV_DOC ( GP_LINK,GP_GUID,GP_NUMBER,GP_DATE,GP_OBJ,
								GP_OBJ_CODE,GP_OBJ_NAME,
						GP_DATE_PROV,GP_SUMMA,
						GP_COMMENT,GP_GET_STORE,GP_DEP,GP_ACC,
						GP_ACC_CODE, GP_ACC_TYPE,
						GP1_LINK,GP1_LINK_UP,GP1_OPER,GP1_NAME_OPER,GP1_ORDERS,
						GP2_LINK,GP2_LINK_UP,GP2_SUMMA,GP2_QUANTITY,GP2_STORNO,GP2_LINK_SELF,GP2_NAME,GP2_ORDERS,GP2_EC_OPER,
								GP2_EC_OPER_CODE,GP2_EC_OPER_NAME,
						GPAP_D_LINK_UP,GPAP_D_DB_KR,GPAP_D_ACC,GPAP_D_KBK,GPAP_D_EKR,GPAP_D_DEP,GPAP_D_SUB,GPAP_D_EMP,GPAP_D_NOMEN,
						GPAP_D_INV,GPAP_D_KAU,GPAP_D_DEP_ACC, GPAP_D_TMC,GPAP_D_INDATE,GPAP_D_SGU,GPAP_D_AP1,GPAP_D_AP2,GPAP_D_AP3,
						GPAP_K_LINK_UP,GPAP_K_DB_KR,GPAP_K_ACC,GPAP_K_KBK,GPAP_K_EKR,GPAP_K_DEP,GPAP_K_SUB,GPAP_K_EMP,GPAP_K_NOMEN,
						GPAP_K_INV,GPAP_K_KAU,GPAP_K_DEP_ACC,GPAP_K_TMC,GPAP_K_INDATE,GPAP_K_SGU,GPAP_K_AP1,GPAP_K_AP2,GPAP_K_AP3)

SELECT  G.LINK,G.[GUID],G.NUMBER,G.[DATE],G.[OBJECT],
		G.S_OBJECTS_CODE,G.S_OBJECTS_NAME,
	    G.DATE_PROV,G.SUMMA,G.COMMENT,G.GET_STORE,G.DEP,G.ACC,
		G.department_accounts_CODE,G.DEPARTMENT_ACCOUNTS_TYPE,
		G1.LINK,G1.LINK_UP,G1.OPER,G1.NAME_OPER,G1.ORDERS,
		G2.LINK,G2.LINK_UP,G2.SUMMA,G2.QUANTITY,G2.STORNO,
		G2.LINK_SELF,G2.NAME,G2.ORDERS,
		G2.ECON_OPER,G2.XOZ_OPER_CODE,G2.XOZ_OPER_NAME,
		GAP1.LINK_UP,GAP1.DB_KR,GAP1.ACCOUNT,GAP1.KBK,GAP1.EKR,GAP1.DEP,GAP1.SUB,GAP1.EMP,GAP1.NOMEN,
		GAP1.INV,GAP1.KAU,GAP1.DEP_ACC, GAP1.TMC,GAP1.INDATE,GAP1.SGU,GAP1.AP1,GAP1.AP2,GAP1.AP3,
		GAP2.LINK_UP,GAP2.DB_KR,GAP2.ACCOUNT,GAP2.KBK,GAP2.EKR,GAP2.DEP,GAP2.SUB,GAP2.EMP,GAP2.NOMEN,
		GAP2.INV,GAP2.KAU,GAP2.DEP_ACC,GAP2.TMC,GAP2.INDATE,GAP2.SGU,GAP2.AP1,GAP2.AP2,GAP2.AP3
FROM
	(select GG.LINK, gg.[GUID],GG.NUMBER,GG.[DATE],GG.[OBJECT],
			S_OBJECTS_CODE = S.CODE,S_OBJECTS_NAME = S.NAME, 
			GG.DATE_PROV,GG.SUMMA, GG.COMMENT,
			GG.GET_STORE,GG.DEP,GG.ACC,	
			department_accounts_CODE = da.CODE, 
			DEPARTMENT_ACCOUNTS_TYPE = DA.[TYPE] 
	from dbo.G_PROV GG 
	INNER JOIN  s_objects s ON s.LINK = GG.[OBJECT] AND s.CODE = 'DOCUMENTS_SALARY'     
	LEFT JOIN DEPARTMENT_ACCOUNTS da ON da.LINK = GG.ACC) G
INNER JOIN (SELECT GG1.LINK,GG1.LINK_UP,GG1.OPER,
					   G_PROV1_NAME_OPER = GGG1.NAME_OPER,
					   GG1.NAME_OPER,GG1.ORDERS 
				from dbo.G_PROV1 gg1 
				LEFT JOIN dbo.G_PROV1 ggg1 ON ggg1.LINK = gg1.OPER ) G1  ON G1.LINK_UP = G.LINK
INNER JOIN (SELECT 	GG2.LINK,GG2.LINK_UP,
					GG2.SUMMA,GG2.QUANTITY,
					GG2.STORNO,GG2.LINK_SELF,
					G_PROV2_NAME = GGG2.NAME, 
					GG2.NAME,GG2.ORDERS,GG2.ECON_OPER,
					XOZ_OPER_CODE = xog.CODE+'.'+ xo.CODE ,XOZ_OPER_NAME = XO.NAME
	            from dbo.G_PROV2 GG2 
	            INNER JOIN XOZ_OPER xo ON xo.LINK = GG2.ECON_OPER
	            INNER JOIN xoz_oper_group xog ON xog.LINK = xo.GROUP_LINK
				LEFT JOIN dbo.G_PROV2 GGG2 ON GGG2.LINK = GG2.LINK_SELF ) G2 ON G2.LINK_UP = G1.LINK
INNER JOIN dbo.G_PROV_AP GAP1 ON GAP1.LINK_UP = G2.LINK
INNER JOIN dbo.G_PROV_AP GAP2 ON GAP2.LINK_UP = G2.LINK
WHERE
	GAP1.DB_KR = 0
	AND
	GAP2.DB_KR = 1
	AND
	G2.LINK IN ( SELECT link FROM #DOC )
		

INSERT #DEP_INFO ( DEP_LINK, DEP_CODE, DEP_NAME, DEP_FNAME, INN, KPP)
SELECT DISTINCT link , code , NAME , FULL_name , inn , kpp
FROM  #PROV_DOC g  
	INNER JOIN departments d ON g.GP_DEP = d.link
	
	

INSERT INTO #G_PROV_AP_FULL	(  GP_LINK,
	GPAP_D_LINK_UP,
	GPAP_D_DB_KR,
	GPAP_D_ACC,
	GPAP_D_name,
	GPAP_D_CODE,
	GPAP_D_cSource,
	GPAP_D_cSinth,
	GPAP_D_cAnalit,
	
	GPAP_D_KBK,
	GPAP_D_KBK_type,GPAP_D_KBK_code,GPAP_D_KBK_NAME,
	
	GPAP_D_EKR, 
	GPAP_D_EKR_code,GPAP_D_EKR_NAME, GPAP_D_EKR_ls_ekr,

	GPAP_D_DEP,
	GPAP_D_DEP_CODE,
	GPAP_D_DEP_NAME,
	GPAP_D_DEP_FNAME,
	GPAP_D_DEP_INN,
	GPAP_D_DEP_KPP,
	
	GPAP_D_SUB,
	GPAP_D_SUB_code, 
	GPAP_D_SUB_NAME, 
	GPAP_D_SUB_lim, 
	GPAP_D_SUB_obosob, 
	GPAP_D_SUB_okato, 
	GPAP_D_SUB_okpp, 
	GPAP_D_SUB_oktmo,
	
	GPAP_D_EMP,
	GPAP_D_EMP_tab, 
	GPAP_D_EMP_fm, 
	GPAP_D_EMP_im, 
	GPAP_D_EMP_ot, 
	GPAP_D_EMP_FIO, 
	GPAP_D_EMP_INSUR_NUM, 
	GPAP_D_EMP_INN, 
	GPAP_D_EMP_date_begin, 
	GPAP_D_EMP_date_end, 
	
	GPAP_D_NOMEN,
	GPAP_D_NOMEN_CODE,GPAP_D_NOMEN_NAME,
	
	GPAP_D_INV,
	GPAP_D_INV_code,	GPAP_D_INV_NAME,
	
	GPAP_D_KAU,
	GPAP_D_KAU_code, GPAP_D_KAU_name, GPAP_D_KAU_thema,
	
	GPAP_D_DEP_ACC,
	GPAP_D_DEP_ACC_code, GPAP_D_DEP_ACC_TYPE,
	
	GPAP_D_TMC,
	GPAP_D_TMC_NAME, GPAP_D_TMC_code,
	
	GPAP_D_INDATE,
	GPAP_D_SGU,
	GPAP_D_SGU_code, GPAP_D_SGU_NAME, GPAP_D_SGU_ls_ekr, 
	
	GPAP_D_AP1,
	GPAP_D_AP1_TYPE_LINK, GPAP_D_AP1_doc_link, GPAP_D_AP1_NUMBER, GPAP_D_AP1_DATE, GPAP_D_AP1_CODE, GPAP_D_AP1_NAME,
					GPAP_D_AP1_DATE_PROV, GPAP_D_AP1_SUMMA, 
	
	GPAP_D_AP2,
	GPAP_D_AP2_code, GPAP_D_AP2_NAME,
	GPAP_D_AP3,


	GPAP_K_LINK_UP,
	GPAP_K_DB_KR,
	GPAP_K_ACC,
	GPAP_K_name,
	GPAP_K_CODE,
	GPAP_K_cSource,
	GPAP_K_cSinth,
	GPAP_K_cAnalit,
	
	GPAP_K_KBK,
	GPAP_K_KBK_type,GPAP_K_KBK_code,GPAP_K_KBK_NAME,

	GPAP_K_EKR,
	GPAP_K_EKR_code,	GPAP_K_EKR_NAME, GPAP_K_EKR_ls_ekr,


	GPAP_K_DEP ,
	GPAP_K_DEP_CODE,
	GPAP_K_DEP_NAME,
	GPAP_K_DEP_FNAME,
	GPAP_K_DEP_INN,
	GPAP_K_DEP_KPP,


	GPAP_K_SUB,
	GPAP_K_SUB_code, 
	GPAP_K_SUB_NAME, 
	GPAP_K_SUB_lim, 
	GPAP_K_SUB_obosob, 
	GPAP_K_SUB_okato, 
	GPAP_K_SUB_okpp, 
	GPAP_K_SUB_oktmo,
	

	GPAP_K_EMP ,
	GPAP_K_EMP_tab, 
	GPAP_K_EMP_fm, 
	GPAP_K_EMP_im, 
	GPAP_K_EMP_ot, 
	GPAP_K_EMP_FIO, 
	GPAP_K_EMP_INSUR_NUM, 
	GPAP_K_EMP_INN, 
	GPAP_K_EMP_date_begin, 
	GPAP_K_EMP_date_end, 
	
	GPAP_K_NOMEN,
	GPAP_K_NOMEN_CODE,GPAP_K_NOMEN_NAME,
	
	GPAP_K_INV,
	GPAP_K_INV_code,GPAP_K_INV_NAME,
	
	GPAP_K_KAU,
	GPAP_K_KAU_code, GPAP_K_KAU_name, GPAP_K_KAU_thema,
	
	GPAP_K_DEP_ACC,
	GPAP_K_DEP_ACC_code, GPAP_K_DEP_ACC_TYPE,
	
	GPAP_K_TMC,
	GPAP_K_TMC_NAME, GPAP_K_TMC_code,
	
	GPAP_K_INDATE,
	GPAP_K_SGU,
	GPAP_K_SGU_code, GPAP_K_SGU_NAME, GPAP_K_SGU_ls_ekr, 
	
	GPAP_K_AP1,
	GPAP_K_AP1_TYPE_LINK, GPAP_K_AP1_doc_link, GPAP_K_AP1_NUMBER, GPAP_K_AP1_DATE, GPAP_K_AP1_CODE, GPAP_K_AP1_NAME,
	GPAP_K_AP1_DATE_PROV, GPAP_K_AP1_SUMMA,
	
	GPAP_K_AP2,
	GPAP_K_AP2_code, GPAP_K_AP2_NAME,
	GPAP_K_AP3)

SELECT G.GP_LINK,
	   G.GPAP_D_LINK_UP,
	   G.GPAP_D_DB_KR,
	   /*GPAP_D_ACCOUNT*/
	   G.GPAP_D_ACC, GPAP_D_name = s.NAME, GPAP_D_CODE = s.CODE, GPAP_D_cSource = s.cSource, GPAP_D_cSinth = s.cSinth, GPAP_D_cAnalit = s.cAnalit,
	   /*GPAP_D_KBK*/
	   G.GPAP_D_KBK, GPAP_D_KBK_type = K.[TYPE], GPAP_D_KBK_code = K.CODE,GPAP_D_KBK_NAME = k.NAME,
	   /*GPAP_D_EKR*/
	   G.GPAP_D_EKR, GP_AP_D_EKR_code = ko.CODE, GP_AP_D_EKR_NAME = ko.NAME, GP_AP_D_EKR_ls_ekr = ko.Is_Ekr,
	   /*GPAP_D_DEP*/
	   G.GPAP_D_DEP, GPAP_D_DEP_CODE = d.CODE, GPAP_D_DEP_NAME = d.NAME, GPAP_D_DEP_FNAME = d.FULL_NAME, GPAP_D_DEP_INN = d.INN, GPAP_D_DEP_KPP = d.KPP,
	   /*GPAP_D_SUB*/
	   G.GPAP_D_SUB, GPAP_D_SUB_code = su.CODE, GPAP_D_SUB_NAME = su.NAME, GPAP_D_SUB_lim = su.LIM, GPAP_D_SUB_obosob = su.OBOSOB, GPAP_D_SUB_okato = su.O_OKATO, GPAP_D_SUB_okpp = su.O_KPP, GPAP_D_SUB_oktmo = su.O_OKTMO,
	   /*GPAP_D_EMP*/
	   G.GPAP_D_EMP,  GPAP_D_EMP_tab = sd.TAB, GPAP_D_EMP_fm = sd.FM, GPAP_D_EMP_im = sd.IM, GPAP_D_EMP_ot = sd.OT, GPAP_D_EMP_FIO = sd.FIO, GPAP_D_EMP_INSUR_NUM = sd.INSUR_NUM, GPAP_D_EMP_INN = sd.INN, GPAP_D_EMP_date_begin = sd.DATE_BEGIN, GPAP_D_EMP_date_end = sd.DATE_END, 
	   /*GPAP_D_NOMEN*/
	   G.GPAP_D_NOMEN, GPAP_D_NOMEN_CODE = n.CODE, GPAP_D_NOMEN_NAME = n.NAME,
	   /*GPAP_D_INV*/
	   G.GPAP_D_INV, GPAP_D_INV_code = i.CODE, GPAP_D_INV_NAME = i.NAME,
	   /*GPAP_D_KAU*/
	   G.GPAP_D_KAU, GPAP_D_KAU_code = ka.CODE, GPAP_D_KAU_name = ka.NAME, GPAP_D_KAU_thema = KA.THEMA,
	   /*GPAP_D_DEP_ACC*/
	   G.GPAP_D_DEP_ACC, GPAP_D_DEP_ACC_code = da.CODE, GPAP_D_DEP_ACC_TYPE = da.[TYPE], 
	   /*GPAP_D_TMC*/
	   G.GPAP_D_TMC, GPAP_D_TMC_NAME = di.NAME, GPAP_D_TMC_code = di.CODE,
	   G.GPAP_D_INDATE, 
	   /*GPAP_D_SGU*/
	   G.GPAP_D_SGU, GPAP_D_SGU_code = KOO.CODE, GPAP_D_SGU_NAME = KOO.NAME, GPAP_D_SGU_ls_ekr = KOO.Is_Ekr, 
	   /*GPAP_D_AP1*/
	   G.GPAP_D_AP1, O.OSNOV_AP1_D_TYPE_LINK, O.OSNOV_AP1_D_doc_link, O.G_PROV_AP1_D_NUMBER, O.G_PROV_AP1_D_DATE, O.S_OBJECTS_AP1_D_CODE, O.S_OBJECTS_AP1_D_NAME,
							O.G_PROV_AP1_D_DATE_PROV, O.G_PROV_AP1_D_SUMMA,
	   /*GPAP_D_AP2*/
	   G.GPAP_D_AP2, GPAP_D_AP2_code = do.CODE, GPAP_D_AP2_NAME = do.NAME,
	   G.GPAP_D_AP3,
	   
	   G.GPAP_K_LINK_UP,
	   G.GPAP_K_DB_KR,
	   /*GPAP_K_ACC*/
	   G.GPAP_K_ACC, GPAP_K_name = s1.NAME, GPAP_K_CODE = s1.CODE, GPAP_K_cSource = s1.cSource, GPAP_K_cSinth = s1.cSinth, GPAP_K_cAnalit = s1.cAnalit,
	   /*GPAP_K_KBK*/
	   G.GPAP_K_KBK, GPAP_K_KBK_type = K1.[TYPE], GPAP_K_KBK_code = K1.CODE,GPAP_K_KBK_NAME = k1.NAME,
	   /*GPAP_K_EKR*/
	   G.GPAP_K_EKR, GPAP_K_EKR_code = ko1.CODE, GPAP_K_EKR_NAME = ko1.NAME, GPAP_K_EKR_ls_ekr = ko1.Is_Ekr,
	   /*GPAP_K_DEP*/
	   G.GPAP_K_DEP, GPAP_K_DEP_CODE = d1.CODE, GPAP_K_DEP_NAME = d1.NAME, GPAP_K_DEP_FNAME = d1.FULL_NAME, GPAP_K_DEP_INN = d1.INN, GPAP_K_DEP_KPP = d1.KPP,
	   /*GPAP_K_SUB*/
	   G.GPAP_K_SUB, GPAP_K_SUB_code = su1.CODE, GPAP_K_SUB_NAME = su1.NAME, GPAP_K_SUB_lim = su1.LIM, GPAP_K_SUB_obosob = su1.OBOSOB, GPAP_K_SUB_okato = su1.O_OKATO, GPAP_K_SUB_okpp = su1.O_KPP, GPAP_K_SUB_oktmo = su1.O_OKTMO,
	   /*GPAP_K_EMP*/
	   G.GPAP_K_EMP,  GPAP_K_EMP_tab = sd1.TAB, GPAP_K_EMP_fm = sd1.FM, GPAP_K_EMP_im = sd1.IM, GPAP_K_EMP_ot = sd1.OT, GPAP_K_EMP_FIO = sd1.FIO, GPAP_K_EMP_INSUR_NUM = sd1.INSUR_NUM, GPAP_K_EMP_INN = sd1.INN, GPAP_K_EMP_date_begin = sd1.DATE_BEGIN, GPAP_K_EMP_date_end = sd1.DATE_END, 
	   /*GPAP_K_NOMEN*/
	   G.GPAP_K_NOMEN, GPAP_K_NOMEN_CODE = n1.CODE, GPAP_K_NOMEN_NAME = n1.NAME,
	   /*GPAP_K_INV*/
	   G.GPAP_K_INV, GPAP_K_INV_code = i1.CODE, GPAP_K_INV_NAME = i1.NAME,
	   /*GPAP_K_KAU*/
	   G.GPAP_K_KAU, GPAP_K_KAU_code = ka1.CODE, GPAP_K_KAU_name = ka1.NAME, GPAP_K_KAU_thema = KA1.THEMA,
	   /*GPAP_K_DEP_ACC*/
	   G.GPAP_K_DEP_ACC, GPAP_K_DEP_ACC_code = da1.CODE, GPAP_K_DEP_ACC_TYPE = da1.[TYPE], 
	   /*GPAP_K_TMC*/
	   G.GPAP_K_TMC, GPAP_K_TMC_NAME = di1.NAME, GPAP_K_TMC_code = di1.CODE,
	   G.GPAP_K_INDATE, 
	   /*GPAP_K_SGU*/
	   G.GPAP_K_SGU, GPAP_K_SGU_code = KOO1.CODE, GPAP_K_SGU_NAME = KOO1.NAME, GPAP_K_SGU_ls_ekr = KOO1.Is_Ekr, 
	   /*GPAP_K_AP1*/
	   G.GPAP_K_AP1, O1.OSNOV_AP1_K_TYPE_LINK, O1.OSNOV_AP1_K_doc_link, O1.G_PROV_AP1_K_NUMBER, O1.G_PROV_AP1_K_DATE, O1.S_OBJECTS_AP1_K_CODE, O1.S_OBJECTS_AP1_K_NAME,
							O1.G_PROV_AP1_K_DATE_PROV, O1.G_PROV_AP1_K_SUMMA , 
	   G.GPAP_K_AP2, GPAP_K_AP2_code = do1.CODE, GPAP_K_AP2_NAME = do1.NAME,
	   G.GPAP_K_AP3
FROM
	#PROV_DOC G
	LEFT JOIN dbo.S_ACCOUNTS		  S ON S.LINK = G.GPAP_D_ACC
	LEFT JOIN dbo.KL_KBK			  K ON  k.link = G.GPAP_D_KBK
	LEFT JOIN dbo.KOSGU				  KO ON KO.LINK = G.GPAP_D_EKR
	LEFT JOIN dbo.departments		  d ON d.link = G.GPAP_D_DEP
	LEFT JOIN dbo.SUBDIV			  su ON su.link =  G.GPAP_D_SUB
	LEFT JOIN dbo.SD_EMPL			  sd ON sd.link =  G.GPAP_D_EMP
	LEFT JOIN dbo.NOMENCLATURE		  N ON n.LINK = G.GPAP_D_NOMEN
	LEFT JOIN dbo.INVENTORY			  I ON   I.link =  G.GPAP_D_INV
	LEFT JOIN dbo.KAU				  KA ON ka.link = G.GPAP_D_KAU
	LEFT JOIN dbo.DEPARTMENT_ACCOUNTS da ON da.link = G.GPAP_D_DEP_ACC
	LEFT JOIN dbo.DICTION			  di ON di.link = G.GPAP_D_TMC
	LEFT JOIN dbo.KOSGU				  KOO ON  KOO.LINK = G.GPAP_D_SGU	
	LEFT JOIN (SELECT oo.link,
					  OSNOV_AP1_D_TYPE_LINK = oo.TYPE_LINK ,
					  OSNOV_AP1_D_doc_link = oo.DOC_LINK,
					  G_PROV_AP1_D_NUMBER = GP.NUMBER ,
					  G_PROV_AP1_D_DATE = GP.[DATE],
					  S_OBJECTS_AP1_D_CODE = s.CODE,
					  S_OBJECTS_AP1_D_NAME = S.NAME,
					  G_PROV_AP1_D_DATE_PROV = GP.DATE_PROV,
					  G_PROV_AP1_D_SUMMA = GP.SUMMA,
					  G_PROV_AP1_D_COMMENT = GP.COMMENT,
					  G_PROV_AP1_D_GET_STORE = GP.GET_STORE,
					  department_accounts_AP1_D_CODE = d_ACc.CODE
			   from dbo.OSNOV oo 
			   LEFT JOIN dbo.G_PROV GP ON GP.LINK = oo.DOC_LINK
			   LEFT JOIN dbo.S_OBJECTS S ON s.link = GP.[OBJECT]	
			   LEFT JOIN department_accounts d_ACc ON d_acc.LINK = GP.ACC  )o ON o.LINK = G.GPAP_D_AP1
	LEFT JOIN dbo.DOP_CLASSIF		  do ON do.LINK = G.GPAP_D_AP1
	
	LEFT JOIN dbo.S_ACCOUNTS		  S1 ON S1.LINK = G.GPAP_K_ACC
	LEFT JOIN dbo.KL_KBK			  K1 ON  k1.link = G.GPAP_K_KBK
	LEFT JOIN dbo.KOSGU				  KO1 ON KO1.LINK = G.GPAP_K_EKR
	LEFT JOIN dbo.departments		  d1 ON d1.link = G.GPAP_K_DEP
	LEFT JOIN dbo.SUBDIV			  su1 ON su1.link =  G.GPAP_K_SUB
	LEFT JOIN dbo.SD_EMPL			  sd1 ON sd1.link =  G.GPAP_K_EMP
	LEFT JOIN dbo.NOMENCLATURE		  N1 ON n1.LINK = G.GPAP_K_NOMEN
	LEFT JOIN dbo.INVENTORY			  I1 ON   I1.link =  G.GPAP_K_INV
	LEFT JOIN dbo.KAU				  KA1 ON ka1.link = G.GPAP_K_KAU
	LEFT JOIN dbo.DEPARTMENT_ACCOUNTS da1 ON da1.link = G.GPAP_K_DEP_ACC
	LEFT JOIN dbo.DICTION			  di1 ON di1.link = G.GPAP_K_TMC
	LEFT JOIN dbo.KOSGU				  KOO1 ON  KOO1.LINK = G.GPAP_K_SGU	
	LEFT JOIN (SELECT oo.link,
					  OSNOV_AP1_K_TYPE_LINK = oo.TYPE_LINK ,
					  OSNOV_AP1_K_doc_link = oo.DOC_LINK,
					  G_PROV_AP1_K_NUMBER = GP.NUMBER ,
					  G_PROV_AP1_K_DATE = GP.[DATE],
					  S_OBJECTS_AP1_K_CODE = s.CODE,
					  S_OBJECTS_AP1_K_NAME = S.NAME,
					  G_PROV_AP1_K_DATE_PROV = GP.DATE_PROV,
					  G_PROV_AP1_K_SUMMA = GP.SUMMA,
					  G_PROV_AP1_K_COMMENT = GP.COMMENT,
					  G_PROV_AP1_K_GET_STORE = GP.GET_STORE,
					  department_accounts_AP1_K_CODE = d_ACc.CODE
			   from dbo.OSNOV oo 
			   LEFT JOIN dbo.G_PROV GP ON GP.LINK = oo.DOC_LINK
			   LEFT JOIN dbo.S_OBJECTS S ON s.link = GP.[OBJECT]	
			   LEFT JOIN department_accounts d_ACc ON d_acc.LINK = GP.ACC  )  o1 ON o1.LINK = G.GPAP_K_AP1
	LEFT JOIN dbo.DOP_CLASSIF		  do1 ON do1.LINK = G.GPAP_K_AP1



--Строка заголовка
CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))

INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

declare @NAME_PROG varchar(254), @VERS_PROG VARCHAR(254)
Select @NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
	@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
from dbo.DICTIONARY_TASK where CODE = 'SALARY'
--------------------------------------------

declare @DEP_LINK int, @lcFNAME VARCHAR(254)/*, @ID INT, @EGRUL varchar(13)*/

--exec dbo.xd_whats_zb @DEP_LINK output
--select @EGRUL = LTRIM(RTRIM(EGRUL)) from DICTIONARY_DEPARTMENT where link = @DEP_LINK 
	
DECLARE @Cur1 CURSOR, @NGROUP int /*Номер пачки*/ , @GPROV_LINK int
set @NGROUP = 0
DECLARE @Cur2 CURSOR , @N_STR int /*Номер строки*/
DECLARE @Cur3 CURSOR , @gp1_link INT
DECLARE @Cur4 CURSOR , @gp2_link int
DECLARE @Cur5 CURSOR , @d_link int, @k_link int

-- ШАПОЧНАЯ ЧАСТЬ ФАЙЛА
-----

--
SET @Cur1 = CURSOR FORWARD_ONLY
FOR select DEP_LINK from #DEP_INFO ORDER BY DEP_LINK
	
OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @DEP_LINK

WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN	
		
	SET @lcFNAME = (SELECT 'ZARPLATA_KS-PROV-C-'+LTRIM(RTRIM(DEP_CODE))+'-INN-'+(CASE when LTRIM(RTRIM(INN)) ='' THEN '000000000000' ELSE LTRIM(RTRIM(INN)) END )+'-KPP-'+(CASE when LTRIM(RTRIM(KPP)) ='' THEN '000000000' ELSE LTRIM(RTRIM(KPP)) END )+'.XML' FROM #DEP_INFO di WHERE DEP_LINK = @DEP_LINK  )


	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
	SELECT @lcFNAME, 'OEM' --Имя файла 
		UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="Windows-1251" ?>' 
		UNION ALL SELECT @lcFNAME, SPACE(0) + '<Exchange version ="1.0">' 
		--UNION ALL SELECT @lcFNAME, SPACE(0) + '<File>' 
 		UNION ALL SELECT @lcFNAME, SPACE(1) + '<FileName>' + RTRIM(LTRIM(@lcFNAME)) + '</FileName>'
		 
	
		
		
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)			 
		 SELECT @lcFNAME, SPACE(1) + '<Org>'
		 UNION ALL SELECT @lcFNAME, SPACE(2) + '<INN>'+RTRIM(LTRIM(COALESCE(INN,'')))+'</INN>'
		 FROM #DEP_INFO WHERE dep_link = @DEP_LINK	
		 UNION ALL SELECT @lcFNAME, SPACE(2) + '<KPP>'+RTRIM(LTRIM(COALESCE(KPP,'')))+'</KPP>'
		 FROM #DEP_INFO WHERE dep_link = @DEP_LINK	
		 UNION ALL SELECT @lcFNAME, SPACE(2) + '<CODE>'+RTRIM(LTRIM(COALESCE(DEP_CODE,'')))+'</CODE>'
		 FROM #DEP_INFO WHERE dep_link = @DEP_LINK	
		 UNION ALL SELECT @lcFNAME, SPACE(2) + '<Name>'+RTRIM(LTRIM(COALESCE(DEP_FNAME,'')))+'</Name>'
		 FROM #DEP_INFO WHERE dep_link = @DEP_LINK	
	
	--
	-- ПЕРЕЧИСЛЕНИЕ ПРОВОДОК
	---
		
		SET @N_STR = 0 
		SET @Cur2 = CURSOR FORWARD_ONLY
		FOR select GP_LINK from #PROV_DOC WHERE GP_DEP = @DEP_LINK GROUP BY GP_LINK 
		
		OPEN @Cur2
		FETCH NEXT FROM @Cur2 INTO @GPROV_LINK

		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN


				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
					SELECT @lcFNAME,					
					/*таблица G_PROV*/
					+ SPACE(3) + '<G_PROV>' + CHAR(10)
					 + SPACE(4) + '<GUID>'+ ltrim(rtrim(P.GP_GUID)) +'</GUID>' + CHAR(10)
					 + SPACE(4) + '<NUMBER>'+ ltrim(rtrim(P.GP_NUMBER)) +'</NUMBER>' + CHAR(10)
					 + SPACE(4) + '<DATE>'+ convert(varchar(10),P.GP_DATE,104) +'</DATE>' + CHAR(10)
					 /*поле OBJECT - линк таблицы S_OBJECTS */
					 + SPACE(4) + '<OBJ_CODE>' + ltrim(rtrim(P.GP_OBJ_CODE)) + '</OBJ_CODE>' + CHAR(10) 
					 + SPACE(4) + '<DATE_PROV>'+ convert(varchar(10),P.GP_DATE_PROV,104) +'</DATE_PROV>' + CHAR(10)
					 + SPACE(4) + '<SUMMA>'+ RTRIM(LTRIM(STR(COALESCE(P.GP_SUMMA,0),18,2))) +'</SUMMA>' + CHAR(10)
					 + SPACE(4) + '<COMMENT>'+ RTRIM(LTRIM(COALESCE(P.GP_COMMENT,''))) +'</COMMENT>' + CHAR(10)
					 + SPACE(4) +  (case when RTRIM(LTRIM(STR(COALESCE(P.GP_GET_STORE,0)))) = 0 then ('<GET_STORE/>' + CHAR(10)) else  ('<GET_STORE>'+   RTRIM(LTRIM(STR(COALESCE(P.GP_GET_STORE,0)))) +'</GET_STORE>' + CHAR(10) ) END)
					 /*Поле DEP - линк таблицы #DEP_INFO*/
					 + SPACE(4) + '<DEP_CODE>' + (select RTRIM(LTRIM(COALESCE(DEP_CODE,''))) FROM #DEP_INFO WHERE DEP_LINK = P.GP_DEP ) + '</DEP_CODE>' + CHAR(10)
					 + SPACE(4) + '<DEP_INN>' + (select RTRIM(LTRIM(COALESCE(INN,''))) FROM #DEP_INFO WHERE DEP_LINK = P.GP_DEP ) + '</DEP_INN>' + CHAR(10)
					 + SPACE(4) + '<DEP_KPP>' + (select RTRIM(LTRIM(COALESCE(KPP,''))) FROM #DEP_INFO WHERE DEP_LINK = P.GP_DEP ) + '</DEP_KPP>' + CHAR(10)
					 /*поле ACC - линк таблицы department_accounts*/
					 + SPACE(4) + '<ACC_CODE>' + ltrim(rtrim(iSnULL(P.GP_ACC_CODE,''))) + '</ACC_CODE>' 
					FROM
						#PROV_DOC P
						--INNER JOIN #G_PROV_AP_FULL GP ON GP.GP_LINK = P.GP_LINK 
					WHERE 
						P.GP_LINK = @GPROV_LINK
					GROUP BY  GP_LINK,GP_GUID, GP_DATE, GP_NUMBER,GP_OBJ_CODE, GP_DATE_PROV , GP_SUMMA , GP_COMMENT , GP_GET_STORE , GP_DEP ,GP_ACC_CODE
					 
					
					
					SET @Cur3 = CURSOR FORWARD_ONLY
					FOR select gp1_link from #PROV_DOC WHERE GP_LINK = @GPROV_LINK  GROUP BY gp1_link
					
					OPEN @Cur3
					FETCH NEXT FROM @Cur3 INTO @GP1_LINK

					WHILE (@@fetch_status <> -1)
					BEGIN
						 INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
								SELECT @lcFNAME,				
								/*Таблица G_PROV1*/
								+ SPACE(4) + '<G_PROV1>' + CHAR(10)						
												
						IF (@@fetch_status <> -2)
						BEGIN
							

						    INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
							SELECT @lcFNAME,				
							--/*Таблица G_PROV1*/
							--+ SPACE(4) + '<G_PROV1>' + CHAR(10)
							/*Поле OPER - линк таблицы G_PROV1*/
									+ SPACE(5) + (case when RTRIM(LTRIM(isnull(P.GP1_NAME_OPER,''))) = '' then ('<OPER/>' + CHAR(10)) else  ('<OPER>' +   RTRIM(LTRIM(isnull(P.GP1_NAME_OPER,''))) + '</OPER>' + CHAR(10) ) END)
									+ SPACE(5) + '<ORDERS>' + RTRIM(LTRIM(ISNULL(P.GP1_ORDERS, 0))) + '</ORDERS>'  + CHAR(10)
									FROM
										#PROV_DOC P
										INNER JOIN #G_PROV_AP_FULL GP ON GP.GP_LINK = P.GP_LINK
									WHERE 
										P.GP1_LINK = @GP1_LINK
									group by p.GP1_ORDERS	, P.GP1_NAME_OPER ,isnull(P.GP1_OPER,0)
								

									SET @Cur4 = CURSOR FORWARD_ONLY
									FOR select gp2_link from #PROV_DOC WHERE GP1_LINK = @GP1_LINK  GROUP BY gp1_link, gp2_link
									
									OPEN @Cur4
									FETCH NEXT FROM @Cur4 INTO @GP2_LINK

									WHILE (@@fetch_status <> -1)
									BEGIN
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
											SELECT @lcFNAME,	
									
									
											/*Таблица G_PROV2*/
											+ SPACE(5) + '<G_PROV2>' + CHAR(10)
			
											IF (@@fetch_status <> -2)
											BEGIN
												INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
												SELECT @lcFNAME,	
									
									
															/*Таблица G_PROV2*/
															---+ SPACE(5) + '<G_PROV2>' + CHAR(10)
																	+ SPACE(6) + '<SUMMA>' + RTRIM(LTRIM(STR(COALESCE(P.[GP2_SUMMA],0),18,2))) + '</SUMMA>'  + CHAR(10)
																	+ SPACE(6) + (case when RTRIM(LTRIM(STR(COALESCE(P.[GP2_QUANTITY],0),18,4))) = '0.0000' then ('<QUANTITY/>' + CHAR(10)) else  ('<QUANTITY>'+   RTRIM(LTRIM(STR(COALESCE(P.[GP2_QUANTITY],0),18,4))) +'</QUANTITY>' + CHAR(10) ) END)
																	+ SPACE(6) + (case when RTRIM(LTRIM(STR(COALESCE(P.GP2_STORNO,'')))) = 0 then ('<STORNO/>' + CHAR(10)) else  ('<STORNO>'+   RTRIM(LTRIM(STR(COALESCE(P.GP2_STORNO,'')))) +'</STORNO>' + CHAR(10) ) END)
															/* ПОЛЕ LINK_SELF - link таблицы G_PROV2*/
																	+ SPACE(6) + '<ORDERS>' + RTRIM(LTRIM(STR(COALESCE(P.GP2_ORDERS,''))))+ '</ORDERS>'  + CHAR(10)
																/*поле ECON_OPER - линк таблицы XOZ_OPER*/
																	+ SPACE(6) + '<EC_OPER_CODE>' + RTRIM(LTRIM(ISNULL(P.GP2_EC_OPER_CODE, ''))) + '</EC_OPER_CODE>'  + CHAR(10)
																	FROM
																		#PROV_DOC P
																		INNER JOIN #G_PROV_AP_FULL GP ON GP.GP_LINK = P.GP_LINK AND GP.GPAP_D_LINK_UP = P.GP2_LINK
																	WHERE 
																		GP.GPAP_D_LINK_UP = @GP2_LINK
																	GROUP BY 	P.GP2_LINK , P.[GP2_SUMMA], P.[GP2_QUANTITY], P.GP2_STORNO, P.GP2_ORDERS , P.GP2_EC_OPER_CODE
																	
																	
																	/*Дебет , кредит*/
																	SET @Cur5 = CURSOR FORWARD_ONLY
																	FOR select GPAP_D_LINK_UP from #G_PROV_AP_FULL where GP_LINK = @GPROV_LINK AND GPAP_D_LINK_UP = @GP2_LINK

																	OPEN @Cur5
																	FETCH NEXT FROM @Cur5 INTO @d_LINK

																	WHILE (@@fetch_status <> -1)
																	BEGIN
																												
																			IF (@@fetch_status <> -2)
																			BEGIN
																				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
																				SELECT @lcFNAME,	

																				/*Дебет*/
																				
				 																+ SPACE(7) + (case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_DB_KR,'')))) = 0 then ('<D_DB_KR/>' + CHAR(10)) else  ('<D_DB_KR>'+   RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_DB_KR,'')))) +'/<D_DB_KR>'+ CHAR(10) ) END)
																				/*поле ACCOUNT - линк таблицы s_accounts*/
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_D_CODE, ''))) = '' then ('<D_ACC/>' + CHAR(10)) else  ('<D_ACC>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_CODE, ''))) +'</D_ACC>'+ CHAR(10) ) END)
																				/*поле KBK - линк таблицы KL_KBK*/
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_D_KBK_code, ''))) = '' then ('<D_KBK/>' + CHAR(10)) else  ('<D_KBK>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_KBK_code, ''))) +'</D_KBK>'+ CHAR(10) ) END)
																				/*поле EKR - линк таблицы KOSGU*/
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_D_EKR_code, ''))) = '' then ('<D_EKR/>' + CHAR(10)) else  ('<D_EKR>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_EKR_code, ''))) +'</D_EKR>'+ CHAR(10) ) END)
																				/*поле DEP - линк таблицы DEPARTMENTS*/
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_d_DEP_CODE, ''))) = '' then ('<D_DEP_CODE/>' + CHAR(10)) else  ('<D_DEP_CODE>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_DEP_CODE, ''))) +'</D_DEP_CODE>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_d_DEP_INN, ''))) = ''  then ('<D_DEP_INN/>' + CHAR(10)) else  ('<D_DEP_INN>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_DEP_INN, ''))) +'</D_DEP_INN>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_d_DEP_KPP, ''))) = '' then ('<D_DEP_KPP/>' + CHAR(10)) else  ('<D_DEP_KPP>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_DEP_KPP, ''))) +'</D_DEP_KPP>'+ CHAR(10) ) END)
																				 /*поле SUB - линк таблицы SUBDIV*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_SUB_code, '')))= '' then ('<D_SUB_code/>' + CHAR(10)) else  ('<D_SUB_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_SUB_code, ''))) +'</D_SUB_code>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_SUB_lim,0),18,2)))= '0.00' then ('<D_SUB_lim/>' + CHAR(10)) else  ('<D_SUB_lim>'+  RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_SUB_lim,0),18,2))) +'</D_SUB_lim>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_SUB_obosob,''))))= 0 then ('<D_SUB_obosob/>' + CHAR(10)) else  ('<D_SUB_obosob>'+ RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_SUB_obosob,'')))) +'</D_SUB_obosob>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_SUB_okato, '')))= '' then ('<D_SUB_okato/>' + CHAR(10)) else  ('<D_SUB_okato>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_SUB_okato, ''))) +'</D_SUB_okato>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_SUB_okpp, '')))= '' then ('<D_SUB_okpp/>' + CHAR(10)) else  ('<D_SUB_okpp>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_SUB_okpp, ''))) +'</D_SUB_okpp>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_SUB_oktmo, '')))= '' then ('<D_SUB_oktmo/>' + CHAR(10)) else  ('<D_SUB_oktmo>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_SUB_oktmo, ''))) +'</D_SUB_oktmo>'+ CHAR(10) ) END)
																				/*поле EMP - линк таблицы SD_EMPL*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_EMP_tab, '')))= '' then ('<D_EMPL_tab/>' + CHAR(10)) else  ('<D_EMPL_tab>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_EMP_tab, ''))) +'</D_EMPL_tab>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_EMP_INSUR_NUM,'')))= '' then ('<D_EMPL_INSUR_NUM/>' + CHAR(10)) else  ('<D_EMPL_INSUR_NUM>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_EMP_INSUR_NUM, ''))) +'</D_EMPL_INSUR_NUM>'+ CHAR(10) ) END)
																				/*поле NOMEN - линк таблицы NOMENCLATURE*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_NOMEN_CODE, '')))= '' then ('<D_NOMEN_CODE/>' + CHAR(10)) else  ('<D_NOMEN_CODE>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_NOMEN_CODE, ''))) +'</D_NOMEN_CODE>'+ CHAR(10) ) END)
																				/*поле INV - линк таблицы INVENTORY*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_INV_code, '')))= '' then ('<D_INVENT_code/>' + CHAR(10)) else  ('<D_INVENT_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_INV_code, ''))) +'</D_INVENT_code>'+ CHAR(10) ) END)
																				/*поле KAU - линк таблицы KAU*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_KAU_code, '')))= '' then ('<D_KAU_code/>' + CHAR(10)) else  ('<D_KAU_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_KAU_code, ''))) +'</D_KAU_code>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_KAU_thema, '')))= '' then ('<D_KAU_thema/>' + CHAR(10)) else  ('<D_KAU_thema>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_KAU_thema, ''))) +'</D_KAU_thema>'+ CHAR(10) ) END)
																				/*поле DEP_ACC - линк таблицы DEPARTMENT_ACCOUNTS*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_DEP_ACC_code, '')))= '' then ('<D_DEP_ACC_code/>' + CHAR(10)) else  ('<D_DEP_ACC_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_DEP_ACC_code, ''))) +'</D_DEP_ACC_code>'+ CHAR(10) ) END)
																				/*поле TMC - линк таблицы DICTION*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_TMC_code,'')))) = 0 then ('<D_TMC_code/>' + CHAR(10)) else  ('<D_TMC_code>'+ RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_TMC_code,'')))) +'</D_TMC_code>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when convert(varchar(10),ISNULL(GP.GPAP_D_INDATE,''),104) = '01.01.1900' then ('<D_INDATE/>' + CHAR(10)) else  ('<D_INDATE>'+ convert(varchar(10),ISNULL(GP.GPAP_D_INDATE,''),104) +'</D_INDATE>'+ CHAR(10) ) END)
																				 /*поле SGU - линк таблицы KOSGU*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_SGU_code, ''))) = 0 then ('<D_SGU_code/>' + CHAR(10)) else  ('<D_SGU_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_SGU_code, ''))) +'</D_SGU_code>'+ CHAR(10) ) END)
																				/*поле AP1 - линк таблицы OSNOV*/
																				/*таблица OSNOV*/
																				--+ SPACE(4) + '<D_AP1_TYPE_LINK>' + case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_AP1_TYPE_LINK,'')))) = 0 THEN '' ELSE RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_AP1_TYPE_LINK,'')))) end  + '</D_AP1_TYPE_LINK>'  + CHAR(10)
																				--+ SPACE(4) + '<D_AP1_doc_link>' +  RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_AP1_doc_link,'')))) + '</D_AP1_doc_link>'  + CHAR(10)
																				/*поле LINK_G_PROV - линк таблицы G_PROV*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_AP1_NUMBER, '')))= '' then ('<D_AP1_NUMBER/>' + CHAR(10)) else  ('<D_AP1_NUMBER>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_AP1_NUMBER, ''))) +'</D_AP1_NUMBER>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when convert(varchar(10),ISNULL(GP.GPAP_D_AP1_DATE,''),104) = '01.01.1900'then ('<D_AP1_DATE/>' + CHAR(10)) else  ('<D_AP1_DATE>'+ convert(varchar(10),ISNULL(GP.GPAP_D_AP1_DATE,''),104) +'</D_AP1_DATE>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_AP1_CODE, ''))) = '' then ('<D_AP1_CODE/>' + CHAR(10)) else  ('<D_AP1_CODE>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_AP1_CODE, ''))) +'</D_AP1_CODE>'+ CHAR(10) ) END)
																				+ SPACE(7) +  (case when convert(varchar(10),ISNULL(GP.GPAP_D_AP1_DATE_PROV,''),104) = '01.01.1900'then ('<D_AP1_DATE_PROV/>' + CHAR(10)) else  ('<D_AP1_DATE_PROV>'+ convert(varchar(10),ISNULL(GP.GPAP_D_AP1_DATE_PROV,''),104) +'</D_AP1_DATE_PROV>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_AP1_SUMMA,0),18,4))) = '0.0000' then ('<D_AP1_SUMMA/>' + CHAR(10)) else  ('<D_AP1_SUMMA>'+ RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_AP1_SUMMA,0),18,4))) +'</D_AP1_SUMMA>'+ CHAR(10) ) END)
																				 /*поле AP2 - линк таблицы DOP_CLASSIF*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_AP2_code, ''))) = '' then ('<D_AP2_code/>' + CHAR(10)) else  ('<D_AP2_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_AP2_code, ''))) +'</D_AP2_code>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_D_AP3, ''))) = 0 then ('<D_AP3/>' + CHAR(10)) else  ('<D_AP3>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_AP3, ''))) +'</D_AP3>'+ CHAR(10) ) END)

	
																			/*Кредит*/

				 																+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_K_DB_KR, ''))) = '' then ('<K_DB_KR/>' + CHAR(10)) else  ('<K_DB_KR>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_DB_KR, ''))) +'</K_DB_KR>'+ CHAR(10) ) END)
																				/*поле ACCOUNT - линк таблицы s_accounts*/
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_K_CODE, ''))) = '' then ('<K_ACC/>' + CHAR(10)) else  ('<K_ACC>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_CODE, ''))) +'</K_ACC>'+ CHAR(10) ) END)
																				/*поле KBK - линк таблицы KL_KBK*/
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_K_KBK_code, ''))) = '' then ('<K_KBK/>' + CHAR(10)) else  ('<K_KBK>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_KBK_code, ''))) +'</K_KBK>'+ CHAR(10) ) END)
																				/*поле EKR - линк таблицы KOSGU*/
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_K_EKR_code, ''))) = '' then ('<K_EKR/>' + CHAR(10)) else  ('<K_EKR>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_EKR_code, ''))) +'</K_EKR>'+ CHAR(10) ) END)
																				 /*поле DEP - линк таблицы DEPARTMENTS*/
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_K_DEP_CODE, ''))) = '' then ('<K_DEP_CODE/>' + CHAR(10)) else  ('<K_DEP_CODE>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_DEP_CODE, ''))) +'</K_DEP_CODE>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_K_DEP_INN, ''))) = ''  then ('<K_DEP_INN/>' + CHAR(10)) else  ('<K_DEP_INN>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_DEP_INN, ''))) +'</K_DEP_INN>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_K_DEP_KPP, ''))) = '' then ('<K_DEP_KPP/>' + CHAR(10)) else  ('<K_DEP_KPP>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_DEP_KPP, ''))) +'</K_DEP_KPP>'+ CHAR(10) ) END)
																				 /*поле SUB - линк таблицы SUBDIV*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_SUB_code, '')))= '' then ('<K_SUB_code/>' + CHAR(10)) else  ('<K_SUB_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_SUB_code, ''))) +'</K_SUB_code>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when  RTRIM(LTRIM(STR(COALESCE(GP.GPAP_k_SUB_lim,0),18,2))) = '0.00' then ('<K_SUB_lim/>' + CHAR(10)) else  ('<K_SUB_lim>'+ RTRIM(LTRIM(STR(COALESCE(GP.GPAP_k_SUB_lim,0),18,2))) +'</K_SUB_lim>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_K_SUB_obosob,'')))) = 0 then ('<K_SUB_obosob/>' + CHAR(10)) else  ('<K_SUB_obosob>'+ RTRIM(LTRIM(STR(COALESCE(GP.GPAP_K_SUB_obosob,'')))) +'</K_SUB_obosob>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_SUB_okato, '')))= '' then ('<K_SUB_okato/>' + CHAR(10)) else  ('<K_SUB_okato>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_SUB_okato, ''))) +'</K_SUB_okato>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_SUB_okpp, '')))= '' then ('<K_SUB_okpp/>' + CHAR(10)) else  ('<K_SUB_okpp>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_SUB_okpp, ''))) +'</K_SUB_okpp>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_SUB_oktmo, '')))= '' then ('<K_SUB_oktmo/>' + CHAR(10)) else  ('<K_SUB_oktmo>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_SUB_oktmo, ''))) +'</K_SUB_oktmo>'+ CHAR(10) ) END)
																				/*поле EMP - линк таблицы SD_EMPL*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_EMP_tab, '')))= '' then ('<K_EMPL_tab/>' + CHAR(10)) else  ('<K_EMPL_tab>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_EMP_tab, ''))) +'</K_EMPL_tab>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_EMP_INSUR_NUM,'')))= '' then ('<K_EMPL_INSUR_NUM/>' + CHAR(10)) else  ('<K_EMPL_INSUR_NUM>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_EMP_INSUR_NUM, ''))) +'</K_EMPL_INSUR_NUM>'+ CHAR(10) ) END)
																				/*поле NOMEN - линк таблицы NOMENCLATURE*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_NOMEN_CODE, '')))= '' then ('<K_NOMEN_CODE/>' + CHAR(10)) else  ('<K_NOMEN_CODE>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_NOMEN_CODE, ''))) +'</K_NOMEN_CODE>'+ CHAR(10) ) END)
																				/*поле INV - линк таблицы INVENTORY*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_INV_code, '')))= '' then ('<K_INVENT_code/>' + CHAR(10)) else  ('<K_INVENT_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_INV_code, ''))) +'</K_INVENT_code>'+ CHAR(10) ) END)
																				/*поле KAU - линк таблицы KAU*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_KAU_code, '')))= '' then ('<K_KAU_code/>' + CHAR(10)) else  ('<K_KAU_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_KAU_code, ''))) +'</K_KAU_code>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_KAU_thema, '')))= '' then ('<K_KAU_thema/>' + CHAR(10)) else  ('<K_KAU_thema>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_KAU_thema, ''))) +'</K_KAU_thema>'+ CHAR(10) ) END)
																				/*поле DEP_ACC - линк таблицы DEPARTMENT_ACCOUNTS*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_DEP_ACC_code, '')))= '' then ('<K_DEP_ACC_code/>' + CHAR(10)) else  ('<K_DEP_ACC_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_DEP_ACC_code, ''))) +'</K_DEP_ACC_code>'+ CHAR(10) ) END)						/*поле TMC - линк таблицы DICTION*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_K_TMC_code,'')))) = 0 then ('<K_TMC_code/>' + CHAR(10)) else  ('<K_TMC_code>'+  RTRIM(LTRIM(STR(COALESCE(GP.GPAP_K_TMC_code,'')))) +'</K_TMC_code>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when convert(varchar(10),ISNULL(GP.GPAP_K_INDATE,''),104) = '01.01.1900' then ('<K_INDATE/>' + CHAR(10)) else  ('<K_INDATE>'+ convert(varchar(10),ISNULL(GP.GPAP_K_INDATE,''),104) +'</K_INDATE>'+ CHAR(10) ) END)
																				 /*поле SGU - линк таблицы KOSGU*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_SGU_code, ''))) = 0 then ('<K_SGU_code/>' + CHAR(10)) else  ('<K_SGU_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_SGU_code, ''))) +'</K_SGU_code>'+ CHAR(10) ) END)
																				/*поле AP1 - линк таблицы OSNOV*/
																				/*таблица OSNOV*/
																				/*поле LINK_G_PROV - линк таблицы G_PROV*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_AP1_NUMBER, '')))= '' then ('<K_AP1_NUMBER/>' + CHAR(10)) else  ('<K_AP1_NUMBER>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_AP1_NUMBER, ''))) +'</K_AP1_NUMBER>'+ CHAR(10) ) END)	
																				+ SPACE(7) + (case when convert(varchar(10),ISNULL(GP.GPAP_K_AP1_DATE,''),104) = '01.01.1900' then ('<K_AP1_DATE/>' + CHAR(10)) else  ('<K_AP1_DATE>'+ convert(varchar(10),ISNULL(GP.GPAP_K_AP1_DATE,''),104) +'</K_AP1_DATE>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_AP1_CODE, ''))) = '' then ('<K_AP1_CODE/>' + CHAR(10)) else  ('<K_AP1_CODE>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_AP1_CODE, ''))) +'</K_AP1_CODE>'+ CHAR(10) ) END)
																				+ SPACE(7) +  (case when convert(varchar(10),ISNULL(GP.GPAP_K_AP1_DATE_PROV,''),104) = '01.01.1900'then ('<K_AP1_DATE_PROV/>' + CHAR(10)) else  ('<K_AP1_DATE_PROV>'+ convert(varchar(10),ISNULL(GP.GPAP_K_AP1_DATE_PROV,''),104) +'</K_AP1_DATE_PROV>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_K_AP1_SUMMA,0),18,4))) = '0.0000' then ('<K_AP1_SUMMA/>' + CHAR(10)) else  ('<K_AP1_SUMMA>'+ RTRIM(LTRIM(STR(COALESCE(GP.GPAP_K_AP1_SUMMA,0),18,4))) +'</K_AP1_SUMMA>'+ CHAR(10) ) END)
																				/*поле AP2 - линк таблицы DOP_CLASSIF*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_AP2_code, ''))) = '' then ('<K_AP2_code/>' + CHAR(10)) else  ('<K_AP2_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_AP2_code, ''))) +'</D_AP2_code>'+ CHAR(10) ) END)
																				
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_AP3, ''))) = 0 then ('<K_AP3/>' + CHAR(10)) else  ('<K_AP3>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_AP3, ''))) +'</K_AP3>'+ CHAR(10) ) END)
																				FROM
																				#PROV_DOC P
																				INNER JOIN #G_PROV_AP_FULL GP ON GP.GP_LINK = P.GP_LINK AND GP.GPAP_D_LINK_UP = P.GP2_LINK
																			WHERE 
																				GP.GPAP_D_LINK_UP = @d_LINK
																		
																							
															--+ SPACE(5) + '</G_PROV2>' + CHAR(10)

																		END
																		
																		FETCH NEXT FROM @Cur5 INTO @d_LINK
																
																	END
																	CLOSE @Cur5
																	DEALLOCATE @Cur5									
								
													

															
										END
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME,
											+ SPACE(5) + '</G_PROV2>' + CHAR(10)
										FETCH NEXT FROM @Cur4 INTO @GP2_LINK
									
									END
									CLOSE @Cur4
									DEALLOCATE @Cur4									
							
								
						END
						INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
						SELECT @lcFNAME,
							+ SPACE(4) + '</G_PROV1>' + CHAR(10)

						FETCH NEXT FROM @Cur3 INTO @GP1_LINK
					
					END
					CLOSE @Cur3
					DEALLOCATE @Cur3
						
					

			END
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME,	
					+ SPACE(3) + '</G_PROV>' + CHAR(10)

			
			set @N_STR = @N_STR + 1 
			FETCH NEXT FROM @Cur2 INTO @GPROV_LINK				
		END

		CLOSE @Cur2
		DEALLOCATE @Cur2
		
		FETCH NEXT FROM @Cur1 INTO @DEP_LINK
	END							

	
	
	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
	SELECT @lcFNAME, SPACE(1) + '</Org>'	
	
	
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, '</Exchange>'

	
END

CLOSE @Cur1
DEALLOCATE @Cur1




SET NOCOUNT OFF

select * from #OUTPUT order by [ID]
--select OUT_TEXT from #OUTPUT order by [ID]







GO


GRANT EXECUTE ON dbo.[SS_PROV_EXPORT] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SZV_K_PACHKA_PROVERKA]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SZV_K_PACHKA_PROVERKA]

GO

CREATE   PROCEDURE dbo.SZV_K_PACHKA_PROVERKA (@result int output, @link int, @mode tinyint)
AS

if @mode = 0 
BEGIN
	Select @result = proverka from dbo.SZV_K_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.SZV_K_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_szv_K_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_szv_k_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_szv_k_svedenia SV
	where	
		SV.link = @link
		and exists (select * FROM dbo.sa_szv_k_sved_WORK_DEP w INNER join dbo.SZV_k_stazh S1 ON  S1.link_UP = w.link1  inner join dbo.SZV_K_stazh S2 on  w.link1 = S2.link_UP and S1.link_UP = S2.link_UP and  S1.link <> S2.link
		where W.link = SV.link1 and (S1.date1 between S2.date1 and S2.date2 or S1.date2 between S2.date1 and S2.date2)) 

	UNION
	Select pachka, orders, msg = 'Пачка ' + convert(varchar(10),pachka) + ' стр. ' + convert(varchar(10),orders) + ' Ошибка:' + 
		+ ' Не заполнены сведения о периоде трудовой или иной общественно-полезной деятельности!'
	from dbo.sa_szv_k_svedenia SV
	where	
		SV.link = @link
		and not exists (select * FROM dbo.sa_szv_k_sved_WORK_DEP w where W.link = SV.link1 ) 

/*	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_szv_k_svedenia S inner join  dbo.szv_k_pachka p on p.link = s.link
	WHERE s.link = @LINK AND s.sum_doh = 0 AND s.INSUR = 0 AND s.GAIN = 0 AND s.DOP = 0 and s.sum_uplata_dolga_str = 0 and s.sum_uplata_dolga_nak = 0
	and p.vid_kor != 3
	AND NOT EXISTS (SELECT * FROM dbo.SZV_k_STAZH ST WHERE ST.LINK_UP = S.LINK1)
	Order by pachka, orders
*/
	if @@ROWCOUNT = 0 
	BEGIN
		exec dbo.SZV_k_NUMERATOR @link
		update dbo.szv_k_pachka set proverka = 1 where link = @link
		set @result = 1
	END

END

RETURN 0






GO


GRANT EXECUTE ON dbo.[SZV_K_PACHKA_PROVERKA] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[XK_NASTR_S_ACCOUNTS_KOSGU]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[XK_NASTR_S_ACCOUNTS_KOSGU]

GO
CREATE PROCEDURE dbo.XK_NASTR_S_ACCOUNTS_KOSGU
	@intLINK_ACCT	INT = NULL,
	@strNASTR_MODE	VARCHAR (30) = 'XK_CONV_NASTR_SA_157N_SGU'
AS
BEGIN

	DECLARE @CURS CURSOR,
		@LINK_SA	INT,
		@LINK_SGU	INT,
		@NAME VARCHAR (254),
		@intERR	INT

	SET @CURS = CURSOR FOR
		SELECT SA.LINK,
			KOSGU.LINK,
			CONVERT (VARCHAR (254), SA_K.[NAME])
		FROM dbo.S_ACCOUNTS_NASTR_KOSGU SA_K
		INNER JOIN dbo.S_ACCOUNTS SA ON (SA.cSINTH = SA_K.SINTH
			AND SA.cANALIT = SA_K.ANALITH)
		INNER JOIN dbo.KOSGU ON (KOSGU.CODE = SA_K.SGU)
		WHERE @intLINK_ACCT IS NULL
			OR SA.LINK = @intLINK_ACCT

	OPEN @CURS
	FETCH FROM @CURS
		INTO @LINK_SA,
			@LINK_SGU,
			@NAME

	WHILE @@FETCH_STATUS = 0 
	BEGIN
		IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_SGU WHERE ACCOUNT = @LINK_SA
						AND LINK_SGU = @LINK_SGU)
			UPDATE dbo.S_ACCOUNTS_SGU SET COMMENT = @NAME
			WHERE ACCOUNT = @LINK_SA
				AND LINK_SGU = @LINK_SGU 
		ELSE
			INSERT INTO dbo.S_ACCOUNTS_SGU (ACCOUNT, LINK_SGU, COMMENT)
			VALUES (@LINK_SA, @LINK_SGU, @NAME)

		IF @@ERROR <> 0
			RETURN @@ERROR

		FETCH NEXT FROM @CURS
			INTO @LINK_SA,
				@LINK_SGU,
				@NAME
	END

	CLOSE @CURS
	DEALLOCATE @CURS

	SET @strNASTR_MODE = LTRIM (ISNULL (@strNASTR_MODE, ''))
	IF LEN (@strNASTR_MODE) > 0
		EXEC dbo.X_SET_OPTION @strNASTR_MODE, 0, '1'

	RETURN 0
END



GO


GRANT EXECUTE ON dbo.[XK_NASTR_S_ACCOUNTS_KOSGU] TO PUBLIC

GO


--Расширенные свойства--


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SZV_K_SVEDENIA_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZV_K_SVEDENIA_SAVE]

GO

CREATE   PROCEDURE dbo.SA_SZV_K_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,
	*/
	@ter_usl VARCHAR(10) = '',
	@ter_koef NUMERIC(18,2) = 0,
	@all_stazh_y INT  = 0, 
	@all_stazh_m INT  = 0,
	@all_stazh_d INT  = 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_SZV_K_SVEDENIA'

IF @LINK is null OR @LINK = 0
	BEGIN
		INSERT INTO dbo.SZV_K_SVEDENIA WITH (ROWLOCK) (link_up, pachka, orders, link_pers, dper_vn_m, dper_vn_d, dper_oz_m, dper_oz_d,terr_usl,terr_koef,all_stazh_y,all_stazh_m,all_stazh_d) 
			VALUES (@link_up, @pachka, @orders, @link_pers, @dper_vn_m, @dper_vn_d, @dper_oz_m, @dper_oz_d,ltrim(rtrim(@ter_usl)),@ter_koef,@all_stazh_y,@all_stazh_m,@all_stazh_d)

		SELECT @varKSERROR = @@ERROR, @LINK = @@IDENTITY
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
ELSE
	BEGIN

		UPDATE dbo.SZV_K_SVEDENIA WITH (ROWLOCK) 
		SET 	link_up =@link_up, pachka = @pachka, orders =@orders, link_pers =@link_pers, dper_vn_m = @dper_vn_m, dper_vn_d =@dper_vn_d, dper_oz_m =@dper_oz_m, 
			dper_oz_d =@dper_oz_d,terr_usl= ltrim(rtrim(@ter_usl)),terr_koef = @ter_koef,all_stazh_y = @all_stazh_y,all_stazh_m = @all_stazh_m,all_stazh_d = @all_stazh_d
		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_SZV_K_SVEDENIA where link = @LINK
EXECUTE WF_GENERATEEVENT 'Сохранение расчета', @varKSEventText, @varKSsoLink, 'SA_SZV_K_SVEDENIA',@LINK
WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN

RETURN 0




GO


GRANT EXECUTE ON dbo.[SA_SZV_K_SVEDENIA_SAVE] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SALARY_FILL_DED_ESN_VKR]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SALARY_FILL_DED_ESN_VKR]

GO

CREATE PROCEDURE [dbo].SALARY_FILL_DED_ESN_VKR
--Начисление страховых взносов
@RefPay int, 
@LinkVKR int,
@LINK_EKR INT, 
@linkPers int, 
@Month int, 
@Year int, 
@FlagMS  tinyint,
@FlagShow int = 0,
@DEP_LINK INT  = NULL
AS

SET NOCOUNT ON

DECLARE @DATE1 datetime, 
		  @linkFace int,
		  @LINK_213EKR INT,
		  @LINK_211EKR INT,
		  @TARIF TINYINT,
		  @SHOW_212 TINYINT,
		  @LINK_EKR_ADD INT
		
		  
SET @TARIF = ISNULL((SELECT TOP 1 ENVD FROM dbo.SAL_SFIN WHERE LINK = @LinkVKR),0) + 1	
		  
SET @LINK_211EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '211')
SET @LINK_EKR_ADD = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '212')
SET @LINK_213EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '213')
SET @FlagMS = 1
SET @SHOW_212 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_3')

IF @SHOW_212 = 1 OR @LINK_EKR <> @LINK_211EKR
	SET @LINK_EKR_ADD = @LINK_EKR
	
DECLARE @ESN_OPTIONS_7 INT --Начислять доп. тариф только для полной ставки
--При включенной опции программа будет начислять страховые взносы по доп. тарифам только если у сотрудника по основной должности полная ставка. 
--Если ставка не полная, то доп. тариф не начисляется.
SET @ESN_OPTIONS_7 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_7')

DECLARE @ESN_OPTIONS_8 INT --Начислять доп. тариф внутренним совместителям
--При включенной опции программа будет начислять страховые взносы по доп. тарифам на доходы внутренних совместителей.
SET @ESN_OPTIONS_8 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_8')

DECLARE @DATE_BEG DATETIME
SET @DATE_BEG = dbo.convertDMY2Date(1,@Month,@Year)
SET @DATE1 = dbo.DateEndOfMonth(@DATE_BEG)

DECLARE @DATE_YEAR_BEG DATETIME
SET @DATE_YEAR_BEG = dbo.convertDMY2Date(1,1,@Year)

SELECT @linkFace = @linkPers 

DECLARE @T1 TABLE
([NUM]			[int],
 [SUMMA]		[numeric](19,2),
 [SUMMA_VKR]		[numeric](19,2),
 [SUMMA_M]		[numeric](19,2),
 [SUMMA_M_VKR]		[numeric](19,2))


IF @DEP_LINK IS NULL
	exec dbo.xd_whats_zb @DEP_LINK output

declare @linkEmpl int,  @Pred_Mesto_Rab numeric(15,2), 	  @FlagD int

Set @linkEmpl = (Select top 1 link from dbo.empl where PERS_LINK = @linkPers)

---------------------------------------------------
DECLARE @item_move TABLE (LINK INT, EMPL_LINK INT, STAFF_LINK INT, DATE_BEGIN DATETIME, DATE_END DATETIME, NUM_STAKE NUMERIC(5,3), active TINYINT, NEW_FACE TINYINT, [STATUS] TINYINT)
INSERT INTO @item_move (LINK, EMPL_LINK, STAFF_LINK, DATE_BEGIN, DATE_END, NUM_STAKE, active, NEW_FACE, [STATUS])
Select 
	P1.LINK, P1.EMPL_LINK, P1.STAFF_LINK, P1.DATE_BEGIN, P1.DATE_END, P1.NUM_STAKE, P1.active, P1.NEW_FACE, P1.[STATUS]
from 
	dbo.empl e INNER JOIN dbo.item_move P1 ON P1.EMPL_LINK = e.link
WHERE
	E.DEP_LINK = @DEP_LINK AND E.PERS_LINK	= @linkPers
---------------------------------------------------

--Информация о размере ставок по каждому табельному номеру
DECLARE @NUM_STAKE TABLE (LINK_EMPL INT, NUM_STAKE NUMERIC(18,4), DATE_BEG DATETIME, DATE_END DATETIME)
INSERT INTO @NUM_STAKE (LINK_EMPL, NUM_STAKE, DATE_BEG, DATE_END)
SELECT DISTINCT
	EMPL_LINK, NUM_STAKE, DATE_BEGIN, DATE_END 
FROM @item_move
WHERE active = 1 AND NEW_FACE <> 3 AND @DATE1 BETWEEN DATE_BEGIN AND DATE_END

if @FlagShow = 1 
	select 'Сотрудник:  '+ LTRIM(RTRIM(P.FM)) + ' ' + SUBSTRING(LTRIM(RTRIM(P.IM)),1,1) + '.' + SUBSTRING(LTRIM(RTRIM(P.OT)),1,1)
		+  ', месяц ' + convert(varchar(2),@Month)+ ', год ' +convert(varchar(4),@Year) as [Исходные данные],
		[Отчисление] = (select rtrim(name) from pays where link =@RefPay)  FROM dbo.PERSON P where link = @linkFace


DECLARE @NASTR TABLE
([LINK_MINROT] 	[int],
 [REF_PAY]			[int],
 [CODE]				[varchar](5),
 [NAME]				[varchar](254),
 [PREDEL]			[numeric](19, 2))

INSERT INTO @NASTR([LINK_MINROT],[REF_PAY],[CODE],[NAME],[PREDEL])
SELECT [LINK_MINROT],[REF_PAY],[CODE],[NAME],[PREDEL] FROM dbo.Salary_deduct_esn(@DATE1)

SELECT @Pred_Mesto_Rab = 0, @FlagD = 0

IF dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_6 ') = 1
BEGIN
	IF YEAR(dbo.kd_DateBeginWork(@linkEmpl,null)) = @Year
	BEGIN
		SET @Pred_Mesto_Rab = (SELECT ISNULL(SUM(SUMMA_DED),0) FROM dbo.SD_EMPL_PREV_DED WHERE LINK_EMPL = @linkEmpl and LINK_DED in (select REF_PAY from @NASTR))
		IF @Pred_Mesto_Rab IS null or @Pred_Mesto_Rab < 0
			SET @Pred_Mesto_Rab = 0
		SET @FlagD = 1
		
		IF  @FlagShow = 1 
			SELECT 'Совокупный доход: '+ rtrim(isnull(convert(varchar(100),(select sum(summa_TYP_INCOMS) from dbo.SD_EMPL_PREV_DOHOD where link_empl =@linkEmpl)),'0')) + ' , вычеты: '+
			 rtrim( isnull( convert(varchar(100),(select sum(summa_ded) from dbo.SD_EMPL_PREV_DED where link_empl =@linkEmpl and LINK_DED in (select REF_PAY from @NASTR) )),'0'))  as 'Данные с предыдущего места работы'
	END
END	

---Учитываются доходы по договорам ГПХ в данной организации, чтобы правильно применить регрессионную шкалу---
DECLARE @SUM_DGH numeric(15,2)
SET @SUM_DGH = 
	ISNULL(
	(
	SELECT SUM(GT.SUMMA_BASE)
	FROM dbo.DOCUMENTS_DGH G INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
	WHERE FLAG_JC = 1
			AND YEAR(G.[DATE]) = @Year
			AND MONTH(G.[DATE]) <= @Month
			AND G.LINK_DEP = @DEP_LINK
			AND GT.LINK_PAY = @RefPay
			AND GT.PERS_LINK = @linkFace
	),0)

IF @SUM_DGH <> 0 AND @FlagShow = 1 
	SELECT 'Совокупный доход: '+ rtrim(isnull(convert(varchar(100),@SUM_DGH),'0')) as 'Доход по договорам ГПХ'


CREATE TABLE #PERIODY (LINK_EMPL INT, LINK_PERSON INT, TAB VARCHAR(10), NUM_STAKE NUMERIC(18,4), POSTNAME VARCHAR(50), st_date1 datetime, st_date2 datetime, im_date1 datetime, im_date2 datetime, [COD_SPO_USL_TRUD] int)

---------------------------------------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC IN (10,11) AND LINK = @RefPay)
BEGIN

	--sa_item_move
	--	
	DECLARE @sa_item_move TABLE (EMPL_LINK INT, STAFF_LINK INT, DATE_BEGIN DATETIME, DATE_END3 DATETIME, NUM_STAKE NUMERIC(5,3), [STATUS] TINYINT )

	INSERT INTO @sa_item_move (EMPL_LINK, STAFF_LINK, DATE_BEGIN, DATE_END3, NUM_STAKE, [STATUS])
	Select 
		P1.EMPL_LINK, P1.STAFF_LINK, P1.DATE_BEGIN, date_end3 = min(P2.date_begin) - 1, P1.NUM_STAKE, P1.[STATUS]
	from 
		dbo.empl e
		INNER JOIN @item_move P1 ON P1.EMPL_LINK = e.link
		INNER JOIN @item_move P2 on P1.EMPL_LINK = P2.EMPL_LINK
	where
		E.PERS_LINK	= @linkPers 
		AND P1.active = 1 AND P2.active = 1 AND P1.NEW_FACE <> 3 AND P2.NEW_FACE <> 3
		AND P1.[date_begin] < P2.[date_begin] 
	group by 
		P1.EMPL_LINK, P1.STAFF_LINK, P1.DATE_BEGIN, P1.NUM_STAKE, P1.[STATUS]

	INSERT INTO @sa_item_move (EMPL_LINK, STAFF_LINK, DATE_BEGIN, DATE_END3, NUM_STAKE, [STATUS])
	Select 
		P3.EMPL_LINK, P3.STAFF_LINK, P3.DATE_BEGIN, date_end3 = '99991231', P3.NUM_STAKE, P3.[STATUS]
	from
		dbo.empl e 
		INNER JOIN @item_move P3 ON P3.EMPL_LINK = e.link
	where
		E.PERS_LINK	= @linkPers  
		AND
		P3.active = 1 AND P3.NEW_FACE <> 3
		AND
		NOT EXISTS (
					Select *
					from 
						@item_move P1 inner join @item_move P2 on P1.EMPL_LINK = P2.EMPL_LINK
					where
						P1.LINK = P3.link
						AND P1.active = 1 and P2.active = 1 AND P1.NEW_FACE <> 3 AND P2.NEW_FACE <> 3
						and P1.[date_begin] < P2.[date_begin] 
					)
	-----------------------------------------------------------------------------------------------------

	CREATE TABLE #ADD_TYPE (
		[type] INT IDENTITY(1,1),
		[TERR_USL_TRUD] int NULL ,
		[TERR_RK] numeric(3, 2) NULL ,
		[OSOB_USL_TRUD] int NULL ,
		[COD_POS_SPISOK] int NULL ,
		[COD_POS_SPISOK2] int NULL ,
		[USL_DOSROCH_PENS] int NULL ,
		[STAVKA_PED_MED] numeric(3, 2) NULL,
		[COD_SPO_USL_TRUD] int NULL
	)

	INSERT INTO #ADD_TYPE 
	SELECT DISTINCT ISNULL(TERR_USL_TRUD,0), ISNULL(TERR_RK,0), ISNULL(OSOB_USL_TRUD,0), ISNULL(COD_POS_SPISOK,0), ISNULL(COD_POS_SPISOK2,0), ISNULL(USL_DOSROCH_PENS,0), ISNULL(STAVKA_PED_MED,0), ISNULL([COD_SPO_USL_TRUD],0)
	FROM dbo.staff
	WHERE ISNULL(COD_POS_SPISOK,0) <> 0 OR ISNULL(COD_POS_SPISOK2,0) <> 0

	INSERT INTO 
		#PERIODY (LINK_EMPL, LINK_PERSON, TAB, NUM_STAKE, POSTNAME, st_date1, st_date2, im_date1, im_date2, [COD_SPO_USL_TRUD])
	SELECT DISTINCT
		E.LINK,
		E.PERS_LINK,
		TAB,
		IM.NUM_STAKE,
		LEFT(PT.NAME,50),
		st_date1 = dbo.DateBeginOfMonth((case when st.DATE_BEGIN >= @DATE_YEAR_BEG then st.DATE_BEGIN else @DATE_YEAR_BEG end)),
		st_date2 = dbo.DateEndOfMonth((case when coalesce(st.DATE_END,@DATE1) <= @DATE1 then coalesce(st.DATE_END,@DATE1) else @DATE1 end)	),
		im_date1 = dbo.DateBeginOfMonth((case when im.DATE_BEGIN >= @DATE_YEAR_BEG then im.DATE_BEGIN else @DATE_YEAR_BEG end)),
		im_date2 = dbo.DateEndOfMonth( 
							CASE WHEN COALESCE(U.DIS_DATE,'20990101') <= (case when ISNULL(ISNULL(U.DIS_DATE,im.DATE_END3),@DATE1) <= @DATE1 then ISNULL(ISNULL(U.DIS_DATE,im.DATE_END3),@DATE1) else @DATE1 end)
								THEN COALESCE(U.DIS_DATE,'20990101')
								ELSE (case when ISNULL(ISNULL(U.DIS_DATE,im.DATE_END3),@DATE1) <= @DATE1 then ISNULL(ISNULL(U.DIS_DATE,im.DATE_END3),@DATE1) else @DATE1 end)
							END	),
		T.[COD_SPO_USL_TRUD]							
	FROM 
		dbo.empl e
		INNER JOIN @sa_item_move im ON im.EMPL_LINK = e.link
		inner join dbo.staff_head sh on sh.link = STAFF_LINK
		inner join dbo.staff st on st.link_up = sh.link
		INNER JOIN dbo.POST PT ON PT.LINK = st.post_link
		INNER join #ADD_TYPE T on ISNULL(st.TERR_USL_TRUD,0) = ISNULL(T.TERR_USL_TRUD,0) 
								AND ISNULL(st.TERR_RK,0) = ISNULL(T.TERR_RK,0) 
								AND ISNULL(st.OSOB_USL_TRUD,0) = ISNULL(T.OSOB_USL_TRUD,0) 
								AND ISNULL(st.COD_POS_SPISOK,0) = ISNULL(T.COD_POS_SPISOK,0) 
								AND ISNULL(st.COD_POS_SPISOK2,0) = ISNULL(T.COD_POS_SPISOK2,0) 
								AND ISNULL(st.USL_DOSROCH_PENS,0) = ISNULL(T.USL_DOSROCH_PENS,0) 
								AND ISNULL(st.STAVKA_PED_MED,0) = ISNULL(T.STAVKA_PED_MED,0)
								AND ISNULL(st.COD_SPO_USL_TRUD,0) = ISNULL(T.COD_SPO_USL_TRUD,0)
		LEFT JOIN dbo.ITEM_DIS_FACE U on E.link = U.empl_link AND U.ACTIVE=1	
	where
		E.PERS_LINK	= @linkPers
		and  
		im.DATE_BEGIN <= @DATE1 and im.DATE_END3 >= @DATE_YEAR_BEG
		AND
		IM.[STATUS] <> 2 --Вредность у внутренних совместителей не учитываем (НЕ ДОЛЖНО БЫТЬ)
		AND
		st.DATE_BEGIN <= @DATE1 and st.DATE_END >= @DATE_YEAR_BEG
		AND
		T.[TYPE] IS NOT NULL
		AND
		(
			ISNULL(T.[COD_POS_SPISOK],0) <> 0 AND EXISTS (SELECT * FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 AND LINK = @RefPay)
			OR
			ISNULL(T.[COD_POS_SPISOK2],0) <> 0 AND EXISTS (SELECT * FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 AND LINK = @RefPay)	
		)	

	if @FlagShow = 1 
		SELECT DISTINCT TAB AS [Таб_номер],  LEFT(dbo.ku_GetEmplSubdivName(LINK_EMPL,@DATE1),50) AS [Отдел], POSTNAME AS [Должность], CONVERT(VARCHAR(10), ST_DATE1, 104) AS 'Нач_пер_с_вредн_ШР', CONVERT(VARCHAR(10),ST_DATE2,104) AS 'Оконч_пер_с_вредн_ШР' FROM #PERIODY
			
	if @FlagShow = 1 
		SELECT DISTINCT TAB AS [Таб_номер],  NUM_STAKE AS [Кол-во ставок], LEFT(dbo.ku_GetEmplSubdivName(LINK_EMPL,@DATE1),50) AS [Отдел], POSTNAME AS [Должность], CONVERT(VARCHAR(10), IM_DATE1, 104) AS 'Нач_пер_с_вредн_должность', CONVERT(VARCHAR(10),IM_DATE2,104) AS 'Оконч_пер_с_вредн_должность', CASE WHEN NUM_STAKE < 1 THEN 'Доп. тариф не начисляется, т.к. не полный день' ELSE '' END AS [Примечание]
		FROM #PERIODY
	
	INSERT INTO @T1 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR])
	SELECT M.NUM,SUM(SJ.SUMMA) AS SUMMA, 			
			 [SUMMA_VKR]	= SUM(CASE WHEN SJ.LINK_VKR = @LinkVKR AND SJ.LINK_EKR IN (@LINK_EKR,@LINK_EKR_ADD) THEN SJ.SUMMA ELSE 0 END),
			 [SUMMA_M] 		= SUM(CASE WHEN MONTH(SJ.PERIOD_BEGIN) = M.NUM THEN SJ.SUMMA ELSE 0 END),
			 [SUMMA_M_VKR] = SUM(CASE WHEN (MONTH(SJ.PERIOD_BEGIN) = M.NUM) AND (SJ.LINK_VKR = @LinkVKR AND SJ.LINK_EKR  IN (@LINK_EKR,@LINK_EKR_ADD)) THEN SJ.SUMMA ELSE 0 END)
	FROM 
		dbo.MONTHS M
		INNER JOIN dbo.EMPL E ON 1=1
		INNER JOIN dbo.CALCULATE_JURNAL SJ ON SJ.LINK_EMPL = E.LINK
		INNER JOIN dbo.TAX_REF TR ON TR.LINK_PAYS =  SJ.LINK_PAYS
	WHERE 
		E.PERS_LINK = @linkFace
		AND (M.NUM <= @Month) 
		AND (MONTH(SJ.PERIOD_BEGIN) <= M.NUM) 
		AND (YEAR(SJ.PERIOD_BEGIN) = @Year)
		AND TR.LINK_TAX = @RefPay 
		AND EXISTS (SELECT * FROM #PERIODY P WHERE 
												(@ESN_OPTIONS_7 = 0 OR @ESN_OPTIONS_7 = 1 AND P.NUM_STAKE >=1)
												AND 
												(
													@ESN_OPTIONS_8 = 0 AND P.LINK_EMPL = SJ.LINK_EMPL 
													OR
													@ESN_OPTIONS_8 = 1 AND P.LINK_PERSON = E.PERS_LINK
												)	
												AND SJ.PERIOD_BEGIN <= P.ST_DATE2 
												AND SJ.PERIOD_END >= P.ST_DATE1 
												AND SJ.PERIOD_BEGIN <= P.IM_DATE2 
												AND SJ.PERIOD_END >= P.IM_DATE1)
	GROUP BY  M.NUM	

	
END
---------------------------------------------------------------------------------------------------------------
ELSE
	INSERT INTO @T1 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR])
	SELECT M.NUM,SUM(SJ.SUMMA) AS SUMMA, 			
			 [SUMMA_VKR]	= SUM(CASE WHEN SJ.LINK_VKR = @LinkVKR AND SJ.LINK_EKR IN (@LINK_EKR,@LINK_EKR_ADD) THEN SJ.SUMMA ELSE 0 END),
			 [SUMMA_M] 		= SUM(CASE WHEN MONTH(SJ.PERIOD_BEGIN) = M.NUM THEN SJ.SUMMA ELSE 0 END),
			 [SUMMA_M_VKR] = SUM(CASE WHEN (MONTH(SJ.PERIOD_BEGIN) = M.NUM) AND (SJ.LINK_VKR = @LinkVKR AND SJ.LINK_EKR  IN (@LINK_EKR,@LINK_EKR_ADD)) THEN SJ.SUMMA ELSE 0 END)
	FROM 
		dbo.MONTHS M
		INNER JOIN dbo.CALCULATE_JURNAL SJ ON 1=1 
		INNER JOIN dbo.TAX_REF TR ON TR.LINK_PAYS =  SJ.LINK_PAYS
		INNER JOIN dbo.EMPL E ON SJ.LINK_EMPL = E.LINK
	WHERE 
		(TR.LINK_TAX = @RefPay) 
		AND (E.PERS_LINK = @linkFace) 
		AND (MONTH(SJ.PERIOD_BEGIN) <= M.NUM) AND (M.NUM <= @Month) AND (YEAR(SJ.PERIOD_BEGIN)=@Year)
		AND sj.LINK_DEP = @DEP_LINK
	GROUP BY  M.NUM


if @FlagShow = 1 
	SELECT [num] as [Месяц], [summa] as [Сумма с нач года],summa_vkr as [Сумма с нач года по ВКР/ЕКР], summa_m as [Сумма за месяц], 
	summa_m_vkr as [Сумма за месяц по ВКР/ЕКР]  FROM @T1

--Если суммы, которые раньше были в базе убрали из базы, теперь базовой суммы вообще нет
IF NOT EXISTS(SELECT * FROM @T1)
	INSERT INTO @T1 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR])
	VALUES(@Month, 0, 0, 0, 0)

DECLARE @Temp1_1 TABLE
([NUM]			[int],
 [LINK_PAYS]	[int],
 [MP]				[numeric](19,2),
 [MP_M]			[numeric](19,2),
 [MP_M_VKR]		[numeric](19,2))

--------------------------------------------------
CREATE TABLE #DICTIONARY_TYP_INCOMS (LINK INT)
INSERT INTO #DICTIONARY_TYP_INCOMS (LINK)
SELECT LINK FROM dbo.DICTIONARY_TYP_INCOMS WHERE EXISTS (SELECT * FROM @NASTR WHERE REF_PAY = REF_DEDUCT)
CREATE INDEX #DICTIONARY_TYP_INCOMS_IDX1 ON #DICTIONARY_TYP_INCOMS (LINK)

-------------------------------------------------
CREATE TABLE #PAYS (LINK INT)
INSERT INTO #PAYS (LINK)
SELECT P.LINK FROM dbo.PAYS P INNER JOIN #DICTIONARY_TYP_INCOMS I ON I.LINK = P.LINK_INC
CREATE INDEX #PAYS_IDX1 ON #PAYS (LINK)


--------------------------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC IN (10,11) AND LINK = @RefPay)
	
	INSERT INTO @Temp1_1 ([NUM],[LINK_PAYS],[MP],[MP_M],[MP_M_VKR])
	SELECT M.NUM,
			 [LINK_PAYS]= (SELECT LINK_INC  from pays where link = sj.LINK_PAYS),
			 [MP] 		= SUM(CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end), 
			 [MP_M] 		= SUM(CASE WHEN month(SJ.PERIOD_BEGIN)=m.num then (CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end) else 0 end),
			 [MP_M_VKR] = SUM(CASE WHEN ( month(SJ.PERIOD_BEGIN)=m.num)AND(sj.link_vkr = @LinkVKR AND SJ.LINK_EKR  IN (@LINK_EKR,@LINK_EKR_ADD)) 
								THEN (CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end) else 0 end)
	FROM 
		dbo.MONTHS M 
		INNER JOIN dbo.S_J_C_Short SJ ON 1=1
		INNER JOIN #PAYS P ON P.LINK = SJ.LINK_PAYS
		INNER JOIN dbo.TAX_REF TR ON TR.LINK_PAYS =  SJ.LINK_PAYS
	WHERE 
		TR.LINK_TAX = @RefPay 
		AND (SJ.LINK_FACE = @linkFace)
		AND YEAR(SJ.PERIOD_BEGIN)=@Year AND M.NUM <= @Month 
		AND sj.LINK_DEP = @DEP_LINK
		AND EXISTS (SELECT * FROM #PERIODY P WHERE 
									(
										@ESN_OPTIONS_8 = 0 AND P.LINK_EMPL = SJ.LINK_EMPL
										OR
										@ESN_OPTIONS_8 = 1 AND P.LINK_PERSON = SJ.LINK_FACE
									)									
									AND SJ.PERIOD_BEGIN <= P.ST_DATE2 AND SJ.PERIOD_END >= P.ST_DATE1)		
		AND EXISTS (SELECT * FROM #PERIODY P WHERE 
									(
										@ESN_OPTIONS_8 = 0 AND P.LINK_EMPL = SJ.LINK_EMPL
										OR
										@ESN_OPTIONS_8 = 1 AND P.LINK_PERSON = SJ.LINK_FACE
									)	
									AND (@ESN_OPTIONS_7 = 0 OR @ESN_OPTIONS_7 = 1 AND P.NUM_STAKE >=1)
									AND SJ.PERIOD_BEGIN <= P.IM_DATE2 AND SJ.PERIOD_END >= P.IM_DATE1)		
	GROUP BY 
		M.NUM,SJ.LINK_PAYS
ELSE
	INSERT INTO @Temp1_1 ([NUM],[LINK_PAYS],[MP],[MP_M],[MP_M_VKR])
	SELECT M.NUM,
			 [LINK_PAYS]= (SELECT LINK_INC  from pays where link = sj.LINK_PAYS),
			 [MP] 		= SUM(CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end), 
			 [MP_M] 		= SUM(CASE WHEN month(SJ.PERIOD_BEGIN)=m.num then (CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end) else 0 end),
			 [MP_M_VKR] = SUM(CASE WHEN ( month(SJ.PERIOD_BEGIN)=m.num)AND(sj.link_vkr = @LinkVKR AND SJ.LINK_EKR  IN (@LINK_EKR,@LINK_EKR_ADD)) 
								THEN (CASE WHEN month(SJ.PERIOD_BEGIN)<=m.num then SJ.summa else 0 end) else 0 end)
	FROM 
		dbo.MONTHS M 
		INNER JOIN dbo.S_J_C_Short SJ ON 1=1
		INNER JOIN #PAYS P ON P.LINK = SJ.LINK_PAYS
		INNER JOIN dbo.TAX_REF TR ON TR.LINK_PAYS =  SJ.LINK_PAYS
	WHERE 
		TR.LINK_TAX = @RefPay 
		AND (SJ.LINK_FACE = @linkFace)
		AND YEAR(SJ.PERIOD_BEGIN)=@Year AND M.NUM <= @Month 
		AND sj.LINK_DEP = @DEP_LINK
	GROUP BY 
		M.NUM,SJ.LINK_PAYS
	

/*if @FlagShow = 1  
	select *  from @Temp1_1*/

DECLARE @Temp1 TABLE
([NUM]			[int],
 [LINK_PAYS]	[int],
 [PREDEL]		[numeric](19,2),
 [MP]				[numeric](19,2),
 [MP_M]			[numeric](19,2),
 [MP_M_VKR]		[numeric](19,2))

INSERT INTO @Temp1 ([NUM],[LINK_PAYS],[PREDEL],[MP],[MP_M],[MP_M_VKR])
SELECT NUM,LINK_PAYS,
		[PREDEL] =  ISNULL((SELECT TOP 1 PREDEL FROM @NASTR 
								WHERE REF_PAY = (SELECT TOP 1 REF_DEDUCT FROM dbo.DICTIONARY_TYP_INCOMS WHERE LINK = LINK_PAYS)),0),
		SUM(MP) AS MP,
		SUM(MP_M) AS MP_M, 
		SUM(MP_M_VKR) AS MP_M_VKR
FROM @Temp1_1
GROUP BY NUM,LINK_PAYS

DECLARE @Temp2 TABLE
([NUM]			[int],
 [LINK_PAYS]	[int],
 [PREDEL]		[numeric](19,2),
 [MP]				[numeric](19,2),
 [MP_M]			[numeric](19,2),
 [MP_M_VKR]		[numeric](19,2),
 [SALDO]			[numeric](19,2),
 [KOEF]			[numeric](19,2))

---


INSERT INTO @Temp2 ([NUM],[LINK_PAYS],[PREDEL],[MP],[MP_M],[MP_M_VKR],[SALDO],[KOEF]) 
SELECT T1.[NUM],T1.[LINK_PAYS],T1.[PREDEL],T1.[MP],T1.[MP_M],T1.[MP_M_VKR],
		 [SALDO] = (CASE WHEN @Pred_Mesto_Rab + ISNULL((SELECT SUM(MP_M) FROM @Temp1 T2 WHERE T2.NUM <= T1.NUM AND T2.LINK_PAYS = T1.LINK_PAYS),0) > PREDEL
				THEN PREDEL
				ELSE @Pred_Mesto_Rab + ISNULL((SELECT SUM(MP_M) FROM @Temp1 T2 WHERE T2.NUM <= T1.NUM AND T2.LINK_PAYS = T1.LINK_PAYS),0)
				END)
				- (CASE WHEN @Pred_Mesto_Rab + ISNULL((SELECT SUM(MP_M) FROM @Temp1 T2 WHERE T2.NUM < T1.NUM AND T2.LINK_PAYS = T1.LINK_PAYS),0) > PREDEL
				THEN PREDEL
				ELSE @Pred_Mesto_Rab + ISNULL((SELECT SUM(MP_M) FROM @Temp1 T2 WHERE T2.NUM < T1.NUM AND T2.LINK_PAYS = T1.LINK_PAYS),0)
				END),
		 [KOEF] 	= (CASE WHEN (SELECT SUM(MP_M) FROM @Temp1 T3 WHERE T3.NUM = T1.NUM AND T3.LINK_PAYS = T1.LINK_PAYS) = 0 
						THEN 0 ELSE (CASE WHEN (SELECT SUM(MP_M) 
				                         FROM @Temp1 T3 WHERE T3.NUM = T1.NUM AND T3.LINK_PAYS = T1.LINK_PAYS)= 0 
										  THEN 0 ELSE 										
											MP_M_VKR/(SELECT SUM(MP_M) 
                    				     FROM @Temp1 T3 WHERE T3.NUM = T1.NUM AND T3.LINK_PAYS = T1.LINK_PAYS) END) END)
FROM @Temp1 T1


declare @predel numeric(18,2)
Set @predel = COALESCE((SELECT TOP 1 PREDEL FROM @Temp1),0)


DECLARE @Temp3 TABLE
([NUM]			[int],
 [LINK_PAYS]	[int],
 [SUMMA]			[numeric](19,2),
 [SUMMA_ALL]	[numeric](19,2),
 [SUMMA_M]		[numeric](19,2),
 [SUMMA_M_VKR]		[numeric](19,2)
)

INSERT INTO @Temp3 ([NUM],[LINK_PAYS],[SUMMA],[SUMMA_ALL],[SUMMA_M], SUMMA_M_VKR)
SELECT  T.[NUM], T.[LINK_PAYS],
		  [SUMMA] 	= dbo.IS_MIN((SELECT SUM(T3.SALDO * KOEF) FROM @Temp2 T3 WHERE  T3.NUM <= T.NUM AND T3.LINK_PAYS = T.LINK_PAYS),T.PREDEL), 
		  [SUMMA_ALL] 	= dbo.IS_MIN((SELECT SUM(T3.SALDO) FROM @Temp2 T3 WHERE  T3.NUM <= T.NUM AND T3.LINK_PAYS = T.LINK_PAYS),T.PREDEL),
		  [SUMMA_M] 	= CASE WHEN ABS(SUM(MP_M)) < ABS(T.SALDO) THEN ABS(T.SALDO) ELSE T.SALDO END,
		SUMMA_M_VKR 	= CASE WHEN ABS(SUM(MP_M)) < ABS(T.SALDO) THEN ABS(T.SALDO) ELSE T.SALDO END * KOEF
FROM @Temp2 T --WHERE SALDO > 0
GROUP BY T.NUM,T.PREDEL,T.SALDO,T.LINK_PAYS, KOEF 
ORDER BY T.NUM

if @FlagShow = 1  
	select num as [Месяц], LINK_PAYS as [Вычет], summa as [Скидка по ВКР/ЕКР], summa_all as [Скидка с начала года], summa_m as [Скидка за месяц]  from @Temp3


DECLARE @PREDEL_INV [numeric](15, 2)
SET @PREDEL_INV = ISNULL((SELECT TOP 1 PREDEL FROM dbo.DICTIONARY_MROT_TABLE3 DMT 
									WHERE LINK_MINROT = (SELECT TOP 1 LINK FROM dbo.DICTIONARY_MROT 
									WHERE PERIOD <=@DATE1 ORDER BY PERIOD DESC) AND (REF_PAY = @RefPay)),0)

DECLARE @T2_1 TABLE
([NUM]			[int],
 [SUMMA]			[numeric](19, 2),
 [SUMMA_VKR]	[numeric](19, 2),
 [SUMMA_M]		[numeric](19, 2),
 [SUMMA_M_VKR]	[numeric](19, 2),
 [MP]				[numeric](19, 2),
 [MP_VKR]		[numeric](19, 2),
 [MP_M]			[numeric](19, 2),
 [MP_M_VKR]		[numeric](19, 2),
 [STATUS]		[int],
 [INV]			[numeric](19, 2))


INSERT INTO @T2_1 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR],[MP],[MP_VKR],[MP_M],[MP_M_VKR],[STATUS],[INV])
SELECT T1.[NUM],T1.[SUMMA],T1.[SUMMA_VKR],T1.[SUMMA_M],T1.[SUMMA_M_VKR],
--		 [MP] 		= ISNULL((SELECT SUM(SUMMA) FROM @Temp3 T WHERE T.NUM <= T1.NUM),0),  
		 [MP] 		= ISNULL((SELECT SUM(SUMMA_ALL) FROM @Temp3 T WHERE T.NUM = T1.NUM),0),  
		 [MP_VKR]	= ISNULL((SELECT SUM(SUMMA) FROM @Temp3 T WHERE T.NUM = T1.NUM),0),  
		 [MP_M] 	= ISNULL((SELECT SUM(SUMMA_M) FROM @Temp3 T WHERE T.NUM = T1.NUM),0),  
		 [MP_M_VKR] = ISNULL((SELECT SUM(SUMMA_M_VKR) FROM @Temp3 T WHERE T.NUM = T1.NUM),0),  
--		 [MP_M_VKR] = ISNULL((SELECT SUM(SUMMA) FROM @Temp3 T WHERE T.NUM = T1.NUM),0),  
		 [STATUS] 	= dbo.is_invalid(@linkFace,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,T1.NUM,@Year))), 
		 [INV] 		= cast(0 as numeric(15,2))
FROM @T1 T1 
GROUP BY T1.NUM,T1.SUMMA,T1.SUMMA_VKR,T1.SUMMA_M,T1.SUMMA_M_VKR
ORDER BY T1.NUM


DECLARE @summa_m 	[numeric](15, 2), 
		  @mp_m 		[numeric](15, 2),
		  @num 		[int], 
		  @Flag 		[bit], 
		  @itog 		[numeric](15, 2)

SET @itog = 0
DECLARE TMP_CUR CURSOR
FOR SELECT SUMMA_M, MP_M,NUM FROM @T2_1 WHERE STATUS = 2
OPEN TMP_CUR
FETCH TMP_CUR INTO @summa_m,@mp_m,@num
WHILE (@@FETCH_STATUS  = 0) AND (@PREDEL_INV - @itog) > 0 BEGIN
	IF @PREDEL_INV < (@itog+ @summa_m - @mp_m)
		UPDATE @T2_1 SET INV =(@PREDEL_INV-@itog) WHERE NUM = @num
	ELSE
		UPDATE @T2_1 SET INV =(@summa_m - @mp_m) WHERE NUM = @num
	
	SET @itog = @itog + @summa_m - @mp_m
	FETCH TMP_CUR INTO @summa_m,@mp_m,@num
END
CLOSE TMP_CUR
DEALLOCATE TMP_CUR

-- Другие льготы за месяц помимо инвалидов
---Вычеты от удержаний
select 
	TA.LINK_DED, MON = MONTH(CJ.PERIOD_BEGIN),
	SUMMA_G = CAST(0 AS NUMERIC(18,2)),
	SUMMA_M = SUM(SUMMA),
	LIMIT = ISNULL((SELECT TOP 1 PREDEL FROM @NASTR WHERE REF_PAY = TA.LINK_DED),0)
INTO #DED_U
from 
	dbo.EMPL E inner join dbo.calculate_jurnal cj on e.link = cj.link_empl
	inner join dbo.TAX2_APP TA on TA.LINK_UP = CJ.LINK_PAYS
where 
	cj.LINK_DEP = @DEP_LINK
	AND
	year(period_begin) = @Year
	and
	E.PERS_LINK = @linkPers	
	and 
	MONTH(cj.PERIOD_BEGIN) <= @Month
	and
	ISNULL(TA.LINK_DED,0) > 0
GROUP BY 
	TA.LINK_DED, MONTH(CJ.PERIOD_BEGIN)


UPDATE A
SET SUMMA_G = (SELECT SUM(SUMMA_M) FROM #DED_U B WHERE B.MON <= A.MON )
FROM #DED_U A

UPDATE #DED_U
SET 
	SUMMA_G = CASE WHEN ISNULL(SUMMA_G,0) < ISNULL(LIMIT,0) THEN ISNULL(SUMMA_G,0) ELSE ISNULL(LIMIT,0) END,
	SUMMA_M = CASE WHEN ISNULL(SUMMA_G,0) < ISNULL(LIMIT,0) THEN ISNULL(SUMMA_M,0)
				ELSE 
					CASE WHEN ISNULL(LIMIT,0) - (ISNULL(SUMMA_G,0) - ISNULL(SUMMA_M,0)) > 0 THEN 
						ISNULL(LIMIT,0) - (ISNULL(SUMMA_G,0) - ISNULL(SUMMA_M,0))
					ELSE 0
					END
			  END

UPDATE @T2_1 SET INV = ISNULL(INV,0) + ISNULL((SELECT SUM(SUMMA_M) FROM #DED_U WHERE MON = NUM),0)

--Расчет налога
--
DECLARE @T2 TABLE 
([NUM]				[int],
 [SUMMA]			[numeric](19, 2),
 [SUMMA_VKR]		[numeric](19, 2),
 [SUMMA_M]			[numeric](19, 2),
 [SUMMA_M_VKR]		[numeric](19, 2),
 [MP]				[numeric](19, 2),
 [MP_VKR]			[numeric](19, 2),
 [MP_M]				[numeric](19, 2),
 [MP_M_VKR]			[numeric](19, 2),
 [STATUS]			[int],
 [INV]				[numeric](19, 2),
 [INV_VKR]			[numeric](19, 2),
 [TARIF]			[TINYINT],
 [SPECO] [INT]
  ) -- Категория тарифа

INSERT INTO @T2 ([NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR],[MP],[MP_VKR],[MP_M],[MP_M_VKR],[STATUS],[INV],[INV_VKR],[TARIF],[SPECO])
SELECT [NUM],[SUMMA],[SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR],[MP],[MP_VKR],[MP_M],[MP_M_VKR],[STATUS],[INV],
		 [INV_VKR] = (CASE WHEN (SUMMA_M - MP_M) = 0 THEN 0 ELSE (SUMMA_M_VKR - MP_M_VKR)*INV/(SUMMA_M - MP_M) END),
		 TARIF = CASE WHEN dbo.is_invalid(@linkFace,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,NUM,@Year))) = 2 THEN 3 ELSE @TARIF END,
		 [SPECO] = (SELECT TOP 1 [COD_SPO_USL_TRUD] FROM #PERIODY 
						WHERE dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,NUM,@Year)) BETWEEN st_date1 AND st_date2
						AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,NUM,@Year)) BETWEEN im_date1 AND im_date2)
FROM 
	@T2_1

if @FlagShow = 1 
	select [num] as [Месяц], [summa] as [Сумма с Н/Г],summa_vkr as [Сумма с Н/Г по ВКР/ЕКР], summa_m as [За мес], 
	summa_m_vkr as [За мес.по ВКР/ЕКР], mp as [Ск.всего], mp_vkr as [Ск.всего по ВКР/ЕКР],mp_m as [Ск. за мес],
	mp_m_vkr as [Ск.за мес.по ВКР/ЕКР], inv as [Льготы], inv_vkr as [Льготы по ВКР/ЕКР], TARIF as [ТАРИФ], [SPECO]  from @T2


DECLARE @WAY_CALC [int]
SELECT @WAY_CALC = WAY_CALC FROM dbo.PAYS WHERE LINK = @RefPay

DECLARE @Pred table  
(
 TARIF TINYINT,	
 [PREDEL]  [numeric](15, 2), 
 [PERCENT] [numeric](8, 2),
 WAY_CALC TINYINT,
 SPECO INT,
 NSPECO VARCHAR(254) )

IF @WAY_CALC<5
	
	IF @FlagMS = 1
		INSERT INTO @Pred (TARIF, [PREDEL],[PERCENT],SPECO,NSPECO)
		SELECT TARIF, [PREDEL],[PERCENT],SPECO=0,NSPECO='' FROM dbo.DICTIONARY_RANGE D
		WHERE
			(LINK_PAYS = @RefPay) 
			AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE D1 WHERE D1.TARIF = D.TARIF AND (LINK_PAYS = @RefPay) AND DATE < @DATE1 ORDER BY [DATE] DESC) 
		ORDER BY 1 
	ELSE 
		INSERT INTO @Pred (TARIF, [PREDEL],[PERCENT],SPECO,NSPECO)
		SELECT TOP 1 TARIF, [PREDEL] = 999999999999, [PERCENT],SPECO=0,NSPECO='' 
		FROM dbo.DICTIONARY_RANGE D
		WHERE 
			(LINK_PAYS = @RefPay) 
			AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE D1 WHERE D1.TARIF = D.TARIF AND (LINK_PAYS = @RefPay) AND DATE < @DATE1 ORDER BY [DATE] DESC) 
		ORDER BY 1 
ELSE 
BEGIN	
		
	DECLARE @Sex 		[int], 
			  @YearB 	[int], 
			  @Type 		[int]

	SELECT @Sex = SEX, @YearB = CASE WHEN RESIDENT = 1 THEN ISNULL(YEAR(BIRTHDATE),0) 
												ELSE 1966 END -- иностранцы по тарифам как для 66 года и страрше
											FROM dbo.PERSON WHERE LINK =@linkFace
	SET 	@Type = (CASE WHEN (@Sex = 1 AND @YearB < 1953) OR (@Sex = 2 AND @YearB<1957) THEN 1
						WHEN (@Sex = 1 AND @YearB BETWEEN 1953 AND 1966) OR (@Sex = 2 AND  @YearB BETWEEN 1957 AND 1966) THEN 2 
						ELSE 3 END)

	IF @FlagMS = 1 
		INSERT INTO @Pred (TARIF, [PREDEL],[PERCENT],WAY_CALC,SPECO,NSPECO)
		SELECT 
			TARIF,  
			[PREDEL],
			[PERCENT] = (CASE WHEN @Type = 1 THEN PERCENT1 WHEN @Type = 2 THEN PERCENT2 ELSE PERCENT3 END),
			WAY_CALC,
			SPECO,
			NSPECO
		FROM 
			dbo.DICTIONARY_RANGE_PF D
		WHERE
			LINK_PAYS = @RefPay 
			AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE_PF D1 WHERE D1.TARIF = D.TARIF AND ISNULL(D1.SPECO,0) = ISNULL(D.SPECO,0) AND LINK_PAYS = @RefPay AND DATE < @DATE1 ORDER BY [DATE] DESC) 
		ORDER BY 1 
	ELSE 
		INSERT INTO @Pred (TARIF, [PREDEL],[PERCENT],WAY_CALC,SPECO,NSPECO)
		SELECT TOP 1 
			TARIF, 
			[PREDEL] = 999999999999,
			[PERCENT] = (CASE WHEN @Type = 1 THEN PERCENT1 WHEN @Type = 2 THEN PERCENT2 ELSE PERCENT3 END),
			WAY_CALC,
			SPECO,NSPECO
		FROM 
			dbo.DICTIONARY_RANGE_PF D
		WHERE
			LINK_PAYS = @RefPay 
			AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE_PF D1 WHERE D1.TARIF = D.TARIF AND ISNULL(D1.SPECO,0) = ISNULL(D.SPECO,0) AND LINK_PAYS = @RefPay AND DATE < @DATE1 ORDER BY [DATE] DESC) 
		ORDER BY 1 
	END

IF @FlagShow = 1 
	select TARIF as [Тариф], Predel as [Предел], [Percent] as [Процент], NSPECO AS [Спецоценка] from @Pred P
	WHERE EXISTS (SELECT * FROM @T2 B WHERE B.TARIF = P.TARIF AND ISNULL(B.[SPECO],0) = ISNULL(P.[SPECO],0))

DECLARE @res TABLE
([NUM]			[int],
 [SUMMA]		[numeric] (19, 2),
 [SUMMA_M_VKR]	[numeric] (19, 2),
 [PERC]			[numeric] (19, 2),
 [SUM_MON]		[numeric] (19, 2),
 [TARIF]		INT,
 [SPECO]		INT)

INSERT INTO @res([NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],[TARIF],[SPECO])
SELECT T7.[NUM],T7.[SUMMA],T7.[SUMMA_M_VKR],T7.[PERC], CAST(0 as numeric(15,2)) AS SUM_MON, [TARIF], [SPECO]
FROM  
	(
	SELECT 
		[NUM], 
		[SUMMA] 		 = SUMMA - MP, 
		[SUMMA_M_VKR] = SUMMA_M_VKR - MP_M_VKR,	
		[PERC] 		 = ISNULL((SELECT TOP 1 T.[PERCENT] FROM (SELECT TOP 1 * FROM @Pred P WHERE B.TARIF = P.TARIF AND ISNULL(B.SPECO,0) = ISNULL(P.[SPECO],0) AND PREDEL > (SUMMA - MP + @SUM_DGH) ORDER BY PREDEL) T),0),
		B.[TARIF],
		B.[SPECO]
	 FROM @T2	B
	 UNION
	 SELECT DISTINCT
		[NUM] 			= ISNULL((SELECT MIN(NUM) FROM @T2 B1 WHERE B1.TARIF = B.TARIF AND ISNULL(B1.[SPECO],0) = ISNULL(B.[SPECO],0) AND (SUMMA-MP+@SUM_DGH) > PREDEL),12), 
		[SUMMA] 		= PREDEL - @SUM_DGH, 
		[SUMMA_M_VKR]= 0, 
		[PERC] 		= [PERCENT],  
		B.[TARIF],
		B.[SPECO]		
 	 FROM 
 		@T2 B INNER JOIN @Pred T ON B.TARIF = T.TARIF AND ISNULL(B.[SPECO],0) = ISNULL(T.[SPECO],0)
 	 WHERE 
 		PREDEL < (SELECT TOP 1 (SUMMA - MP + @SUM_DGH) FROM @T2 B1 WHERE B1.TARIF = B.TARIF AND ISNULL(B1.[SPECO],0) = ISNULL(B.[SPECO],0) ORDER BY 1 DESC)
 	) T7


DECLARE Curs CURSOR FAST_FORWARD FOR
SELECT NUM,SUMMA FROM @res ORDER BY [NUM]  

DECLARE @Summa [numeric] (19, 2), 
	@summa_prev [numeric] (19, 2), 
	@num1 [int]


SET @summa_prev = 0
OPEN Curs
FETCH NEXT FROM Curs INTO @num1, @Summa
WHILE @@FETCH_STATUS = 0 BEGIN
	UPDATE @res SET SUM_MON = @Summa - @summa_prev WHERE NUM = @num1 AND SUMMA = @Summa
	SET @summa_prev = @Summa
  	FETCH NEXT FROM Curs INTO @num1, @Summa
END
CLOSE Curs
DEALLOCATE Curs

DECLARE @Result1 TABLE
([NUM]			[int],
 [SUMMA]			[numeric] (19, 2),
 [SUMMA_M_VKR]	[numeric] (19, 2),
 [PERC]			[numeric] (19, 2),
 [SUM_MON]		[numeric] (19, 2),
 [SKIDKA]		[numeric] (19, 2),
 [KOEF]			[numeric] (19, 10), 
 [TARIF]		INT,
 [SPECO]		INT)


INSERT INTO @Result1 ([NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],[SKIDKA],[KOEF], [TARIF], [SPECO])
SELECT [NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],
		 [SKIDKA] = dbo.is_min(T1.SUM_MON, ISNULL((SELECT INV FROM @T2 T4  WHERE T4.NUM = T1.NUM),0)  
						- ISNULL((SELECT SUM(T3.SUM_MON) FROM @res T3 WHERE T3.NUM = T1.NUM AND T3.SUMMA < T1.SUMMA), 0)),
		 [KOEF] = (SELECT (CASE WHEN (SUMMA_M - MP_M) = 0 THEN 0 ELSE (SUMMA_M_VKR - MP_M_VKR)/(SUMMA_M - MP_M) END) FROM @T2 T2 WHERE T2.NUM = T1.NUM),
		 [TARIF], [SPECO]
FROM @res T1

DECLARE @RESULT TABLE
([NUM]			[int],
 [SUMMA]			[numeric] (19, 2),
 [SUMMA_M_VKR]	[numeric] (19, 2),
 [PERC]			[numeric] (19, 2),
 [SUM_MON]		[numeric] (19, 2),
 [SKIDKA]		[numeric] (19, 2),
 [KOEF]			[numeric] (19, 10),
 [VYCH] 		[numeric] (19, 2),
 [TARIF]		INT,
 [SPECO]		INT)

INSERT INTO @RESULT ([NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],[SKIDKA],[KOEF], [TARIF], [SPECO])
SELECT [NUM],[SUMMA],[SUMMA_M_VKR],[PERC],[SUM_MON],
		 [SKIDKA] = (CASE WHEN SKIDKA < 0 THEN 0 ELSE SKIDKA END),
		 [KOEF], [TARIF], [SPECO]
FROM @Result1

DECLARE @Razn 			[numeric](15, 2), 
	  @NalCurr 	[numeric](15, 2),
	  @Sum1 		[numeric](15, 2)

--Расчет с копейками
SET @NalCurr = (SELECT sum(ROUND((PERC * (COALESCE(SUM_MON,0) - COALESCE(SKIDKA,0))* COALESCE(KOEF,0)/100) * 100, 2) / 100) FROM @RESULT )

--Сумма ранее начисленного взноса
SET @Sum1 = ISNULL((SELECT SUM(SJ.SUMMA) FROM dbo.S_J_C_Short SJ 
WHERE SJ.LINK_VKR = @LinkVKR 
	--AND ( (SJ.LINK_EKR IN (@LINK_EKR,@LINK_EKR_ADD) AND @LINK_EKR <> @LINK_211EKR) OR (@LINK_EKR = @LINK_211EKR AND SJ.LINK_EKR IN (@LINK_211EKR,@LINK_213EKR)) )
	AND ( (SJ.LINK_EKR IN (@LINK_EKR,@LINK_EKR_ADD) AND @LINK_EKR <> @LINK_211EKR) OR (@LINK_EKR = @LINK_211EKR AND SJ.LINK_EKR = @LINK_EKR) )
	AND SJ.LINK_PAYS = @RefPay 
	AND (SJ.LINK_FACE = @linkFace) 
	AND MONTH_BEGIN <= @Month 
	AND YEAR_BEGIN=@Year 
	AND sj.LINK_DEP = @DEP_LINK),0)

--IF --ЕСЛИ ГОДОВОЙ ДОХОД ПО ВСЕМ ИСТОЧНИКАМ < 0
--	(SELECT SUM(SUMMA) FROM @RESULT) < 0 
--		--AND @Sum1 = 0 
--		-- И ЕСЛИ ТЕКУЩИЙ НАЛОГ ПОЛУЧАЕТСЯ < 0
--		AND @NalCurr < 0
--	SET @NalCurr = 0
	
SET @Razn = @NalCurr - @Sum1

DECLARE @FLG INT
SELECT TOP 1 @FLG = ISNULL(CONVERT(INT,VALUE),0) 
FROM S_OPTIONS WHERE OBJECT = (SELECT TOP 1 LINK FROM S_OBJECTS WHERE CODE = 'ESN_OPTIONS_FLG') AND SID IS NULL

IF @Razn <0 AND @FLG = 0
	SET @Razn=0

SELECT [SUMMA] 		= ISNULL(SUMMA_VKR,0), 
	 [SUMMA_VKR] 	= ISNULL(SUMMA_M_VKR, 0),
	 [SUM_DED] 		=	CASE WHEN ISNULL(SUMMA_VKR, 0) > 0 
						THEN
							ISNULL((SELECT TOP 1 MP_VKR FROM @T2 WHERE NUM = @Month), 0)
						ELSE 0 END,	
	 [INV_M] 		= CASE WHEN ISNULL(SUMMA_VKR, 0) > 0 
						THEN
							ISNULL((SELECT SUM(SKIDKA*KOEF) FROM @RESULT WHERE NUM = @Month),0)
						ELSE 0 END,
	 [INV] 			= CASE WHEN ISNULL(SUMMA_VKR, 0) > 0 
						THEN
							ISNULL((SELECT SUM(SKIDKA*KOEF) FROM @RESULT WHERE NUM <= @Month),0)
						ELSE 0 END,
	 [DED_M] 		= CASE WHEN ISNULL(SUMMA_VKR, 0) > 0 
						THEN
							ISNULL((SELECT TOP 1 MP_M_VKR FROM @T2 WHERE NUM = @Month), 0)
						ELSE 0 END,
	 [PERC]			= ISNULL((SELECT MIN(PERC) FROM @RESULT WHERE NUM = @Month),0),
	 [NALOG] 		= @NalCurr, 
	 [NAL_DED] 		= @Sum1, 
	 [NAL_CUR] 		= @Razn,
	 [TARIF]		= ISNULL((SELECT MIN([TARIF]) FROM @RESULT WHERE NUM = @Month),0), 
	 [SPECO]		= ISNULL((SELECT MIN([SPECO]) FROM @RESULT WHERE NUM = @Month),0),
	 [NSPECO]		= (SELECT TOP 1 CODE FROM dbo.SZV4_SPR WHERE LINK = ISNULL((SELECT MIN([SPECO]) FROM @RESULT WHERE NUM = @Month),0) )
FROM 
	@T1 
WHERE 
	NUM = @Month

SET NOCOUNT OFF




GO


GRANT EXECUTE ON dbo.[SALARY_FILL_DED_ESN_VKR] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RSA_RSV_1_PERS_UCH]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RSA_RSV_1_PERS_UCH]

GO

CREATE PROCEDURE dbo.RSA_RSV_1_PERS_UCH
	@dDate1 DATETIME,
	@dDate2 DATETIME,
	@LINK_DEP int = NULL,
	@REP TINYINT = 0, 
	@VARILSF INT = null
AS BEGIN

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output

	SET @DEP_LINK = COALESCE(@LINK_DEP,@DEP_LINK)

	DECLARE @ATR_PERS_UCH INT
	SET @ATR_PERS_UCH  = (SELECT DBO.RN_GET_ATR_VALUE(@VARILSF, 'REPORTS_ATR_PERS_UCH'))
	
	SELECT * into #docs FROM  dbo.SA_SZV4_PACHKA P 
	WHERE
	p.link_dep = @DEP_LINK and p.link = @ATR_PERS_UCH
	
	SELECT * into #docs_kor_otm FROM  dbo.SA_SZV4_PACHKA P 
	WHERE
	p.link_dep = @DEP_LINK and p.year_begin = year(@dDate1) and month_end <= month(@dDate2) and p.type = 1 and vid_kor <> 1
	AND P.LINK_ISHOD = @ATR_PERS_UCH

	--Округление каждой строчки таблицы
	DECLARE @ROUND_TYPE tinyint, @ROUND_LEN tinyint
	Set @ROUND_TYPE = dbo.sa_get_option_by_code('SA_SZV4_OPT2')
	Set @ROUND_LEN = (case when @ROUND_TYPE <= 1 then 2 else 0 end)
	Set @ROUND_TYPE = (case when @ROUND_TYPE = 3 then 1 else 0 end)

	--Округление только итогов
	DECLARE @IT_ROUND_TYPE tinyint
	Set @IT_ROUND_TYPE = dbo.sa_get_option_by_code('SA_SZV4_OPT5')

	DECLARE @PREDEL NUMERIC(18,2)
	SET @PREDEL = ISNULL((SELECT MIN(PREDEL) FROM dbo.DICTIONARY_RANGE_PF WHERE WAY_CALC = 6 AND TARIF = 1 AND [DATE] >= dbo.ConvertDMY2Date(1,1,YEAR(@dDate1))),0)
	-----------

	IF @REP = 0 
	BEGIN 
		Select 	
			[YEAR] = ISNULL(CASE WHEN year_begin >= 2013 THEN year_begin ELSE NULL END ,0),
			[NGROUP] = S.pachka,
			[DOCCOUNT] = COALESCE(MAX(case when S.forma = 2 then CEILING (CAST(S.orders AS FLOAT) /5 ) else 0 end),0)
					+ SUM(case when S.forma = 1 then 1 else 0 end),
			[PERS_CNT] = COUNT(S.orders),
			[cGRP] = REPLACE(str(S.pachka,5),' ','0'),
			[OPT1] = (case when p.type = 1 then 1 else 0 end),
			[OPT2] = (case when p.type = 2 then 1 else 0 end),
			[OPT3] = (case when vid_kor = 2 then 1 else 0 end),
			[OPT4] = (case when vid_kor = 3 then 1 else 0 end),
			INC_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.INCOME_M1)),@ROUND_LEN,@ROUND_TYPE),																																	
			INC_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.INCOME_M2)),@ROUND_LEN,@ROUND_TYPE),																														
			INC_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.INCOME_M3)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M1)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M2)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M3)),@ROUND_LEN,@ROUND_TYPE),
			B_AFT_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_AFTER_M1)),@ROUND_LEN,@ROUND_TYPE),
			B_AFT_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_AFTER_M2)),@ROUND_LEN,@ROUND_TYPE),
			B_AFT_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_AFTER_M3)),@ROUND_LEN,@ROUND_TYPE),
			--[INSUR] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_doh)),@ROUND_LEN,@ROUND_TYPE),			
			[INSUR] = ROUND(CONVERT(NUMERIC(18,2),
						sum(
						CASE WHEN ISNULL(S.BASE_AFTER_M1,0) + ISNULL(S.BASE_AFTER_M2,0) + ISNULL(S.BASE_AFTER_M3,0) <> 0 THEN
								ISNULL(S.BASE_BEFORE_M1,0) * PERCENT1 / 100 + ISNULL(S.BASE_BEFORE_M2,0) * PERCENT1 / 100 + ISNULL(S.BASE_BEFORE_M3,0) * PERCENT1 / 100
							ELSE
								ISNULL(S.sum_doh,0)
							END						
						)
						),@ROUND_LEN,@ROUND_TYPE),
			[INSUR1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_str)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_nak)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dop)),@ROUND_LEN,@ROUND_TYPE),
			sd_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_str)),@ROUND_LEN,@ROUND_TYPE),
			sud_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_str)),@ROUND_LEN,@ROUND_TYPE),
			sd_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_nak)),@ROUND_LEN,@ROUND_TYPE),
			sud_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_nak)),@ROUND_LEN,@ROUND_TYPE),
			[PER] = ISNULL(CASE WHEN year_begin >= 2013 THEN PER ELSE NULL END ,0) ,
			[PER10] = ISNULL(CASE WHEN year_begin >= 2013 THEN PER ELSE NULL END ,0) ,
			[TYPE] = p.[vid_kor],
			[PER_EDT] = ISNULL(PER_EDT,0),
			[YEAR_EDT] = ISNULL(YEAR_EDT,0),
			[T_DOG] = s.forma,
			DATE_CRT = '20131201',
			DATE_DOC = [date],
			SZV = MAX(S.forma), 
			FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),year_begin) + '-ORG-' + LTRIM(RTRIM(d.PFNUMBER)) + '-DCK-' + REPLACE(str(S.pachka,5),' ','0') + '-DPT-000000-DCK-00000.XML',
			LINK_DOC = P.link,
			link_pers = S.link_pers
		into #TMP
		from 
			dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up  AND (s.forma = 1 
															OR s.forma = 2 AND NOt EXISTS(SELECT * from dbo.SZV4_SVEDENIA WHERE  link_up = S.link_up and link_pers = s.link_pers AND forma = 1) )
			
			INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND
			inner join departments d on d.link = p.link_dep 
			INNER JOIN 
			(
				SELECT 
					TARIF, PERCENT1
				FROM 
					dbo.DICTIONARY_RANGE_PF D
				WHERE
					WAY_CALC = 6 AND PREDEL = @PREDEL
					AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE_PF D1 WHERE D1.TARIF = D.TARIF AND ISNULL(D1.SPECO,0) = ISNULL(D.SPECO,0) AND WAY_CALC = 6 AND DATE < @dDate1 ORDER BY [DATE] DESC) 
			) C ON C.TARIF = K.LINK2 			
		where
			P.link in (select link from #DOCS)
			and P.proverka = 1
			and p.link_dep = @DEP_LINK
		group by
			s.pachka, s.Forma, year_begin, p.[vid_kor], p.[TYPE], [date], K.CODE, PER, PER_EDT, YEAR_EDT, d.PFNUMBER, P.[link], S.link_pers
		order by
			S.pachka

		Select 	
			[YEAR] = ISNULL(CASE WHEN year_begin >= 2013 THEN year_begin ELSE NULL END ,0),
			[NGROUP] = S.pachka,
			[DOCCOUNT] = COALESCE(MAX(case when S.forma = 2 then CEILING (CAST(S.orders AS FLOAT) /5 ) else 0 end),0)
					+ SUM(case when S.forma = 1 then 1 else 0 end),
			[PERS_CNT] = COUNT(S.orders),
			[cGRP] = REPLACE(str(S.pachka,5),' ','0'),
			[OPT1] = (case when p.type = 1 then 1 else 0 end),
			[OPT2] = (case when p.type = 2 then 1 else 0 end),
			[OPT3] = (case when vid_kor = 2 then 1 else 0 end),
			[OPT4] = (case when vid_kor = 3 then 1 else 0 end),
			INC_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.INCOME_M1)),@ROUND_LEN,@ROUND_TYPE),																																	
			INC_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.INCOME_M2)),@ROUND_LEN,@ROUND_TYPE),																														
			INC_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.INCOME_M3)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M1)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M2)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M3)),@ROUND_LEN,@ROUND_TYPE),
			B_AFT_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_AFTER_M1)),@ROUND_LEN,@ROUND_TYPE),
			B_AFT_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_AFTER_M2)),@ROUND_LEN,@ROUND_TYPE),
			B_AFT_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_AFTER_M3)),@ROUND_LEN,@ROUND_TYPE),
			--[INSUR] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_doh)),@ROUND_LEN,@ROUND_TYPE),
			[INSUR] = ROUND(CONVERT(NUMERIC(18,2),
						sum(
						CASE WHEN ISNULL(S.BASE_AFTER_M1,0) + ISNULL(S.BASE_AFTER_M2,0) + ISNULL(S.BASE_AFTER_M3,0) <> 0 THEN
								ISNULL(S.BASE_BEFORE_M1,0) * PERCENT1 / 100 + ISNULL(S.BASE_BEFORE_M2,0) * PERCENT1 / 100 + ISNULL(S.BASE_BEFORE_M3,0) * PERCENT1 / 100
							ELSE
								ISNULL(S.sum_doh,0)
							END						
						)
						),@ROUND_LEN,@ROUND_TYPE),			
			[INSUR1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_str)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_nak)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dop)),@ROUND_LEN,@ROUND_TYPE),
			sd_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_str)),@ROUND_LEN,@ROUND_TYPE),
			sud_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_str)),@ROUND_LEN,@ROUND_TYPE),
			sd_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_nak)),@ROUND_LEN,@ROUND_TYPE),
			sud_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_nak)),@ROUND_LEN,@ROUND_TYPE),
			[PER] = ISNULL(CASE WHEN year_begin >= 2013 THEN PER ELSE NULL END ,0),
			[PER10] = ISNULL(CASE WHEN year_begin >= 2013 THEN PER ELSE NULL END ,0),
			[TYPE] = p.[vid_kor],
			[PER_EDT] = ISNULL(PER_EDT,0),
			[YEAR_EDT] = ISNULL(YEAR_EDT,0),
			[T_DOG] = s.forma,
			DATE_CRT = '20131201',
			DATE_DOC = [date],
			SZV = MAX(S.forma), 
			FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),year_begin) + '-ORG-' + LTRIM(RTRIM(d.PFNUMBER)) + '-DCK-' + REPLACE(str(S.pachka,5),' ','0') + '-DPT-000000-DCK-00000.XML',
			LINK_DOC = P.link,
			link_pers = S.link_pers
		into #TMP_1
		from 
			dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up  
																	and s.forma = 2 
																	AND EXISTS(SELECT * from dbo.SZV4_SVEDENIA WHERE  link_up = S.link_up and link_pers = s.link_pers AND forma = 1) 
			
			INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND
			inner join departments d on d.link = p.link_dep 
			INNER JOIN 
			(
				SELECT 
					TARIF, PERCENT1
				FROM 
					dbo.DICTIONARY_RANGE_PF D
				WHERE
					WAY_CALC = 6 AND PREDEL = @PREDEL
					AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE_PF D1 WHERE D1.TARIF = D.TARIF AND ISNULL(D1.SPECO,0) = ISNULL(D.SPECO,0) AND WAY_CALC = 6 AND DATE < @dDate1 ORDER BY [DATE] DESC) 
			) C ON C.TARIF = K.LINK2 				
		where
			P.link in (select link from #DOCS)
			and P.proverka = 1
			and p.link_dep = @DEP_LINK

		group by
			s.pachka, s.Forma, year_begin, p.[vid_kor], p.[TYPE], [date], K.CODE, PER, PER_EDT, YEAR_EDT, d.PFNUMBER, P.[link] , S.link_pers
		order by
			S.pachka

		UPDATE t 
			SEt t.INC_M1 = t.INC_M1+ t1.INC_M1, 
				t.INC_M2 = t.INC_M2+ t1.INC_M2,
				t.INC_M3 = t.INC_M3 + t1.INC_M3 ,
				t.B_BEF_M1 = t.B_BEF_M1 + t1.B_BEF_M1,
				t.B_BEF_M2 = t.B_BEF_M2 + t1.B_BEF_M2, 
				t.B_BEF_M3 = t.B_BEF_M3 + t1.B_BEF_M3,
				t.B_AFT_M1 = t.B_AFT_M1 + t1.B_AFT_M1,
				t.B_AFT_M2 = t.B_AFT_M2 + t1.B_AFT_M2, 
				t.B_AFT_M3 = t.B_AFT_M3 + t1.B_AFT_M3,
				t.[INSUR] =  t.[INSUR] + t1.[INSUR] ,
				t.[INSUR1] = t.[INSUR1] + t1.[INSUR1],
				t.[GAIN] = t.[GAIN] + t1.[GAIN] ,
				t.[GAIN1] = t.[GAIN1] + t1.[GAIN1] ,
				t.sd_str = t.sd_str + t1.sd_str,
				t.sud_str = t.sud_str + t1.sud_str,
				t.sd_nak = t.sd_nak + t1.sd_nak,
				t.sud_nak = t.sud_nak + t1.sud_nak
		FROM #TMP t inner join #TMP_1 t1 ON t.LINK_PERS = t1.link_pers


		UPDATE T
				SET	FNAME = REPLACE( FNAME, REPLACE(str(((SELECT MAX(nGROUP) FROM #TMP  where link_pers =t.link_pers )),5)+'-',' ','0'),REPLACE(str(((SELECT MIN(nGROUP) FROM #TMP  where link_pers =t.link_pers )),5)+'-',' ','0')), 
					nGROUP = (SELECT MIN(nGROUP) FROM #TMP  where link_pers =t.link_pers ),
					cGRP = REPLACE(str((SELECT MIN(nGROUP) FROM #TMP  where link_pers =t.link_pers ),5),' ','0')
		FROM #TMP T
		WHERE t.link_pers in (SELECT link_pers FROM #TMP  GROUP BY link_pers HAVING COUNT(link_pers) > 1)

		SELECT
			CODE = CONVERT(VARCHAR(10), [NGROUP]),
			COL1 = CONVERT(VARCHAR(10),[NGROUP]),
			COL2 = CONVERT(VARCHAR(10),''),
			COL3 = isnull((SUM(isnull(b_bef_m1,0)) + SUM(isnull(b_bef_m2,0)) + SUM(isnull(b_bef_m3,0))),0.00),
			COL4 = SUM(isnull(insur,0.00)),
			COL5 = SUM(ISNULL(pers_cnt,0)),
			COL6 = isnull(fname,''),
			COL7 = CONVERT(VARCHAR(10), date_doc, 104),
			COL8 = [TYPE],
			COL9 = PER,
			COL10 = [YEAR],
			COL11 = [LINK_DOC]
		FROM
			#TMP 
		GROUP BY 
			[NGROUP], fname , date_doc	, [TYPE] , PER , [YEAR] , [LINK_DOC]
		ORDER BY
			NGROUP


		drop table #TMP	
		drop table #TMP_1
					
	END
	
	IF @REP = 1 
	BEGIN 	
		Select 	
			[YEAR] = ISNULL(CASE WHEN year_begin >= 2013 THEN year_begin ELSE NULL END ,0),
			[MONTH] = ISNULL(month_end ,0),
			[PER] = case PER when 1 then 3 when 2 then 6 when 3 then 9 when 4 then 0 else null end ,
			[NGROUP] = S.pachka,
			[cGRP] = REPLACE(str(S.pachka,5),' ','0'),
			[CODE] = K.CODE,
			--[INSUR] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_doh)),@ROUND_LEN,@ROUND_TYPE),
			[INSUR] = ROUND(CONVERT(NUMERIC(18,2),
						sum(
						CASE WHEN ISNULL(S.BASE_AFTER_M1,0) + ISNULL(S.BASE_AFTER_M2,0) + ISNULL(S.BASE_AFTER_M3,0) <> 0 THEN
								ISNULL(S.BASE_BEFORE_M1,0) * PERCENT1 / 100 + ISNULL(S.BASE_BEFORE_M2,0) * PERCENT1 / 100 + ISNULL(S.BASE_BEFORE_M3,0) * PERCENT1 / 100
							ELSE
								ISNULL(S.sum_doh,0)
							END						
						)
						),@ROUND_LEN,@ROUND_TYPE),				
			[INSUR1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_str)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_nak)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dop)),@ROUND_LEN,@ROUND_TYPE),
			sd_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_str)),@ROUND_LEN,@ROUND_TYPE),
			sud_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_str)),@ROUND_LEN,@ROUND_TYPE),
			sd_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_nak)),@ROUND_LEN,@ROUND_TYPE),
			sud_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_nak)),@ROUND_LEN,@ROUND_TYPE),		
			[PERS_CNT] = COUNT(S.orders),
			[PER_EDT] = case ISNULL(PER_EDT,0 ) when 1 then 3 when 2 then 6 when 3 then 9 when 4 then 0 else null end ,
			[YEAR_EDT] = ISNULL(YEAR_EDT,0),
			FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),year_begin) + '-ORG-' + LTRIM(RTRIM(d.PFNUMBER)) + '-DCK-' + REPLACE(str(S.pachka,5),' ','0') + '-DPT-000000-DCK-00000.XML',
			IT_ROUND = @IT_ROUND_TYPE,
			DATE_DOC = p.[date],
			[TYPE] = p.[vid_kor],
			B_BEF_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M1)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M2)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M3)),@ROUND_LEN,@ROUND_TYPE),
			[T_DOG] = s.forma,
			LINK_DOC = P.link,
			link_pers = S.link_pers,
			dep_pFNUM = d.PFNUMBER
		into #TMP1
		from 
			dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up AND (s.forma = 1 
															OR s.forma = 2 AND NOt EXISTS(SELECT * from dbo.SZV4_SVEDENIA WHERE  link_up = S.link_up and link_pers = s.link_pers AND forma = 1) )
			INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND
			inner join departments d on d.link = p.link_dep
			INNER JOIN 
			(
				SELECT 
					TARIF, PERCENT1
				FROM 
					dbo.DICTIONARY_RANGE_PF D
				WHERE
					WAY_CALC = 6 AND PREDEL = @PREDEL
					AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE_PF D1 WHERE D1.TARIF = D.TARIF AND ISNULL(D1.SPECO,0) = ISNULL(D.SPECO,0) AND WAY_CALC = 6 AND DATE < @dDate1 ORDER BY [DATE] DESC) 
			) C ON C.TARIF = K.LINK2 				
		where
			P.link in (select link from #docs_kor_otm)
			and P.proverka = 1
			and P.vid_kor > 1
			and p.link_dep = @DEP_LINK
		group by
			s.pachka, s.Forma, year_begin,month_end,per, p.[vid_kor], K.CODE, PER_EDT, YEAR_EDT, d.PFNUMBER, p.[date], P.[link],S.link_pers


-------- нумерация пачек для корректирующих в зависимости от исходных сведений	
declare @MAX_PACHKA_ISHOD  int,@MIN_PACHKA_ISHOD int,  @MIN_PACHKA_KORR int,  
		@COUNT int , @ID int

select @MAX_PACHKA_ISHOD = max(s.pachka),
		@MIN_PACHKA_ISHOD = min(s.pachka),
		@MIN_PACHKA_KORR = (select max(s.pachka) FROM dbo.SA_SZV4_PACHKA p INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up and P.LINK = @ATR_PERS_UCH)
		FROM dbo.SA_SZV4_PACHKA p INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up and P.LINK_ISHOD = @ATR_PERS_UCH

IF @min_PACHKA_ISHOD = @MIN_PACHKA_KORR
BEGIN 
	declare @Cur cursor , @GR int , @cGR int
	set @ID = 1
	SET @Cur = CURSOR FORWARD_ONLY
	FOR 
		select ngroup,cGRP  from #tmp1 group by ngroup,cGRP
	OPEN @Cur
	FETCH NEXT FROM @Cur INTO @GR, @cGR
	
	WHILE (@@fetch_status <> -1)
	BEGIN
		
		IF (@@fetch_status <> -2)
		BEGIN	

			UPDATE #tmp1
				set NGROUP = @MAX_PACHKA_ISHOD+@ID --, t.[cGRP] =  '00'+ (@MAX_PACHKA_ISHOD+@ID)
			where ngroup = @GR AND cGRP = @cGR
				
			set @ID = @ID+1	
		end
		FETCH NEXT FROM @Cur INTO @GR , @cGR
	end

	CLOSE @Cur
	DEALLOCATE @Cur

END 

UPDATE t
	SET  cGRP=  '00'+ convert(varchar(3),NGROUP) 
	from #tmp1 t 
UPDATE t
	SET  FNAME=  'PFR-700-Y-' + CONVERT(VARCHAR(4),[year]) + '-ORG-' + LTRIM(RTRIM(dep_pFNUM)) + '-DCK-' + REPLACE(str(NGROUP,5),' ','0') + '-DPT-000000-DCK-00000.XML'	
	from #tmp1 t  WHERE TYPE <> 1

		Select 	
			[YEAR] = ISNULL(CASE WHEN year_begin >= 2013 THEN year_begin ELSE NULL END ,0),
			[MONTH] = ISNULL(month_end ,0),
			[PER] =  case PER when 1 then 3 when 2 then 6 when 3 then 9 when 4 then 0 else null end,
			[NGROUP] = S.pachka,
			[cGRP] = REPLACE(str(S.pachka,5),' ','0'),
			[CODE] = K.CODE,
			--[INSUR] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_doh)),@ROUND_LEN,@ROUND_TYPE),
			[INSUR] = ROUND(CONVERT(NUMERIC(18,2),
						sum(
						CASE WHEN ISNULL(S.BASE_AFTER_M1,0) + ISNULL(S.BASE_AFTER_M2,0) + ISNULL(S.BASE_AFTER_M3,0) <> 0 THEN
								ISNULL(S.BASE_BEFORE_M1,0) * PERCENT1 / 100 + ISNULL(S.BASE_BEFORE_M2,0) * PERCENT1 / 100 + ISNULL(S.BASE_BEFORE_M3,0) * PERCENT1 / 100
							ELSE
								ISNULL(S.sum_doh,0)
							END						
						)
						),@ROUND_LEN,@ROUND_TYPE),				
			[INSUR1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_str)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_nak)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dop)),@ROUND_LEN,@ROUND_TYPE),
			sd_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_str)),@ROUND_LEN,@ROUND_TYPE),
			sud_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_str)),@ROUND_LEN,@ROUND_TYPE),
			sd_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_nak)),@ROUND_LEN,@ROUND_TYPE),
			sud_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_nak)),@ROUND_LEN,@ROUND_TYPE),		
			[PERS_CNT] = COUNT(S.orders),
			[PER_EDT] = case when YEAR_EDT between '2011' and '2013'  then (case ISNULL(PER_EDT,0) when 1 then 1 when 2 then 2 when 3 then 3 when 4 then 4 else 0 end)
							when YEAR_EDT >= '2014' then (case ISNULL(PER_EDT,0) when 1 then 3 when 2 then 6 when 3 then 9 when 4 then 0 else null end) 
							end ,
			[YEAR_EDT] = ISNULL(YEAR_EDT,0),
			FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),year_begin) + '-ORG-' + LTRIM(RTRIM(d.PFNUMBER)) + '-DCK-' + REPLACE(str(S.pachka,5),' ','0') + '-DPT-000000-DCK-00000.XML',
			IT_ROUND = @IT_ROUND_TYPE,
			DATE_DOC = p.[date],
			[TYPE] = p.[vid_kor],
			B_BEF_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M1)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M2)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M3)),@ROUND_LEN,@ROUND_TYPE),
			[T_DOG] = s.forma,
			LINK_DOC = P.link,
			link_pers = S.link_pers
		into #TMP1_1
		from 
			dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up 																	
																	and s.forma = 2 
																	AND EXISTS(SELECT * from dbo.SZV4_SVEDENIA WHERE  link_up = S.link_up and link_pers = s.link_pers AND forma = 1) 
			INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND
			inner join departments d on d.link = p.link_dep
			INNER JOIN 
			(
				SELECT 
					TARIF, PERCENT1
				FROM 
					dbo.DICTIONARY_RANGE_PF D
				WHERE
					WAY_CALC = 6 AND PREDEL = @PREDEL
					AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE_PF D1 WHERE D1.TARIF = D.TARIF AND ISNULL(D1.SPECO,0) = ISNULL(D.SPECO,0) AND WAY_CALC = 6 AND DATE < @dDate1 ORDER BY [DATE] DESC) 
			) C ON C.TARIF = K.LINK2 				
		where
			P.link in (select link from #docs_kor_otm)
			and P.proverka = 1
			and P.vid_kor > 1
			and p.link_dep = @DEP_LINK
		group by
			s.pachka, s.Forma, year_begin,month_end,per, p.[vid_kor], K.CODE, PER_EDT, YEAR_EDT, d.PFNUMBER, p.[date], P.[link],S.link_pers

		/*Корректирующие сведения по физ лицам*/
		SELECT year_edt = p.YEAR_EDT, 
				PER_EDT = p.PER_EDT, 
				link_dep = p.link_dep,
				link_pers = s.link_pers,
				Link_kateg = S.Link_kateg,
				pachka = s.pachka
		INTO #tmp_pers
		FROM 	dbo.SA_SZV4_PACHKA P 
				INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up 															
		where
			P.link in (select link from #docs_kor_otm)
			and P.proverka = 1
			and P.vid_kor > 1
			and p.link_dep = @DEP_LINK


		CREATE TABLE #tmp_pers_kor_sum (link INT  , [date] DATETIME, YEAR_degin INT , per INT , vid_kor int, link_dep INT , proverka INT  , CODE VARCHAR(5), link_pers INT , 
										sum_doh NUMERIC(18,2), sum_str NUMERIC(18,2), sum_nak NUMERIC(18,2),sum_dop NUMERIC(18,2) , pachka int) 
	
		DECLARE @Cur1 CURSOR, @link int ,@LINK_pers INT, @year_edt INT , @per_edt INT , @Link_kateg INT ,@pachka int
		SET @Cur1 = CURSOR FORWARD_ONLY

		FOR SELECT LINK_pers, year_edt, per_edt, Link_kateg ,pachka FROM #tmp_pers ORDER by link_pers

		OPEN @Cur1
		FETCH NEXT FROM @Cur1 INTO @LINK_pers, @year_edt, @per_edt , @link_kateg, @pachka
		WHILE (@@fetch_status <> -1)
		BEGIN

			IF (@@fetch_status <> -2)
			BEGIN
				
				
					SET @link = 0
					
					SELECT @link =max(pp.link)
					FROM SA_SZV4_PACHKA pp 
					INNER JOIN dbo.SZV4_SVEDENIA Ss ON ss.link_up = pp.link  
					WHERE  pp.proverka = 1 AND pp.vid_kor = 1 
										   and pp.link_dep = @DEP_LINK 
										   and pp.year_begin =@year_edt  
										   AND pp.PER =@per_edt 
										   AND @LINK_pers = ss.link_pers
										   AND @link_kateg = ss.link_kateg  
										   AND pp.date = (SELECT MAX(p1.[date]) FROM SA_SZV4_PACHKA p1 
																INNER JOIN dbo.SZV4_SVEDENIA S1 ON s1.link_up = p1.link  
																WHERE  p1.proverka = 1 AND p1.vid_kor = 1 
																					   and p1.link_dep = @DEP_LINK 
																					   and p1.year_begin =@year_edt  
																					   AND p1.PER =@per_edt 
																					   AND @LINK_pers = s1.link_pers
																					   AND @link_kateg = s1.link_kateg )

					
					INSERT INTO #tmp_pers_kor_sum (link, [date], YEAR_degin, per, vid_kor, link_dep, proverka , CODE, link_pers, 
										sum_doh, sum_str, sum_nak,sum_dop, pachka) 
					SELECT pp.link, pp.[date], pp.YEAR_begin, pp.per, pp.vid_kor, pp.link_dep, pp.proverka, CODE = k.code, ss.link_pers, 
										ss.sum_doh, ss.sum_str, ss.sum_nak,ss.sum_dop , pachka = @pachka
					FROM SA_SZV4_PACHKA pp 
					INNER JOIN dbo.SZV4_SVEDENIA Ss ON ss.link_up = pp.link  
					INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = ss.LINK_KATEG AND pp.YEAR_begin BETWEEN YBEG AND YEND		
					WHERE pp.link = @link and pp.proverka = 1 
										  AND pp.vid_kor = 1 
										  and pp.link_dep = @DEP_LINK 
										  and pp.year_begin =@year_edt  
										  AND pp.PER =@per_edt 
										  AND ss.link_pers = @LINK_pers
										  AND ss.link_kateg = @link_kateg
										  

			END

			FETCH NEXT FROM @Cur1 INTO @LINK_pers, @year_edt, @per_edt, @link_kateg, @pachka
		END

		CLOSE @Cur1
		DEALLOCATE @Cur1
		

		UPDATE t 
			SEt t.[INSUR] =  t.[INSUR] + t1.[INSUR] ,
				t.[INSUR1] = t.[INSUR1] + t1.[INSUR1],
				t.[GAIN] = t.[GAIN] + t1.[GAIN] ,
				t.[GAIN1] = t.[GAIN1] + t1.[GAIN1] ,
				t.sd_str = t.sd_str + t1.sd_str,
				t.sud_str = t.sud_str + t1.sud_str,
				t.sd_nak = t.sd_nak + t1.sd_nak,
				t.sud_nak = t.sud_nak + t1.sud_nak
		FROM #TMP1 t inner join #TMP1_1 t1 ON t.LINK_PERS = t1.link_pers


---------->>>>>>>>>>
declare @SUM_DONACH_STR numeric(18,2),
		@SUM_DONACH_NAK numeric(18,2),
		@SUM_DONACH_STR_I numeric(18,2),
		@SUM_DONACH_NAK_I numeric(18,2)

select  @SUM_DONACH_STR = CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum WHERE CODE = 'НР' ) ,0)),

	    @SUM_DONACH_NAK = CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUM_nak) FROM #tmp_pers_kor_sum WHERE CODE = 'НР') ,0)), 
	
		@SUM_DONACH_STR_I = CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum WHERE CODE = 'ООИ') ,0)),
	    @SUM_DONACH_NAK_I = CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUM_nak) FROM #tmp_pers_kor_sum WHERE CODE = 'ООИ') ,0))

	SELECT
			CODE = CONVERT(VARCHAR(10), [NGROUP]),
			COL1 = CONVERT(VARCHAR(10),[NGROUP]),
			COL2 = CONVERT(VARCHAR(10),''),
			COL3 = CONVERT(VARCHAR(10),per_edt),
			COL4 = CONVERT(VARCHAR(10),year_edt),
			COL5 = ISNULL((case when year_edt >= 2014 then SUM(INSUR) - (CASE WHEN CODE = 'НР' then (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum WHERE CODE = 'НР' AND pachka = #TMP1.ngroup) 
															else (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum WHERE CODE <> 'НР' AND pachka = #TMP1.ngroup) end)	
													  else 0 end),0),
			COL6 = ISNULL((case when year_edt < 2014 then SUM(INSUR) - (CASE WHEN CODE = 'НР' then (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum WHERE CODE = 'НР' AND pachka = #TMP1.ngroup) 
															else (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum WHERE CODE <> 'НР' AND pachka = #TMP1.ngroup) end)
														else 0 end),0),
			COL7 = ISNULL((case when year_edt < 2014 then SUM(GAIN) - (CASE WHEN CODE = 'НР' then (SELECT SUM(SUM_nak) FROM #tmp_pers_kor_sum WHERE CODE = 'НР' AND pachka = #TMP1.ngroup)
															else (SELECT SUM(SUM_nak) FROM #tmp_pers_kor_sum WHERE CODE <> 'НР' AND pachka = #TMP1.ngroup) end)
														 else 0 end),0),
										 
														 
			COL8 = SUM(ISNULL(PERS_CNT, 0)),
			COL9 = isnull(fname,''),
			COL10 = CONVERT(VARCHAR(10), date_doc, 104),
			COL11 = [TYPE],
			COL12 = CONVERT(VARCHAR(1),PER),
			COL13 = CONVERT(VARCHAR(4),[YEAR]),
			COL14 = isnull((SUM(isnull(b_bef_m1,0)) + SUM(isnull(b_bef_m2,0)) + SUM(isnull(b_bef_m3,0))),0.00),
			COL15 = SUM(ISNULL([INSUR],0)),
			COL16 = [LINK_DOC]
		FROM
			#TMP1  
		GROUP BY [NGROUP],CODE,per_edt,year_edt, fname , date_doc	, [TYPE] , PER , [YEAR] , [LINK_DOC]	
		ORDER BY
			NGROUP

		drop table #TMP1
		drop table #TMP1_1

	END 
	
		drop table #docs_kor_otm
		drop table #docs

END

GO


GRANT EXECUTE ON dbo.[RSA_RSV_1_PERS_UCH] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SZV_K_STAZH_DOP_DELETE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZV_K_STAZH_DOP_DELETE]

GO



---------------------------------

CREATE PROCEDURE dbo.SA_SZV_K_STAZH_DOP_DELETE
	@varKSintLINK	int
AS
DECLARE @varKStrancount	int,
		@varKSObjectLink	int,
		@varKSEventText	varchar(254)

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

	DECLARE @link_up int
	select @link_up = link_up from dbo.SZV_K_STAZH_DOP where link = @varKSintLINK

	
	Select  @varKSEventText = 'Дополнительная запись о льготном стаже по физлицу ' + RTRIM(LTRIM(s.FIO)) + ', в организации' + RTRIM(LTRIM(sv.NAME_DEP)) 
	from dbo.SA_SZV_K_SVEDENIA  s 
		INNER join dbo.sa_szv_k_sved_work_dep sv ON s.link1 = sv.link 
		INNER join dbo.sa_szv_k_stazh st ON sv.link1 = st.link 
	WHERE st.link1 = @LINK_UP

	Select  @varKSEventText = @varKSEventText + ' с ' + convert(varchar(10), date1, 104) + ' по ' + convert(varchar(10), coalesce(date2,'20990101'), 104) from dbo.SZV_K_STAZH_DOP 
		WITH (UPDLOCK) WHERE link = @varKSintLINK

	IF @@RowCount = 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 2
	END

	DELETE FROM dbo.SZV_K_STAZH_DOP WHERE LINK = @varKSintLINK
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END


	/*Правильная сортировка*/
	declare @uslovie int
	set @uslovie = 1
	
	update SZV_K_STAZH_DOP set orders = 0 where link_up = @link_up
	
	while @uslovie > 0
	begin
		update SZV_K_STAZH_DOP set orders = @uslovie 
		from SZV_K_STAZH_DOP as tt
		where 	
			link_up = @link_up
			and coalesce(orders,0) = 0
			and date1 = (select min(t.date1) from SZV_K_STAZH_DOP t where coalesce(orders,0) = 0 and link_up = @link_up)
	
		if @@rowcount > 0
			set @uslovie = @uslovie + 1
		else
			set @uslovie = 0
	end

IF @@TRANCOUNT > @varKStrancount
	BEGIN
		SELECT @varKSObjectLink = LINK FROM S_OBJECTS WHERE CODE = 'SA_SZV_K_STAZH_DOP'
		EXECUTE WF_GENERATEEVENT 'Удаление из справочника', @varKSEventText, @varKSObjectLink, 'SA_SZV_K_STAZH_DOP', @varKSintLINK

		COMMIT TRAN
	END
RETURN 0



GO


GRANT EXECUTE ON dbo.[SA_SZV_K_STAZH_DOP_DELETE] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_RSV1_EXPORT_0700_2014]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_RSV1_EXPORT_0700_2014]

GO
---- exec [dbo].SA_RSV1_EXPORT_0700_2014 2565

CREATE   PROCEDURE [dbo].SA_RSV1_EXPORT_0700_2014 ( @Link int /*Ссылка на расчет*/ ) 
AS

CREATE TABLE #OUTPUT (ID int identity(1,1), F_NAME VARCHAR(254), OUT_TEXT TEXT)

SET NOCOUNT ON

--Строка заголовка
CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))

INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

declare @NAME_PROG varchar(254), @VERS_PROG VARCHAR(254), @WORK_END varchar(1)
Select @NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
	@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
from dbo.DICTIONARY_TASK where CODE = 'SALARY'
--------------------------------------------
-- Проставлять ОКАТО или ОКТМО по настройке
DECLARE @OKATO_OR_OKTMO int
SET @OKATO_OR_OKTMO = dbo.SA_GET_OPTION_BY_CODE('NASTR_USE_OKATO_OKTMO') 

DECLARE @ATR_TYPE_KOR INT
SET @ATR_TYPE_KOR  = (SELECT DBO.RN_GET_ATR_VALUE(@Link, 'REPORTS_ATR_TYPE_KOR'))	

	
DECLARE @LINK_DEP INT, @YEAR INT, @Version TINYINT, @Period_Number TINYINT, @LINK_FORM INT, @Begin_Date DATETIME, @End_Date DATETIME, @modify_date DATETIME
SELECT 
	@LINK_DEP = LINK_ORGANIZATION, 
	@YEAR = YEAR(Begin_Date),
	@Version = [Version],
	@Period_Number = Period_Number,
	@LINK_FORM = LINK_FORM,
	@Begin_Date = dbo.DateBeginOfYear(Begin_Date),
	@End_Date = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,Period_Number*3,YEAR(Begin_Date))),
	@modify_date = modify_date
FROM dbo.REPORT_SAVED_FORMS WHERE LINK_SAVED_FORM = @link

SELECT top 1
	DD1.OKPO AS OKPO1, 
	RIGHT(REPLICATE('0',12) + LTRIM(RTRIM(DD1.INN)), 12) AS INN1, 
	DD1.KPP AS KPP1, 
	FULL_NAME = CONVERT(VARCHAR(160),UPPER(DD1.FULL_NAME)),
	UPPER(DD1.NAME) AS ORGNAME,
	DD2.NALOG AS IMNS_SONO, DD2.NAME AS IMNS_NAME, 
	DD2.NALOG AS SONO, 
	RIGHT(REPLICATE('0',15) + LTRIM(RTRIM(DD1.OGRN)), 15) AS OGRN1,
	LTRIM(RTRIM(dbo.GetAddressBykladr(DD1.REF_LINK_A))) 
		+ CASE WHEN ISNULL(DD1.HOUSE, '') = '' THEN '' ELSE ' ' + LTRIM(RTRIM(DD1.HOUSE)) END
		+ CASE WHEN ISNULL(DD1.FLAT, '') = '' THEN '' ELSE ' - ' + LTRIM(RTRIM(DD1.FLAT)) END
	AS ADDR_STR,
	CAST(NULL AS DATETIME) AS DATE_END,
	UPPER(RTRIM(CHIEF.FM) + ' ' + LEFT(CHIEF.IM, 1) + '. ' + LEFT(CHIEF.OT,1) + '.') AS CHIEF_FIO,
	RTRIM(CHIEF.PHONE) AS CH_PHONE,
	UPPER(RTRIM(GLBUH.FM) + ' ' + LEFT(GLBUH.IM, 1) + '. ' + LEFT(GLBUH.OT,1) + '.') AS GLBUH_FIO,
	RTRIM(GLBUH.PHONE) AS GL_PHONE,
	OGRN = RIGHT(REPLICATE('0',15) + LTRIM(RTRIM(DD1.OGRN)), 15),
	DD1.OKATO,
	DD1.OKTMO,
	OKVED = (CASE WHEN LEN(ltrim(rtrim(DD1.OKVED)))<8 AND RIGHT(DD1.OKVED,1) = '.' THEN STUFF(DD1.OKVED,LEN(ltrim(rtrim(DD1.OKVED))),1,'') ELSE DD1.OKVED end) ,
 	DD1.OKPO,
	DD1.FSS_REG_NUM, --Регистрационный номер (код) страхователя ТФОМС
	DD1.FSS_KOD_P, --Код подчиненности - код, состоящий из пяти цифр, указывающий на территориальный орган Фонда, в котором страхователь зарегистрирован в текущий момент;	
	DD1.FSS_KOD_DOP, --Дополнительный код предусмотрен для обособленных подразделений организаций
	DD1.OKOPF, --- код Общероссийского классификатора организационно-правовых форм;
	DD1.OKFS, --- код Общероссийского классификатора форм собственности;
	DD1.PFNUMBER,
	DA.PINDEX, REGION = UPPER(DA.REGION), DA.REGCODE, RAION = UPPER(DA.RAION), GOROD = UPPER(DA.GOROD), 
	NASEL = UPPER(DA.NASEL), STREET = UPPER(DA.STREET), DA.HOUSE, DA.KORP, DA.FLAT,
	TFOMS_RNUM = DD1.TFOMS_REG_NUM,
	TFOMS_KT = DD1.TFOMS_KT,
	TFOMS_KTI = '03',
	WORK_END = '1'
INTO #DEP_DATA	
FROM DICTIONARY_DEPARTMENT DD1 
	LEFT OUTER JOIN DICTIONARY_DEPARTMENT DD2 ON DD1.IMNS_LINK = DD2.LINK
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Руководитель') chief on chief.link_dep = dd1.link
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Главный бухгалтер') GLBUH ON GLBUH.link_dep = dd1.link
	LEFT JOIN DBO.DEP_ADRESS(@LINK_DEP) DA ON 1=1
WHERE DD1.LINK = @LINK_DEP

DECLARE @Cur0 CURSOR, @CurD0 CURSOR, @Cur00 CURSOR,@Cur000 CURSOR, @TAB_NUM TINYINT, @TAB_NAME VARCHAR(254), @TABD_NUM TINYINT, @TABD_NAME VARCHAR(254), @TAB1_NAME VARCHAR(254), @TAB1_NUM TINYINT, @Cur CURSOR, @Cur1 CURSOR , @Cur2 CURSOR , @NUM INT, @BLOK_NAME VARCHAR(254), @RAZDEL_NUM TINYINT, @RAZDEL_NAME VARCHAR(254),
		@CurI0 CURSOR,@CurI00 CURSOR,@CurI000 CURSOR,@CurI CURSOR, @CurI1 CURSOR, @CurI2 CURSOR

DECLARE @lcFNAME varchar(254)
SELECT @lcFNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),@YEAR) + '-ORG-' + RTRIM(LTRIM(COALESCE(PFNUMBER,''))) + '-DCK-00001-DPT-000000-DCK-00000.XML' FROM #DEP_DATA

	--exec SA_RSV1_EXPORT_0700_2014   2565	


INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
 SELECT @lcFNAME, 'OEM' --Имя файла
 UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="Windows-1251" ?>'
 UNION ALL SELECT @lcFNAME, SPACE(0) + '<ФайлПФР>'
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<ИмяФайла>' + RTRIM(LTRIM(@lcFNAME)) + '</ИмяФайла>'
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<ЗаголовокФайла>'
	 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ВерсияФормата>07.00</ВерсияФормата>'
	 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ТипФайла>ВНЕШНИЙ</ТипФайла>'
	 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ПрограммаПодготовкиДанных>'
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<НазваниеПрограммы>' + @NAME_PROG + '</НазваниеПрограммы>'
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<Версия>' + @VERS_PROG + '</Версия>'
	 UNION ALL SELECT @lcFNAME, SPACE(2) + '</ПрограммаПодготовкиДанных>'
	 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ИсточникДанных>СТРАХОВАТЕЛЬ</ИсточникДанных> '
	UNION ALL SELECT @lcFNAME, SPACE(1) + '</ЗаголовокФайла>'
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<ПачкаВходящихДокументов Окружение="Единичный запрос">'
	 UNION ALL SELECT @lcFNAME, SPACE(2) + '<РАСЧЕТ_ПО_СТРАХОВЫМ_ВЗНОСАМ_НА_ОПС_И_ОМС_ПЛАТЕЛЬЩИКАМИ_ПРОИЗВОДЯЩИМИ_ВЫПЛАТЫ_ФЛ_2014>'
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<НомерВпачке>1</НомерВпачке>'
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<РегистрационныйНомерПФР>' + LTRIM(RTRIM(ISNULL(PFNUMBER,''))) + '</РегистрационныйНомерПФР>' + CHAR(10) +
								 SPACE(3) + '<НомерКорректировки>' + CASE @Version WHEN 0 THEN '000' ELSE (REPLICATE('0',2) + ltrim(rtrim(CONVERT(varchar(3),@Version)))) END + '</НомерКорректировки>' + CHAR(10) +
								 SPACE(3) + '<КодОтчетногоПериода>' + CASE @Period_Number WHEN 1 THEN '3' WHEN 2 THEN '6' WHEN 3 THEN '9' ELSE '0' END +'</КодОтчетногоПериода>' + CHAR(10) +
								 SPACE(3) + '<КалендарныйГод>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),@YEAR),''))) + '</КалендарныйГод> ' + CHAR(10) +
							   CASE WHEN LTRIM(RTRIM(ISNULL(@WORK_END,''))) = 'Л' THEN
										SPACE(3) + '<ПрекращениеДеятельности>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(1),WORK_END),''))) + '</ПрекращениеДеятельности> ' + CHAR(10)
								 ELSE '' END
		FROM #DEP_DATA	
		UNION ALL SELECT @lcFNAME, (	CASE  WHEN isnull(@ATR_TYPE_KOR,0) = 0 OR  @Version = 0 THEN ''
								ELSE  
								SPACE(3) + '<ТипКорректировки>' + CONVERT(varchar(1),@ATR_TYPE_KOR) + '</ТипКорректировки>' + CHAR(10) 
								END)

	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<НаименованиеОрганизации>' + LTRIM(RTRIM(ISNULL(FULL_NAME,''))) + '</НаименованиеОрганизации>' FROM #DEP_DATA
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + '<РегистрационныйНомерТФОМС>' + LTRIM(RTRIM(ISNULL(TFOMS_RNUM,''))) + '</РегистрационныйНомерТФОМС>' FROM #DEP_DATA
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<ИННсимвольный>' + LTRIM(RTRIM(ISNULL(INN1,''))) + '</ИННсимвольный>' FROM #DEP_DATA
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<КПП>' + LTRIM(RTRIM(ISNULL(KPP1,''))) + '</КПП>' FROM #DEP_DATA
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + '<ОГРН>' + LTRIM(RTRIM(ISNULL(OGRN1,''))) + '</ОГРН>' FROM #DEP_DATA 
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + case when @OKATO_OR_OKTMO = 1 
				--							 then ('<КодПоОКАТО>' + REPLACE(LTRIM(RTRIM(ISNULL(OKATO,''))),SPACE(1),'') + '</КодПоОКАТО>' )
				--							 ELSE ('<КодПоОКТМО>' + REPLACE(LTRIM(RTRIM(ISNULL(OKTMO,''))),SPACE(1),'') + '</КодПоОКТМО>' ) END 
				--							 FROM #DEP_DATA
	  											
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКВЭД>' + LTRIM(RTRIM(ISNULL(OKVED,''))) + '</КодПоОКВЭД>' FROM #DEP_DATA 
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКПО>' + LTRIM(RTRIM(ISNULL(OKPO,''))) + '</КодПоОКПО>' FROM #DEP_DATA 
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКОПФ>' + LTRIM(RTRIM(ISNULL(OKOPF,''))) + '</КодПоОКОПФ>' FROM #DEP_DATA 
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКФС>' + LTRIM(RTRIM(ISNULL(OKFS,''))) + '</КодПоОКФС>' FROM #DEP_DATA 
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<Телефон>' + LTRIM(RTRIM(ISNULL(GL_PHONE,''))) + '</Телефон>' FROM #DEP_DATA 
		
	 -- UNION ALL SELECT @lcFNAME, SPACE(3) + '<АдресРегистрации>'
		 -- UNION ALL SELECT @lcFNAME, SPACE(4) + '<ТипАдреса>РОССИЙСКИЙ</ТипАдреса>' 
		 -- UNION ALL SELECT @lcFNAME, SPACE(4) + '<Индекс>'+ LTRIM(RTRIM(ISNULL(PINDEX,''))) + '</Индекс>' FROM #DEP_DATA  
		 -- UNION ALL SELECT @lcFNAME, SPACE(4) + '<РоссийскийАдрес>' + CHAR(10) +

			--								CASE WHEN LTRIM(RTRIM(ISNULL(REGION,''))) <> '' THEN
			--								 SPACE(5) + '<Регион>' + CHAR(10) + 
			--									SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(REGION,len(REGION)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(REGION),1,' '))) ) )) + '</ГеографическоеНазвание>' + CHAR(10) + 
			--									SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(REGION),1,' ')) )) + '</Сокращение>' + CHAR(10) +
			--								SPACE(5) + '</Регион>' + CHAR(10) 
			--								ELSE '' END +
											
			--								CASE WHEN LTRIM(RTRIM(ISNULL(RAION,''))) <> '' THEN
			--								 SPACE(5) + '<Район>' + CHAR(10) + 
			--									SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(RAION,len(RAION)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(RAION),1,' '))) ) )) + '</ГеографическоеНазвание>' + CHAR(10) + 
			--									SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(RAION),1,' ')) )) + '</Сокращение>' + CHAR(10) +
			--								SPACE(5) + '</Район>' + CHAR(10) 
			--								ELSE '' END +

			--								CASE WHEN LTRIM(RTRIM(ISNULL(GOROD,''))) <> '' THEN
			--								 SPACE(5) + '<Город>' + CHAR(10) + 
			--									SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(GOROD,len(GOROD)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(GOROD),1,' '))) ) )) + '</ГеографическоеНазвание>' + CHAR(10) + 
			--									SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(GOROD),1,' ')) )) + '</Сокращение>' + CHAR(10) +
			--								SPACE(5) + '</Город>' + CHAR(10) 
			--								ELSE '' END +

			--								CASE WHEN LTRIM(RTRIM(ISNULL(NASEL,''))) <> '' THEN
			--								 SPACE(5) + '<НаселенныйПункт>' + CHAR(10) + 
			--									SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(NASEL,len(NASEL)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(NASEL),1,' '))) ) )) + '</ГеографическоеНазвание>' + CHAR(10) + 
			--									SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(NASEL),1,' ')) )) + '</Сокращение>' + CHAR(10) +
			--								SPACE(5) + '</НаселенныйПункт>' + CHAR(10) 
			--								ELSE '' END +	

			--								CASE WHEN LTRIM(RTRIM(ISNULL(STREET,''))) <> '' THEN
			--								SPACE(5) + '<Улица>' + CHAR(10)
			--									+ SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(STREET,len(STREET)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(STREET),1,' '))) ) ))+'</ГеографическоеНазвание>' + CHAR(10) 
			--									+ SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(STREET),1,' ')) ))+'</Сокращение>' + CHAR(10) 
			--									+ SPACE(5) + '</Улица>' + CHAR(10)
			--								ELSE '' END	+			

			--								CASE WHEN LTRIM(RTRIM(ISNULL(HOUSE,''))) <> '' THEN
			--								 SPACE(5) + '<Дом>' + CHAR(10) + 
			--									SPACE(6) + '<Сокращение>ДОМ</Сокращение>' + CHAR(10) +
			--									SPACE(6) + '<Номер>'+ UPPER(LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),HOUSE),'')))) + '</Номер>' + CHAR(10) + 
			--								SPACE(5) + '</Дом>' + CHAR(10) 
			--								ELSE '' END +												

			--								CASE WHEN LTRIM(RTRIM(ISNULL(KORP,''))) <> '' THEN
			--								 SPACE(5) + '<Корпус>' + CHAR(10) + 
			--									SPACE(6) + '<Сокращение>КОРП.</Сокращение>' + CHAR(10) +
			--									SPACE(6) + '<Номер>'+ UPPER(LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),KORP),'')))) + '</Номер>' + CHAR(10) + 
			--								SPACE(5) + '</Корпус>' + CHAR(10) 
			--								ELSE '' END +																

			--								CASE WHEN LTRIM(RTRIM(ISNULL(FLAT,''))) <> '' THEN
			--								 SPACE(5) + '<Квартира>' + CHAR(10) + 
			--									SPACE(6) + '<Сокращение>КВ.</Сокращение>' + CHAR(10) +
			--									SPACE(6) + '<Номер>'+ UPPER(LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),FLAT),'')))) + '</Номер>' + CHAR(10) + 
			--								SPACE(5) + '</Квартира>' + CHAR(10) 
			--								ELSE '' END +				
											
			--						SPACE(4) + '</РоссийскийАдрес>' + CHAR(10) +
			--					SPACE(3) + '</АдресРегистрации>'
			--FROM #DEP_DATA  

------ стр.1_2
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
select @lcFNAME, 
		CASE WHEN T.COL = 3 THEN
			SPACE(3) + '<КоличествоЗЛ>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ>'
		ELSE
			SPACE(3) + '<СреднесписочнаяЧисленность>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СреднесписочнаяЧисленность>'		
		END	
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 1, 1, DEFAULT) T WHERE T.COL IN (3,4) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)	
		 --SELECT @lcFNAME, SPACE(3) + '<КодУстановленногоТарифа>' + LTRIM(RTRIM(ISNULL(TFOMS_KT,''))) + '</КодУстановленногоТарифа>' FROM #DEP_DATA
/*UNION ALL*/ SELECT @lcFNAME, SPACE(3) + '<КоличествоСтраниц>14</КоличествоСтраниц>'
UNION ALL SELECT @lcFNAME, SPACE(3) + '<КоличествоЛистовПриложения>0</КоличествоЛистовПриложения>'

----- стр.2
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<Раздел1РасчетПоНачисленнымУплаченным2014>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ОстатокЗадолженностиНаНачалоРасчетногоПериода2014>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, CASE T.COL 
	WHEN 3 THEN SPACE(5) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
				SPACE(5) + '<СтраховыеВзносыОПС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОПС>' 
	WHEN 4 THEN	SPACE(5) + '<ОПСстраховаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧасть>'
	WHEN 5 THEN SPACE(5) + '<ОПСнакопительнаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСнакопительнаяЧасть>'
	WHEN 6 THEN SPACE(6) + '<ВзносыПоДопТарифу1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу1>'	
	WHEN 7 THEN SPACE(6) + '<ВзносыПоДопТарифу2_18>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу2_18>'
	WHEN 8 THEN SPACE(5) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'		
	--WHEN 6 THEN SPACE(5) + '<СтраховыеВзносыТФОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СтраховыеВзносыТФОМС>'
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 1, DEFAULT) T WHERE T.COL IN (3,4,5,6,7,8) ORDER BY T.COL

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ОстатокЗадолженностиНаНачалоРасчетногоПериода2014>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<НачисленоСначалаРасчетногоПериода2014>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME,
	CASE T.COL 
	WHEN 3 THEN 
		 CASE T.ROW WHEN 2 THEN SPACE(5) + '<ВсегоСначалаРасчетногоПериода2014>' WHEN 6 THEN SPACE(5) + '<ПоследниеТриМесяцаИтого2014>' ELSE SPACE(5) + '<ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 2))) + 'с2014>' END + CHAR(10) +
				SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
				SPACE(6) + '<СтраховыеВзносыОПС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОПС>' 
	--WHEN 4 THEN SPACE(6) + '<ОПСнакопительнаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСнакопительнаяЧасть>' 
	WHEN 6 THEN SPACE(6) + '<ВзносыПоДопТарифу1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу1>'	
	WHEN 7 THEN SPACE(6) + '<ВзносыПоДопТарифу2_18>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу2_18>'		
	WHEN 8 THEN SPACE(6) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'	+ CHAR(10) +		
	--WHEN 6 THEN SPACE(6) + '<СтраховыеВзносыТФОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СтраховыеВзносыТФОМС>' + CHAR(10) +	
		 CASE T.ROW WHEN 2 THEN SPACE(5) + '</ВсегоСначалаРасчетногоПериода2014>' WHEN 6 THEN SPACE(5) + '</ПоследниеТриМесяцаИтого2014>' ELSE SPACE(5) + '</ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 2))) + 'с2014>' END	
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 0, DEFAULT) T WHERE ROW IN (2,3,4,5,6) AND T.COL IN (3,6,7,8) ORDER BY T.ROW, T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</НачисленоСначалаРасчетногоПериода2014>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ДоначисленоСначалаРасчетногоПериода2014всего>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, CASE T.COL 
	WHEN 3 THEN --SPACE(5) + '<ВсегоСначалаРасчетногоПериода2013>' + CHAR(10) +
					SPACE(5) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
					SPACE(5) + '<СтраховыеВзносыОПС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОПС>'
	WHEN 4 THEN		SPACE(5) + '<ОПСстраховаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧасть>'
	WHEN 5 THEN		SPACE(5) + '<ОПСнакопительнаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСнакопительнаяЧасть>'
	WHEN 6 THEN		SPACE(5) + '<ВзносыПоДопТарифу1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу1>'	
	WHEN 7 THEN		SPACE(5) + '<ВзносыПоДопТарифу2_18>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу2_18>'		
	WHEN 8 THEN		SPACE(5) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'	
				--SPACE(5) + '</ВсегоСначалаРасчетногоПериода2013>'
	--WHEN 6 THEN sPACE(5) + '<СтраховыеВзносыТФОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СтраховыеВзносыТФОМС>'
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 7, DEFAULT) T WHERE T.COL IN (3,4,5,6,7,8) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ДоначисленоСначалаРасчетногоПериода2014всего>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ДоначисленоСначалаРасчетногоПериода2014превышающие>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, CASE T.COL 
	WHEN 3 THEN	--SPACE(5) + '<СсуммПревышающихПредельнуюВеличинуБазы>' + CHAR(10) +	
					SPACE(5) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
					SPACE(5) + '<СтраховыеВзносыОПС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОПС>' 
	WHEN 4 THEN		SPACE(5) + '<ОПСстраховаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧасть>'
	--WHEN 5 THEN		SPACE(5) + '<ОПСнакопительнаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСнакопительнаяЧасть>'
	--WHEN 6 THEN		SPACE(5) + '<ВзносыПоДопТарифу1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу1>'	
	--WHEN 7 THEN		SPACE(5) + '<ВзносыПоДопТарифу2_18>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу2_18>'	
	--WHEN 8 THEN		SPACE(5) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'	 
				--SPACE(5) + '</СсуммПревышающихПредельнуюВеличинуБазы>'	
	--WHEN 6 THEN sPACE(5) + '<СтраховыеВзносыТФОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СтраховыеВзносыТФОМС>'
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 8, DEFAULT) T WHERE T.COL IN (3,4) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ДоначисленоСначалаРасчетногоПериода2014превышающие>'


INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ВсегоКуплате2014>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, CASE T.COL 
	WHEN 3 THEN --SPACE(5) + '<ВсегоСначалаРасчетногоПериода2013>' + CHAR(10) +
					SPACE(5) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
					SPACE(5) + '<СтраховыеВзносыОПС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОПС>'
	WHEN 4 THEN		SPACE(5) + '<ОПСстраховаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧасть>'
	WHEN 5 THEN		SPACE(5) + '<ОПСнакопительнаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСнакопительнаяЧасть>'
	WHEN 6 THEN		SPACE(5) + '<ВзносыПоДопТарифу1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу1>'	
	WHEN 7 THEN		SPACE(5) + '<ВзносыПоДопТарифу2_18>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу2_18>'		
	WHEN 8 THEN		SPACE(5) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'	
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 10, DEFAULT) T WHERE T.COL IN (3,4,5,6,7,8) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ВсегоКуплате2014>'


INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<УплаченоСначалаРасчетногоПериода2014>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME,
	CASE T.COL 
	WHEN 3 THEN 
	CASE T.ROW WHEN 11 THEN SPACE(5) + '<ВсегоСначалаРасчетногоПериода2014>' WHEN 15 THEN SPACE(5) + '<ПоследниеТриМесяцаИтого2014>' ELSE SPACE(5) + '<ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 11))) + 'с2014>' END + CHAR(10) +
				SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
				SPACE(6) + '<СтраховыеВзносыОПС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОПС>' 
	
	WHEN 4 THEN SPACE(6) + '<ОПСстраховаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧасть>' 
	WHEN 5 THEN SPACE(6) + '<ОПСнакопительнаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСнакопительнаяЧасть>' 
	WHEN 6 THEN SPACE(6) + '<ВзносыПоДопТарифу1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу1>'	
	WHEN 7 THEN SPACE(6) + '<ВзносыПоДопТарифу2_18>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу2_18>'		
	WHEN 8 THEN SPACE(6) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'	+ CHAR(10) +		
	--WHEN 6 THEN SPACE(6) + '<СтраховыеВзносыТФОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СтраховыеВзносыТФОМС>' + CHAR(10) +	
	CASE T.ROW WHEN 11 THEN SPACE(5) + '</ВсегоСначалаРасчетногоПериода2014>' WHEN 15 THEN SPACE(5) + '</ПоследниеТриМесяцаИтого2014>' ELSE SPACE(5) + '</ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 11))) + 'с2014>' END	
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 0, DEFAULT) T WHERE ROW IN (11,12,13,14,15) AND T.COL IN (3,4,5,6,7,8) ORDER BY T.ROW, T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</УплаченоСначалаРасчетногоПериода2014>'

--INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ВтомЧислеЗаПредыдущиеРасчетныеПериоды2013>'
--INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
--SELECT @lcFNAME, CASE T.COL 
--	WHEN 3 THEN SPACE(5) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
--		 SPACE(5) + '<ОПСстраховаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧасть>'
--	WHEN 4 THEN SPACE(5) + '<ОПСнакопительнаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСнакопительнаяЧасть>'
--	WHEN 5 THEN	SPACE(6) + '<ОПСстраховаяЧастьПоДопТар1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧастьПоДопТар1>'		
--	WHEN 6 THEN	SPACE(6) + '<ОПСстраховаяЧастьПоДопТар2>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧастьПоДопТар2>'
--	WHEN 7 THEN SPACE(5) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'		
--	--WHEN 6 THEN SPACE(5) + '<СтраховыеВзносыТФОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СтраховыеВзносыТФОМС>'
--	END						
--FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 16, DEFAULT) T WHERE T.COL IN (3,4,5,6,7) ORDER BY T.COL
--INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ВтомЧислеЗаПредыдущиеРасчетныеПериоды2013>'


INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ОстатокЗадолженностиНаКонецРасчетногоПериода2014>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, CASE T.COL 
	WHEN 3 THEN	SPACE(5) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
				SPACE(5) + '<СтраховыеВзносыОПС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОПС>'
	WHEN 4 THEN	SPACE(5) + '<ОПСстраховаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧасть>'
	WHEN 5 THEN	SPACE(5) + '<ОПСнакопительнаяЧасть>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСнакопительнаяЧасть>'
	WHEN 6 THEN	SPACE(5) + '<ВзносыПоДопТарифу1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу1>'	
	WHEN 7 THEN	SPACE(5) + '<ВзносыПоДопТарифу2_18>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ВзносыПоДопТарифу2_18>'		
	WHEN 8 THEN	SPACE(5) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'	
	END							
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 16, DEFAULT) T WHERE T.COL IN (3,4,5,6,7,8) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ОстатокЗадолженностиНаКонецРасчетногоПериода2014>'


INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '</Раздел1РасчетПоНачисленнымУплаченным2014>'	


-----Разделы 2
CREATE TABLE #TABLES (NUM TINYINT, TAB_NAME VARCHAR(254))
INSERT INTO #TABLES 
		SELECT 3,'Раздел2РасчетПоТарифуИдопТарифу'
		
CREATE TABLE #TABLES_1 (NUM1 TINYINT, TAB_NUM TINYINT, TAB1_NAME varchar(254))
INSERT INTO #TABLES_1 
		SELECT 4,3, 'Раздел_2_1'

CREATE TABLE #STR_2_1R (NUM TINYINT, TAB_NUM TINYINT, RAZDEL_NAME VARCHAR(254))
INSERT INTO #STR_2_1R 
		SELECT 1,4,'НаОбязательноеПенсионноеСтрахование2014'
UNION	SELECT 2,4,'НаОбязательноеМедицинскоеСтрахование'

--UNION	SELECT 2,4,'НачисленоСтраховыхВзносовВпользуРаботниковИнвалидов'
--UNION	SELECT 3,4,'РасчетПоВыплатамРаботникамЕНВД' WHERE @YEAR <= 2010
--UNION	SELECT 4,4,'НачисленоСтраховыхВзносовВпользуРаботниковЕНВД' WHERE @YEAR <= 2010

CREATE TABLE #STR_2_1B (NUM TINYINT, RAZDEL_NUM TINYINT, BLOK_NAME VARCHAR(254))
INSERT INTO #STR_2_1B 
		SELECT 1,1,'СуммаВыплатИвознагражденийОПС'
UNION	SELECT 2,1,'НеПодлежащиеОбложениюОПС'
UNION	SELECT 3,1,'СуммаРасходовПринимаемыхКвычетуОПС'
UNION	SELECT 4,1,'ПревышающиеПредельнуюВеличинуБазыОПС'
UNION	SELECT 5,1,'БазаДляНачисленияСтраховыхВзносовНаОПС'
UNION	SELECT 6,1,'НачисленоНаОПСсСуммНеПревышающих'
UNION	SELECT 7,1,'НачисленоНаОПСсСуммПревышающих'
UNION	SELECT 8,1,'КоличествоФЛвсего'
UNION	SELECT 9,1,'КоличествоФЛпоКоторымБазаПревысилаПредел'
UNION	SELECT 10,2,'СуммаВыплатИвознаграждений'
UNION	SELECT 11,2,'НеПодлежащиеОбложению'
UNION	SELECT 12,2,'СуммаРасходовПринимаемыхКвычету'
UNION	SELECT 13,2,'ПревышающиеПредельнуюВеличинуБазы'
UNION	SELECT 14,2,'БазаДляНачисленияСтраховыхВзносовНаОМС'
UNION	SELECT 15,2,'НачисленоНаОМС'

--- ДОП ТАРИФЫ раздел 2_2 2_3
CREATE TABLE #TABLES1 (NUM TINYINT, TAB_NAME VARCHAR(254))
INSERT INTO #TABLES1 
		SELECT 5,'Раздел_2_2'
 union SELECT 6,'Раздел_2_3'

 

CREATE TABLE #STR_2_2C (NUM TINYINT, TAB_NUM TINYINT, BLOK_NAME VARCHAR(254))
INSERT INTO #STR_2_2C
		SELECT 1,5,'СуммаВыплатИвознагражденийПоДопТарифу'
UNION	SELECT 2,5,'НеПодлежащиеОбложениюПоДопТарифу'
UNION	SELECT 3,5,'БазаДляНачисленияСтраховыхВзносовПоДопТарифу'
UNION	SELECT 4,5,'НачисленоПоДопТарифу'
UNION	SELECT 5,5,'КоличествоФЛпоДопТарифу'

UNION	SELECT 6,6,'СуммаВыплатИвознагражденийПоДопТарифу'
UNION	SELECT 7,6,'НеПодлежащиеОбложениюПоДопТарифу'
UNION	SELECT 8,6,'БазаДляНачисленияСтраховыхВзносовПоДопТарифу'
UNION	SELECT 9,6,'НачисленоПоДопТарифу'
UNION	SELECT 10,6,'КоличествоФЛпоДопТарифу'


CREATE TABLE #TABLES_2 (NUM2 TINYINT, TAB2_NAME varchar(254))
INSERT INTO #TABLES_2 
		SELECT 7, 'Раздел_2_4'

CREATE TABLE #STR_2_4R (NUM TINYINT, TAB_NUM TINYINT, RAZDEL_NAME VARCHAR(254))
INSERT INTO #STR_2_4R 
		SELECT 1,7,'РасчетНачисленныхПоКодуСпецОценкиУТ'
CREATE TABLE #STR_2_4r1 (NUM TINYINT, RAZDEL_NUM TINYINT, BLOK_NAME VARCHAR(254))
INSERT INTO #STR_2_4r1 
		SELECT 1,1,'РасчетНачисленныхПоДопТарифу'
UNION	SELECT 2,1,'РасчетНачисленныхПоДопТарифу'
UNION	SELECT 3,1,'РасчетНачисленныхПоДопТарифу'
UNION	SELECT 4,1,'РасчетНачисленныхПоДопТарифу'
UNION	SELECT 5,1,'РасчетНачисленныхПоДопТарифу'
CREATE TABLE #STR_2_4B (NUM TINYINT, RAZDEL_NUM TINYINT, BLOK_NAME VARCHAR(254))
INSERT INTO #STR_2_4B 
		SELECT 1,1,'СуммаВыплатИвознагражденийПоДопТарифу'		
UNION	SELECT 2,1,'НеПодлежащиеОбложениюПоДопТарифу'
UNION	SELECT 3,1,'БазаДляНачисленияСтраховыхВзносовПоДопТарифу'
UNION	SELECT 4,1,'НачисленоПоДопТарифу'
UNION	SELECT 5,1,'КоличествоФЛпоДопТарифу'
UNION	SELECT 6,2,'СуммаВыплатИвознагражденийПоДопТарифу'		
UNION	SELECT 7,2,'НеПодлежащиеОбложениюПоДопТарифу'
UNION	SELECT 8,2,'БазаДляНачисленияСтраховыхВзносовПоДопТарифу'
UNION	SELECT 9,2,'НачисленоПоДопТарифу'
UNION	SELECT 10,2,'КоличествоФЛпоДопТарифу'
UNION	SELECT 11,3,'СуммаВыплатИвознагражденийПоДопТарифу'		
UNION	SELECT 12,3,'НеПодлежащиеОбложениюПоДопТарифу'
UNION	SELECT 13,3,'БазаДляНачисленияСтраховыхВзносовПоДопТарифу'
UNION	SELECT 14,3,'НачисленоПоДопТарифу'
UNION	SELECT 15,3,'КоличествоФЛпоДопТарифу'
UNION	SELECT 16,4,'СуммаВыплатИвознагражденийПоДопТарифу'		
UNION	SELECT 17,4,'НеПодлежащиеОбложениюПоДопТарифу'
UNION	SELECT 18,4,'БазаДляНачисленияСтраховыхВзносовПоДопТарифу'
UNION	SELECT 19,4,'НачисленоПоДопТарифу'
UNION	SELECT 20,4,'КоличествоФЛпоДопТарифу'
UNION	SELECT 21,5,'СуммаВыплатИвознагражденийПоДопТарифу'		
UNION	SELECT 22,5,'НеПодлежащиеОбложениюПоДопТарифу'
UNION	SELECT 23,5,'БазаДляНачисленияСтраховыхВзносовПоДопТарифу'
UNION	SELECT 24,5,'НачисленоПоДопТарифу'
UNION	SELECT 25,5,'КоличествоФЛпоДопТарифу'


--INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<' + @TAB_NAME + '>'
--select * from DBO.SA_SAVED_REPORT_VIEW (37368, 3, 0, DEFAULT) T WHERE T.COL IN (3) ORDER BY T.COL


SET @Cur0 = CURSOR FORWARD_ONLY
FOR select NUM, TAB_NAME from #TABLES order by NUM
OPEN @Cur0
FETCH NEXT FROM @Cur0 INTO @TAB_NUM, @TAB_NAME
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN	
	
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<' + @TAB_NAME + '>'
		

		SET @Cur = CURSOR FORWARD_ONLY
		FOR select NUM1, TAB1_NAME from #TABLES_1 WHERE TAB_NUM = @TAB_NUM order by NUM1
		OPEN @Cur
		FETCH NEXT FROM @Cur INTO @TAB1_NUM, @TAB1_NAME
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN	
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @TAB1_NAME + '>'
					
			--- Рабочие тариф 01
			IF @TAB1_NUM = 4
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<КодТарифа>' + LTRIM(RTRIM(ISNULL(TFOMS_KT,''))) + '</КодТарифа>' FROM #DEP_DATA

				SET @Cur1 = CURSOR FORWARD_ONLY
				FOR select NUM, RAZDEL_NAME from #STR_2_1R WHERE TAB_NUM = @TAB1_NUM order by NUM
				OPEN @Cur1
				FETCH NEXT FROM @Cur1 INTO @RAZDEL_NUM, @RAZDEL_NAME
				WHILE (@@fetch_status <> -1)
				BEGIN
					IF (@@fetch_status <> -2)
					BEGIN		

						INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<' + @RAZDEL_NAME + '>'
						
						SET @Cur2 = CURSOR FORWARD_ONLY
						FOR select NUM, BLOK_NAME from #STR_2_1B WHERE RAZDEL_NUM = @RAZDEL_NUM OR RAZDEL_NUM = @RAZDEL_NUM order by NUM
						OPEN @Cur2
						FETCH NEXT FROM @Cur2 INTO @NUM, @BLOK_NAME
						WHILE (@@fetch_status <> -1)
						BEGIN
							IF (@@fetch_status <> -2)
							BEGIN
								if @num = 8 or @num = 9
								begin
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @BLOK_NAME + '>'
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME, 
											CASE WHEN T.COL = 3 THEN SPACE(7) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
												 SPACE(7) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
											ELSE SPACE(7) + '<КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + + '</КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
											END				
										FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'

								end
								else begin
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @BLOK_NAME + '>'
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME, 
											CASE WHEN T.COL = 3 THEN SPACE(7) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
												 SPACE(7) + '<РасчетСумм>' + CHAR(10) +
												 SPACE(8) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
											ELSE SPACE(8) + '<СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + + '</СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
											END				
										FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</РасчетСумм>'
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'
								end
							END
							FETCH NEXT FROM @Cur2 INTO @NUM, @BLOK_NAME
						END
						CLOSE @Cur2
						DEALLOCATE @Cur2

						INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</' + @RAZDEL_NAME + '>'
					END
					FETCH NEXT FROM @Cur1 INTO @RAZDEL_NUM, @RAZDEL_NAME
				END
				CLOSE @Cur1
				DEALLOCATE @Cur1
			
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TAB1_NAME + '>'
			end	
			FETCH NEXT FROM @Cur INTO @TAB1_NUM, @TAB1_NAME
			END
		CLOSE @Cur
		DEALLOCATE @Cur

		--- Инвалиды тариф 03
		if (select count(*) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, DEFAULT, DEFAULT) T WHERE T.COL = 3 AND SUMMA <> 0 ) > 0
		begin
			SET @CurI0 = CURSOR FORWARD_ONLY
			FOR select NUM1, TAB1_NAME from #TABLES_1 order by NUM1
			OPEN @CurI0
			FETCH NEXT FROM @CurI0 INTO @TAB1_NUM, @TAB1_NAME
			WHILE (@@fetch_status <> -1)
			BEGIN
				IF (@@fetch_status <> -2)
				BEGIN	
				
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @TAB1_NAME + '>'


					--- Инвалиды тариф 03
					IF @TAB1_NUM = 4
						INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<КодТарифа>' + LTRIM(RTRIM(ISNULL(TFOMS_KTI,''))) + '</КодТарифа>' FROM #DEP_DATA

					SET @CurI = CURSOR FORWARD_ONLY
					FOR select NUM, RAZDEL_NAME from #STR_2_1R WHERE TAB_NUM = @TAB1_NUM order by NUM
					OPEN @CurI
					FETCH NEXT FROM @CurI INTO @RAZDEL_NUM, @RAZDEL_NAME
					WHILE (@@fetch_status <> -1)
					BEGIN
						IF (@@fetch_status <> -2)
						BEGIN		

							INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<' + @RAZDEL_NAME + '>'
					
							SET @CurI1 = CURSOR FORWARD_ONLY
							FOR select NUM, BLOK_NAME from #STR_2_1B WHERE RAZDEL_NUM = @RAZDEL_NUM OR RAZDEL_NUM = @RAZDEL_NUM order by NUM
							OPEN @CurI1
							FETCH NEXT FROM @CurI1 INTO @NUM, @BLOK_NAME
							WHILE (@@fetch_status <> -1)
							BEGIN
								IF (@@fetch_status <> -2)
								BEGIN
									if @num = 8 or @num = 9
									begin
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @BLOK_NAME + '>'
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
											SELECT @lcFNAME,
												CASE WHEN T.COL = 3 THEN SPACE(7) + '<КодСтроки>' + substring(LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))),1,3) + '</КодСтроки>' + CHAR(10) +
													 SPACE(7) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
												ELSE SPACE(7) + '<КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + + '</КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
												END				
											FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'
									end
									else begin
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @BLOK_NAME + '>'
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
											SELECT @lcFNAME, 
												CASE WHEN T.COL = 3 THEN SPACE(7) + '<КодСтроки>' + substring(LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))),1,3) + '</КодСтроки>' + CHAR(10) +
													 SPACE(7) + '<РасчетСумм>' + CHAR(10) +
													 SPACE(8) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
												ELSE SPACE(8) + '<СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + + '</СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
												END				
											FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</РасчетСумм>'
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'

									end
								END
								FETCH NEXT FROM @CurI1 INTO @NUM, @BLOK_NAME
							END
							CLOSE @CurI1
							DEALLOCATE @CurI1

							INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</' + @RAZDEL_NAME + '>'
						END
						FETCH NEXT FROM @CurI INTO @RAZDEL_NUM, @RAZDEL_NAME
					END
					CLOSE @CurI
					DEALLOCATE @CurI
						
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TAB1_NAME + '>'
				END
				FETCH NEXT FROM @CurI0 INTO @TAB1_NUM, @TAB1_NAME
			END
			CLOSE @CurI0
			DEALLOCATE @CurI0	
		end



		------------------------------------------------
		------------------------------------------------

		--- ДОП ТАРИФЫ
		---Раздел 2.2 и 2.3
		SET @CurD0 = CURSOR FORWARD_ONLY
		FOR select NUM, TAB_NAME from #TABLES1 order by NUM
		OPEN @CurD0
		FETCH NEXT FROM @CurD0 INTO @TABD_NUM, @TABD_NAME
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN	
			
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @TABD_NAME + '>'
				--- ДОП ТАРИФЫ 01
				--IF @TAB_NUM = 5
				--	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<КодТарифа>' + LTRIM(RTRIM(ISNULL(TFOMS_KT,''))) + '</КодТарифа>' FROM #DEP_DATA

				--SET @Cur = CURSOR FORWARD_ONLY
				--FOR select NUM, RAZDEL_NAME from #STR_2_1R WHERE TAB_NUM = @TAB_NUM order by NUM
				--OPEN @Cur
				--FETCH NEXT FROM @Cur INTO @RAZDEL_NUM, @RAZDEL_NAME
				--WHILE (@@fetch_status <> -1)
				--BEGIN
				--	IF (@@fetch_status <> -2)
				--	BEGIN		

				--		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @RAZDEL_NAME + '>'
						
						SET @Cur = CURSOR FORWARD_ONLY
						FOR select NUM, BLOK_NAME from #STR_2_2C WHERE TAB_NUM = @TABD_NUM OR TAB_NUM = @TABD_NUM order by NUM
						OPEN @Cur
						FETCH NEXT FROM @Cur INTO @NUM, @BLOK_NAME
						WHILE (@@fetch_status <> -1)
						BEGIN
							IF (@@fetch_status <> -2)
							BEGIN
								if @num = 5 or @num = 10
								begin
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @BLOK_NAME + '>'
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME, 
											CASE WHEN T.COL = 3 THEN SPACE(7) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
												 SPACE(7) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
											ELSE SPACE(7) + '<КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + + '</КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
											END				
										FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'

								end
								else begin
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @BLOK_NAME + '>'
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME, 
											CASE WHEN T.COL = 3 THEN SPACE(7) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
												 SPACE(7) + '<РасчетСумм>' + CHAR(10) +
												 SPACE(8) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
											ELSE SPACE(8) + '<СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + + '</СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
											END				
										FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</РасчетСумм>'
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'
								end
							END
							FETCH NEXT FROM @Cur INTO @NUM, @BLOK_NAME
						END
						CLOSE @Cur
						DEALLOCATE @Cur

				--		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @RAZDEL_NAME + '>'
				--	END
				--	FETCH NEXT FROM @Cur INTO @RAZDEL_NUM, @RAZDEL_NAME
				--END
				--CLOSE @Cur
				--DEALLOCATE @Cur
			
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TABD_NAME + '>'
			END
			FETCH NEXT FROM @CurD0 INTO @TABD_NUM, @TABD_NAME

		END
		CLOSE @CurD0
		DEALLOCATE @CurD0

		------------------------------------------------
		------------------------------------------------

		--- ДОП ТАРИФЫ
		---Раздел 2.4_1 и 2.4_2
		SET @Cur00 = CURSOR FORWARD_ONLY
		FOR select NUM2, TAB2_NAME from #TABLES_2 
		OPEN @Cur00
		FETCH NEXT FROM @Cur00 INTO @TAB1_NUM, @TAB1_NAME
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN	
			
				if (select count(*) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, DEFAULT, DEFAULT) T WHERE T.COL = 3 AND SUMMA <> 0 ) > 0
				BEGIN	
			--- --- доп тариф 01
				IF @TAB1_NUM = 7
				BEGIN
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @TAB1_NAME + '>'
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<КодОснованияРасчетаПоДопТарифу>' + LTRIM(RTRIM('1')) + '</КодОснованияРасчетаПоДопТарифу>'
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ОснованиеЗаполненияРаздела2_4>' + LTRIM(RTRIM('РЕЗУЛЬТАТЫ СПЕЦОЦЕНКИ')) + '</ОснованиеЗаполненияРаздела2_4>'
				end
				SET @Cur000 = CURSOR FORWARD_ONLY
				FOR select NUM, RAZDEL_NAME from #STR_2_4R WHERE TAB_NUM = @TAB1_NUM order by NUM
				OPEN @Cur000
				FETCH NEXT FROM @Cur000 INTO @RAZDEL_NUM, @RAZDEL_NAME
				WHILE (@@fetch_status <> -1)
				BEGIN
					IF (@@fetch_status <> -2)
					BEGIN		

						
						
						
						--NUM TINYINT, RAZDEL_NUM TINYINT, BLOK_NAME 
						SET @Cur1 = CURSOR FORWARD_ONLY
						FOR select NUM, BLOK_NAME from #STR_2_4R1 WHERE RAZDEL_NUM = @RAZDEL_NUM order by NUM
						OPEN @Cur1
						FETCH NEXT FROM @Cur1 INTO @TABD_NUM, @TABD_NAME
						WHILE (@@fetch_status <> -1)
						BEGIN
							IF (@@fetch_status <> -2)
							BEGIN		
								
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<' + @RAZDEL_NAME + '>'
								
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) 
											SELECT @lcFNAME, 
													SPACE(6) + '<КодСпециальнойОценкиУсловийТруда>' + 
													(CASE WHEN @TABD_NUM = 1 THEN LTRIM(RTRIM('О4'))
														 WHEN @TABD_NUM = 2 THEN LTRIM(RTRIM('В3.4'))
														 WHEN @TABD_NUM = 3 THEN LTRIM(RTRIM('В3.3'))
														 WHEN @TABD_NUM = 4 THEN LTRIM(RTRIM('В3.2'))
														 ELSE LTRIM(RTRIM('В3.1')) END ) + '</КодСпециальнойОценкиУсловийТруда>'
								
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @TABD_NAME + '>'	
									
									
									SET @Cur2 = CURSOR FORWARD_ONLY
									FOR select NUM, BLOK_NAME from #STR_2_4B WHERE RAZDEL_NUM = @TABD_NUM OR RAZDEL_NUM = @TABD_NUM order by NUM
									OPEN @Cur2
									FETCH NEXT FROM @Cur2 INTO @NUM, @BLOK_NAME
									WHILE (@@fetch_status <> -1)
									BEGIN
										IF (@@fetch_status <> -2)
										BEGIN
												
																						
											if @num = 5 or @num = 10 or @num = 15 or @num = 20 or @num = 25 
											begin
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '<' + @BLOK_NAME + '>'
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT @lcFNAME, 
														CASE WHEN T.COL = 3 THEN SPACE(8) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
															 SPACE(8) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
														ELSE SPACE(8) + '<КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + + '</КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
														END				
													FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</' + @BLOK_NAME + '>'

											end
											else begin
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '<' + @BLOK_NAME + '>'
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT @lcFNAME, 
														CASE WHEN T.COL = 3 THEN SPACE(8) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
															 SPACE(8) + '<РасчетСумм>' + CHAR(10) +
															 SPACE(9) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
														ELSE SPACE(9) + '<СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + + '</СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
														END				
													FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(8) + '</РасчетСумм>'
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</' + @BLOK_NAME + '>'
											end
										END
										FETCH NEXT FROM @Cur2 INTO @NUM, @BLOK_NAME
									END
									CLOSE @Cur2
									DEALLOCATE @Cur2
								
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @TABD_NAME + '>'	
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</' + @RAZDEL_NAME + '>'
							END
							FETCH NEXT FROM @Cur1 INTO @TABD_NUM, @TABD_NAME
					
						END
						CLOSE @Cur1
						DEALLOCATE @Cur1						
						
						
						
					END
					FETCH NEXT FROM @Cur000 INTO @RAZDEL_NUM, @RAZDEL_NAME	
				END 	
				CLOSE @Cur000
				DEALLOCATE @Cur000
				
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TAB1_NAME + '>'
				END 
				/***************************/	
			--- доп тариф 2
				/***************************/
				if (select count(*) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, DEFAULT, DEFAULT) T WHERE T.COL = 3 AND SUMMA <> 0 ) > 0
				begin
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @TAB1_NAME + '>'
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<КодОснованияРасчетаПоДопТарифу>' + LTRIM(RTRIM('2')) + '</КодОснованияРасчетаПоДопТарифу>'
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ОснованиеЗаполненияРаздела2_4>' + LTRIM(RTRIM('РЕЗУЛЬТАТЫ СПЕЦОЦЕНКИ')) + '</ОснованиеЗаполненияРаздела2_4>'

					SET @CurI0 = CURSOR FORWARD_ONLY
					FOR select NUM, RAZDEL_NAME from #STR_2_4R WHERE TAB_NUM = @TAB1_NUM order by NUM
					OPEN @CurI0
					FETCH NEXT FROM @CurI0 INTO @RAZDEL_NUM, @RAZDEL_NAME
					WHILE (@@fetch_status <> -1)
					BEGIN
						IF (@@fetch_status <> -2)
						BEGIN		

							
														
							--NUM TINYINT, RAZDEL_NUM TINYINT, BLOK_NAME 
							SET @CurI00 = CURSOR FORWARD_ONLY
							FOR select NUM, BLOK_NAME from #STR_2_4R1 WHERE RAZDEL_NUM = @RAZDEL_NUM order by NUM
							OPEN @CurI00
							FETCH NEXT FROM @CurI00 INTO @TABD_NUM, @TABD_NAME
							WHILE (@@fetch_status <> -1)
							BEGIN
								IF (@@fetch_status <> -2)
								BEGIN	
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<' + @RAZDEL_NAME + '>'	
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) 
											SELECT @lcFNAME, 
													SPACE(6) + '<КодСпециальнойОценкиУсловийТруда>' + 
													(CASE WHEN @TABD_NUM = 1 THEN LTRIM(RTRIM('О4'))
														 WHEN @TABD_NUM = 2 THEN LTRIM(RTRIM('В3.4'))
														 WHEN @TABD_NUM = 3 THEN LTRIM(RTRIM('В3.3'))
														 WHEN @TABD_NUM = 4 THEN LTRIM(RTRIM('В3.2'))
														 ELSE LTRIM(RTRIM('В3.1')) END ) + '</КодСпециальнойОценкиУсловийТруда>'
									
									
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @TABD_NAME + '>'	
										
										
										SET @CurI000 = CURSOR FORWARD_ONLY
										FOR select NUM, BLOK_NAME from #STR_2_4B WHERE RAZDEL_NUM = @TABD_NUM OR RAZDEL_NUM = @TABD_NUM order by NUM
										OPEN @CurI000
										FETCH NEXT FROM @CurI000 INTO @NUM, @BLOK_NAME
										WHILE (@@fetch_status <> -1)
										BEGIN
											IF (@@fetch_status <> -2)
											BEGIN
												if @num = 5 or @num = 10 or @num = 15 or @num = 20 or @num = 25 
												begin
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '<' + @BLOK_NAME + '>'
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT @lcFNAME, 
															CASE WHEN T.COL = 3 THEN SPACE(8) + '<КодСтроки>' + substring(LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))),1,3) + '</КодСтроки>' + CHAR(10) +
																 SPACE(8) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
															ELSE SPACE(8) + '<КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + + '</КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
															END				
														FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</' + @BLOK_NAME + '>'

												end
												else begin
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '<' + @BLOK_NAME + '>'
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT @lcFNAME, 
															CASE WHEN T.COL = 3 THEN SPACE(8) + '<КодСтроки>' + substring(LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))),1,3) + '</КодСтроки>' + CHAR(10) +
																 SPACE(8) + '<РасчетСумм>' + CHAR(10) +
																 SPACE(9) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
															ELSE SPACE(9) + '<СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + + '</СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
															END				
														FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(8) + '</РасчетСумм>'
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</' + @BLOK_NAME + '>'
												end
											END
											FETCH NEXT FROM @CurI000 INTO @NUM, @BLOK_NAME
										END
										CLOSE @CurI000
										DEALLOCATE @CurI000
									
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @TABD_NAME + '>'	
									
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</' + @RAZDEL_NAME + '>'
								END
								FETCH NEXT FROM @CurI00 INTO @TABD_NUM, @TABD_NAME
						
							END
							CLOSE @CurI00
							DEALLOCATE @CurI00						
							
							
							
						END
						FETCH NEXT FROM @CurI0 INTO @RAZDEL_NUM, @RAZDEL_NAME	
					END 	
					CLOSE @CurI0
					DEALLOCATE @CurI0
				
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TAB1_NAME + '>'
				/*****************/
				END
			
				--INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TAB1_NAME + '>'
			end	
			FETCH NEXT FROM @Cur00 INTO @TAB1_NUM, @TAB1_NAME
		END
		CLOSE @Cur00
		DEALLOCATE @Cur00

		-----Разделы 2.5.1 и 2.5.2
		CREATE TABLE #PACHKA_ISH (
			LINK INT, NOM_PACH VARCHAR(10), SUM_BASE NUMERIC(18,2), SUM_NACH NUMERIC(18,2), KOL_ZL NUMERIC(5), 
			NAME_FILE VARCHAR(254))

		CREATE TABLE #TAB3 (ROW_CODE VARCHAR(10), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
		INSERT INTO #TAB3 (ROW_CODE, COL, SUMMA, STR_VAL)
		SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

		INSERT INTO #PACHKA_ISH (NOM_PACH, SUM_BASE, SUM_NACH, KOL_ZL, NAME_FILE)
		SELECT DISTINCT 
			NOM_PACH = (SELECT TOP 1 ROW_CODE FROM #TAB3 T WHERE T.COL = 2 AND T.ROW_CODE = T3.ROW_CODE),
			SUM_BASE = (SELECT TOP 1 SUMMA FROM #TAB3 T WHERE T.COL = 3 AND T.ROW_CODE = T3.ROW_CODE),
			SUM_NACH = (SELECT TOP 1 SUMMA FROM #TAB3 T WHERE T.COL = 4 AND T.ROW_CODE = T3.ROW_CODE),
			KOL_ZL = (SELECT TOP 1 SUMMA FROM #TAB3 T WHERE T.COL = 5 AND T.ROW_CODE = T3.ROW_CODE),
			NAME_FILE = (SELECT TOP 1 STR_VAL FROM #TAB3 T WHERE T.COL = 6 AND T.ROW_CODE = T3.ROW_CODE)
		FROM
			#TAB3 T3

		DROP TABLE #TAB3

		DECLARE @NUM_pp INT
		SET @NUM_pp = 0
		UPDATE #PACHKA_ISH SET @NUM_pp = @NUM_pp + 1, LINK = @NUM_pp

		
		CREATE TABLE #PACHKA_KOR (
			LINK INT, NOM_PACH VARCHAR(4), PERIOD_CODE VARCHAR(1), PERIOD_YEAR VARCHAR(4),SUM_D NUMERIC(18,2), SUM_D_STR NUMERIC(18,2) , SUM_D_NAK NUMERIC(18,2), KOL_ZL NUMERIC(5), 
			NAME_FILE VARCHAR(254))

		CREATE TABLE #TAB4 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
		INSERT INTO #TAB4 (ROW_CODE, COL, SUMMA, STR_VAL)
		SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

		INSERT INTO #PACHKA_KOR (NOM_PACH, PERIOD_CODE, PERIOD_YEAR,SUM_D, SUM_D_STR, SUM_D_NAK, KOL_ZL, NAME_FILE)
		SELECT DISTINCT 
			NOM_PACH = (SELECT TOP 1 ROW_CODE FROM #TAB4 T WHERE T.COL = 2 AND T.ROW_CODE = T4.ROW_CODE),
			PERIOD_CODE = (SELECT TOP 1 STR_VAL FROM #TAB4 T WHERE T.COL = 3 AND T.ROW_CODE = T4.ROW_CODE),
			PERIOD_YEAR = (SELECT TOP 1 STR_VAL FROM #TAB4 T WHERE T.COL = 4 AND T.ROW_CODE = T4.ROW_CODE),
			SUM_D = (SELECT TOP 1 SUMMA FROM #TAB4 T WHERE T.COL = 5 AND T.ROW_CODE = T4.ROW_CODE),
			SUM_D_STR = (SELECT TOP 1 SUMMA FROM #TAB4 T WHERE T.COL = 6 AND T.ROW_CODE = T4.ROW_CODE),
			SUM_D_NAK = (SELECT TOP 1 SUMMA FROM #TAB4 T WHERE T.COL = 7 AND T.ROW_CODE = T4.ROW_CODE),
			KOL_ZL = (SELECT TOP 1 SUMMA FROM #TAB4 T WHERE T.COL = 8 AND T.ROW_CODE = T4.ROW_CODE),
			NAME_FILE = (SELECT TOP 1 STR_VAL FROM #TAB4 T WHERE T.COL = 9 AND T.ROW_CODE = T4.ROW_CODE)
		FROM
			#TAB4 T4

		DROP TABLE #TAB4
		
		SET @NUM_pp = 0
		UPDATE #PACHKA_KOR SET @NUM_pp = @NUM_pp + 1, LINK = @NUM_pp


		IF (SELECT COUNT(*) FROM #PACHKA_ISH) > 0 -- исходные сведения
			OR (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 8, DEFAULT, DEFAULT) WHERE COL = 5 AND SUMMA2 <> 0) > 0 
		BEGIN
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел_2_5>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ПереченьПачекИсходныхСведенийПУ>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<КоличествоПачек>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),(SELECT COUNT(*) FROM #PACHKA_ISH)),''))) + '</КоличествоПачек>'

			UNION ALL SELECT @lcFNAME, 
				SPACE(6) + '<СведенияОпачкеИсходных>' + CHAR(10) +
					SPACE(7) + '<НомерПП>' + LTRIM(RTRIM(CONVERT(VARCHAR(10),ISNULL(LINK,0)))) + '</НомерПП>' + CHAR(10) +			
					SPACE(7) + '<БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_BASE,0)))) + '</БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + CHAR(10) +	
					SPACE(7) + '<СтраховыхВзносовОПС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_NACH,0)))) + '</СтраховыхВзносовОПС>' + CHAR(10) +	
					SPACE(7) + '<КоличествоЗЛвПачке>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(KOL_ZL,0)))) + '</КоличествоЗЛвПачке>' + CHAR(10) +
					SPACE(7) + '<ИмяФайла>' + LTRIM(RTRIM(ISNULL(NAME_FILE,''))) + '</ИмяФайла>'+ CHAR(10) +					
					SPACE(6) + '</СведенияОпачкеИсходных>'		
			    FROM #PACHKA_ISH
			UNION ALL SELECT @lcFNAME, 
				SPACE(7) + '<ИтогоСведенияПоПачкам>' + CHAR(10) + 
					SPACE(8) + '<БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SUM_BASE),0)))) + '</БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + CHAR(10) +			
					SPACE(8) + '<СтраховыхВзносовОПС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SUM_NACH),0)))) + '</СтраховыхВзносовОПС>' + CHAR(10) +
					SPACE(8) + '<КоличествоЗЛвПачке>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(KOL_ZL),0)))) + '</КоличествоЗЛвПачке>' + CHAR(10) +
				SPACE(7) + '</ИтогоСведенияПоПачкам>'
			FROM #PACHKA_ISH	
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ПереченьПачекИсходныхСведенийПУ>'

			IF (SELECT COUNT(*) FROM #PACHKA_KOR) > 0 -- исходные сведения
				OR (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 9, DEFAULT, DEFAULT) WHERE COL = 8 AND SUMMA2 <> 0) > 0 
			BEGIN
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ПереченьПачекКорректирующихСведенийПУ>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<КоличествоПачек>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),(SELECT COUNT(*) FROM #PACHKA_KOR)),''))) + '</КоличествоПачек>'

				UNION ALL SELECT @lcFNAME, 
					SPACE(6) + '<СведенияОпачкеКорректирующих>' + CHAR(10) +
						SPACE(7) + '<НомерПП>' + LTRIM(RTRIM(CONVERT(VARCHAR(10),ISNULL(LINK,0)))) + '</НомерПП>' + CHAR(10) +			
						SPACE(7) + '<КорректируемыйОтчетныйПериод>' + CHAR(10) + 
							SPACE(8) + '<Квартал>' + LTRIM(RTRIM(ISNULL(/*(CASE WHEN */ PERIOD_CODE/*= '1' THEN '3'
																			 WHEN PERIOD_CODE= '2' THEN '6'
																			 WHEN PERIOD_CODE= '3' THEN '9'
																			 ELSE 0 END
																		 )*/,''))) + '</Квартал>' + CHAR(10) +	
							SPACE(8) + '<Год>' + LTRIM(RTRIM(ISNULL(PERIOD_YEAR,''))) + '</Год>' + CHAR(10) +
							SPACE(8) + '<Название>' + LTRIM(RTRIM(ISNULL((CASE WHEN PERIOD_CODE= '1' THEN 'С 01.01.'+PERIOD_YEAR+' ПО 31.03.'+PERIOD_YEAR+''
																			 WHEN PERIOD_CODE= '2' THEN 'С 01.01.'+PERIOD_YEAR+' ПО 30.06.'+PERIOD_YEAR+''
																			 WHEN PERIOD_CODE= '3' THEN 'С 01.01.'+PERIOD_YEAR+' ПО 30.09.'+PERIOD_YEAR+''
																			 ELSE 'С 01.01.'+PERIOD_YEAR+' ПО 31.12.'+PERIOD_YEAR+'' END
																		 ),''))) + '</Название>' + CHAR(10) +
						SPACE(7) + '</КорректируемыйОтчетныйПериод>' + CHAR(10) + 
						SPACE(7) + '<ДоначисленоСтраховыхВзносовОПС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_D,0)))) + '</ДоначисленоСтраховыхВзносовОПС>' + CHAR(10) +	
						SPACE(7) + '<ДоначисленоНаСтраховуюЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_D_STR,0)))) + '</ДоначисленоНаСтраховуюЧасть>' + CHAR(10) +	
						SPACE(7) + '<ДоначисленоНаНакопительнуюЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_D_NAK,0)))) + '</ДоначисленоНаНакопительнуюЧасть>' + CHAR(10) +	
						SPACE(7) + '<КоличествоЗЛвПачке>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(KOL_ZL,0)))) + '</КоличествоЗЛвПачке>' + CHAR(10) +
						SPACE(7) + '<ИмяФайла>' + LTRIM(RTRIM(ISNULL(NAME_FILE,''))) + '</ИмяФайла>'+ CHAR(10) +					
					SPACE(6) + '</СведенияОпачкеКорректирующих>' 	
					FROM #PACHKA_KOR
				UNION ALL SELECT @lcFNAME, 
					SPACE(7) + '<ИтогоСведенияПоПачкамКорректирующих>' + CHAR(10) + 
						SPACE(8) + '<ДоначисленоСтраховыхВзносовОПС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SUM_D),0)))) + '</ДоначисленоСтраховыхВзносовОПС>' + CHAR(10) +			
						SPACE(8) + '<ДоначисленоНаСтраховуюЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SUM_D_STR),0)))) + '</ДоначисленоНаСтраховуюЧасть>' + CHAR(10) +
						SPACE(8) + '<ДоначисленоНаНакопительнуюЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SUM_D_NAK),0)))) + '</ДоначисленоНаНакопительнуюЧасть>' + CHAR(10) +
						SPACE(8) + '<КоличествоЗЛвПачке>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(KOL_ZL),0)))) + '</КоличествоЗЛвПачке>' + CHAR(10) +
					SPACE(7) + '</ИтогоСведенияПоПачкамКорректирующих>'
				FROM #PACHKA_KOR	
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ПереченьПачекКорректирующихСведенийПУ>'
			END


			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел_2_5>'	

		END


		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '</' + @TAB_NAME + '>'


	END
	FETCH NEXT FROM @Cur0 INTO @TAB_NUM, @TAB_NAME
END
CLOSE @Cur0
DEALLOCATE @Cur0


-----Разделы 3
/*CREATE TABLE #INVALID (
	LINK INT, FIO VARCHAR(254), FIO2 VARCHAR(254), NUM_SPR VARCHAR(30), DATE_SPR VARCHAR(10), 
	GRP VARCHAR(25), GRP2 VARCHAR(25), PER_BEG VARCHAR(10), PER_END VARCHAR(10), 
	SM_ALL 	NUMERIC(18,2), SM_QWART NUMERIC(18,2), SM1 NUMERIC(18,2), SM2 NUMERIC(18,2), SM3 NUMERIC(18,2) )

CREATE TABLE #TAB5 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
INSERT INTO #TAB5 (ROW_CODE, COL, SUMMA, STR_VAL)
SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

INSERT INTO #INVALID (FIO2, DATE_SPR, PER_END, SM_ALL, SM1, SM2, SM3)
SELECT DISTINCT 
	FIO2 = (SELECT TOP 1 REPLACE(STR_VAL,SPACE(1), ', ') FROM #TAB5 T WHERE T.COL = 2 AND T.ROW_CODE = T5.ROW_CODE),
	DATE_SPR = (SELECT TOP 1 STR_VAL FROM #TAB5 T WHERE T.COL = 3 AND T.ROW_CODE = T5.ROW_CODE),
	PER_END = (SELECT TOP 1 STR_VAL FROM #TAB5 T WHERE T.COL = 4 AND T.ROW_CODE = T5.ROW_CODE),
	SM_ALL = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 5 AND T.ROW_CODE = T5.ROW_CODE),
	SM1 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 6 AND T.ROW_CODE = T5.ROW_CODE),
	SM2 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 7 AND T.ROW_CODE = T5.ROW_CODE),
	SM3 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 8 AND T.ROW_CODE = T5.ROW_CODE)
FROM
	#TAB5 T5

DROP TABLE #TAB5

--Проставить номера попорядку
DECLARE @NEXT_NUM INT
SET @NEXT_NUM = 0
UPDATE #INVALID SET @NEXT_NUM = @NEXT_NUM + 1, LINK = @NEXT_NUM

IF (SELECT COUNT(*) FROM #INVALID) > 0 -- инвалиды
	OR (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 7, DEFAULT, DEFAULT) WHERE COL = 3 AND SUMMA <> 0) > 0 -- информ. технол.
BEGIN
	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<Раздел3РасчетНаПравоПримененияПониженногоТарифа>'
---Раздел3_1	
	IF (SELECT COUNT(*) FROM #INVALID) > 0 -- инвалиды
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_1_СведенияДляПримененияПониженногоТарифа>'

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<КоличествоРаботниковИнвалидов>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),(SELECT COUNT(*) FROM #INVALID)),''))) + '</КоличествоРаботниковИнвалидов>'
		UNION ALL SELECT @lcFNAME, 
			SPACE(5) + '<СведенияОработникеИнвалиде>' + CHAR(10) +
				SPACE(6) + '<НомерПП>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(LINK,0)))) + '</НомерПП>' + CHAR(10) +			
				SPACE(6) + '<ФИО>' + CHAR(10) + 
					SPACE(7) + '<Фамилия>' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,1,','),' ')))) + '</Фамилия>' + CHAR(10) + 		
					SPACE(7) + '<Имя>' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,2,','),' ')))) + '</Имя>' + CHAR(10) + 		
					SPACE(7) + '<Отчество>' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,3,','),' ')))) + '</Отчество>' + CHAR(10) + 										
				SPACE(6) + '</ФИО>' + CHAR(10) + 
				SPACE(6) + '<СведенияИзСправки>' + CHAR(10) + 
					SPACE(7) + '<ДатаВыдачиСправки>' + LTRIM(RTRIM(ISNULL(DATE_SPR,' '))) + '</ДатаВыдачиСправки>' + CHAR(10) +
					SPACE(7) + '<ДатаОкончанияДействия>' + LTRIM(RTRIM(ISNULL(PER_END,''))) + '</ДатаОкончанияДействия>' + CHAR(10) +
				SPACE(6) + '</СведенияИзСправки>' + CHAR(10) + 				
				SPACE(6) + '<СуммыВыплатИвознаграждений>' + CHAR(10) +
					SPACE(7) + '<СуммаВсегоСначалаРасчетногоПериода>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM_ALL,0)))) + '</СуммаВсегоСначалаРасчетногоПериода>' + CHAR(10) +			
					SPACE(7) + '<СуммаПоследние1месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM1,0)))) + '</СуммаПоследние1месяц>' + CHAR(10) +
					SPACE(7) + '<СуммаПоследние2месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM2,0)))) + '</СуммаПоследние2месяц>' + CHAR(10) +
					SPACE(7) + '<СуммаПоследние3месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM3,0)))) + '</СуммаПоследние3месяц>' + CHAR(10) +								
				SPACE(6) + '</СуммыВыплатИвознаграждений>' + CHAR(10) +			
			SPACE(5) + '</СведенияОработникеИнвалиде>'
		FROM #INVALID
		UNION ALL SELECT @lcFNAME, 
			SPACE(5) + '<ИтогоВыплат>' + CHAR(10) + 
				SPACE(6) + '<СуммаВсегоСначалаРасчетногоПериода>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SM_ALL),0)))) + '</СуммаВсегоСначалаРасчетногоПериода>' + CHAR(10) +			
				SPACE(6) + '<СуммаПоследние1месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SM1),0)))) + '</СуммаПоследние1месяц>' + CHAR(10) +
				SPACE(6) + '<СуммаПоследние2месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SM2),0)))) + '</СуммаПоследние2месяц>' + CHAR(10) +
				SPACE(6) + '<СуммаПоследние3месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SM3),0)))) + '</СуммаПоследние3месяц>' + CHAR(10) +								
			SPACE(5) + '</ИтогоВыплат>'
		FROM #INVALID	

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_1_СведенияДляПримененияПониженногоТарифа>'	

*/		

		
		---Раздел3---
IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 10, DEFAULT, 3) WHERE SUMMA <> 0) > 0
BEGIN
			
	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<Раздел3РасчетНаПравоПримененияПониженногоТарифа2014>'
	  
	---Раздел3_1---	
	IF ( SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 10, 1, DEFAULT) WHERE SUMMA <> 0) > 0
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_1_ДляОбщественныхОрганизацийИнвалидов>'
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ЧисленностьЧленовОрганизации>'
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, CASE T.COL 
							WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
										SPACE(6) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
							WHEN 4 THEN SPACE(6) + '<КоличествоЗЛ_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_1месяц>'
							WHEN 5 THEN SPACE(6) + '<КоличествоЗЛ_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_2месяц>'		
							WHEN 6 THEN SPACE(6) + '<КоличествоЗЛ_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_3месяц>'
						END						
		FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ЧисленностьЧленовОрганизации>'

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ЧисленностьИнвалидов>'
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, CASE T.COL 
			WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
				 SPACE(6) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
			WHEN 4 THEN SPACE(6) + '<КоличествоЗЛ_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_1месяц>'
			WHEN 5 THEN SPACE(6) + '<КоличествоЗЛ_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_2месяц>'		
			WHEN 6 THEN SPACE(6) + '<КоличествоЗЛ_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_3месяц>'
			END						
		FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 2, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ЧисленностьИнвалидов>'

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<УдельныйВесЧисленности>'
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, CASE T.COL 
			WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
				 SPACE(6) + '<УдельныйВес_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_Всего>'
			WHEN 4 THEN SPACE(6) + '<УдельныйВес_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_1месяц>'
			WHEN 5 THEN SPACE(6) + '<УдельныйВес_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_2месяц>'		
			WHEN 6 THEN SPACE(6) + '<УдельныйВес_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_3месяц>'
			END						
		FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 3, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</УдельныйВесЧисленности>'			
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_1_ДляОбщественныхОрганизацийИнвалидов>'
	END	--IF ( SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 10, 1, DEFAULT) WHERE SUMMA <> 0) > 0 	



---Раздел3_2

	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 4, DEFAULT) WHERE SUMMA <> 0) > 0
	BEGIN

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_2_ДляОрганизацийУставныйКапиталСостоитИзВкладовОбщОргИнвалидов>'
					
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СреднесписочнаяЧисленность>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
							SPACE(6) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
				WHEN 4 THEN SPACE(6) + '<КоличествоЗЛ_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_1месяц>'
				WHEN 5 THEN SPACE(6) + '<КоличествоЗЛ_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_2месяц>'		
				WHEN 6 THEN SPACE(6) + '<КоличествоЗЛ_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_3месяц>'
				END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 4, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СреднесписочнаяЧисленность>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СреднесписочнаяЧисленностьИнвалидов>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
		  					SPACE(6) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
				WHEN 4 THEN SPACE(6) + '<КоличествоЗЛ_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_1месяц>'
				WHEN 5 THEN SPACE(6) + '<КоличествоЗЛ_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_2месяц>'		
				WHEN 6 THEN SPACE(6) + '<КоличествоЗЛ_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_3месяц>'
				END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 5, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СреднесписочнаяЧисленностьИнвалидов>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<УдельныйВесЧисленности>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
							SPACE(6) + '<УдельныйВес_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_Всего>'
				WHEN 4 THEN SPACE(6) + '<УдельныйВес_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_1месяц>'
				WHEN 5 THEN SPACE(6) + '<УдельныйВес_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_2месяц>'		
				WHEN 6 THEN SPACE(6) + '<УдельныйВес_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_3месяц>'
			END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 6, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</УдельныйВесЧисленности>'
					
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ФондОплатыТруда>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
							SPACE(6) + '<РасчетСумм>' + CHAR(10) +
								SPACE(7) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
					WHEN 4 THEN SPACE(7) + '<СуммаПоследние1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние1месяц>'
					WHEN 5 THEN SPACE(7) + '<СуммаПоследние2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние2месяц>'		
					WHEN 6 THEN SPACE(7) + '<СуммаПоследние3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние3месяц>'
				END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 7, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</РасчетСумм>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ФондОплатыТруда>'		
		
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ЗарплатаИнвалидов>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
		 					SPACE(6) + '<РасчетСумм>' + CHAR(10) +
								SPACE(7) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
					WHEN 4 THEN SPACE(7) + '<СуммаПоследние1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние1месяц>'
					WHEN 5 THEN SPACE(7) + '<СуммаПоследние2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние2месяц>'		
					WHEN 6 THEN SPACE(7) + '<СуммаПоследние3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние3месяц>'
				END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 8, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</РасчетСумм>'			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ЗарплатаИнвалидов>'		
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<УдельныйВесЗарплатыИнвалидов>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
							 SPACE(6) + '<УдельныйВес_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_Всего>'
				WHEN 4 THEN SPACE(6) + '<УдельныйВес_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_1месяц>'
				WHEN 5 THEN SPACE(6) + '<УдельныйВес_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_2месяц>'		
				WHEN 6 THEN SPACE(6) + '<УдельныйВес_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_3месяц>'
				END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 9, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</УдельныйВесЗарплатыИнвалидов>'
						
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_2_ДляОрганизацийУставныйКапиталСостоитИзВкладовОбщОргИнвалидов>'
	END --IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 4, DEFAULT) WHERE SUMMA <> 0) > 0

	
	--Раздел3_3
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 11, DEFAULT, DEFAULT) WHERE COL = 3 AND SUMMA <> 0) > 0 -- информ. технол.
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_3_ДляОрганизацийИТ>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовПоНКвсего>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
							WHEN 2 THEN	SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>'
							WHEN 3 THEN	SPACE(6) + '<СуммаДоходаПоПредшествующему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>' 
							WHEN 4 THEN SPACE(6) + '<СуммаДоходаПоТекущему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'
							END
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, DEFAULT) T where col in (2,3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, + SPACE(5) +'</СуммаДоходовПоНКвсего>'
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовИТизНих>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
							WHEN 2 THEN	SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' 
							WHEN 3 THEN SPACE(6) + '<СуммаДоходаПоПредшествующему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>' 
							WHEN 4 THEN SPACE(6) + '<СуммаДоходаПоТекущему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'
							END
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, DEFAULT) T where col in (2,3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СуммаДоходовИТизНих>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ДоляДоходовИТ>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
							WHEN 2 THEN	SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' 
							WHEN 3 THEN	SPACE(6) + '<ДоляДоходаПоПредшествующему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</ДоляДоходаПоПредшествующему>' 
							WHEN 4 THEN	SPACE(6) + '<ДоляДоходаПоТекущему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</ДоляДоходаПоТекущему>'
							END
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 3,DEFAULT) T where col in (2,3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ДоляДоходовИТ>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ЧисленностьРаботниковИТ>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME,CASE T.COL 
							WHEN 2 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' 
							WHEN 3 THEN	SPACE(6) + '<КоличествоЗЛпоПредшествующему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛпоПредшествующему>' 
							WHEN 4 THEN SPACE(6) + '<КоличествоЗЛпоТекущему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛпоТекущему>' 
							END
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, DEFAULT) T where col in (2,3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ЧисленностьРаботниковИТ>'


			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СведенияИзРеестраИТ>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
				WHEN 5 THEN SPACE(6) + '<ДатаЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,'\ \.\ \.\  '))) + '</ДатаЗаписиВреестре>'
				WHEN 6 THEN SPACE(6) + '<НомерЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</НомерЗаписиВреестре>'		
				END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, DEFAULT) T WHERE T.COL IN (3,5,6) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СведенияИзРеестраИТ>'
		
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_3_ДляОрганизацийИТ>'
	END	 --IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 11, DEFAULT, DEFAULT) WHERE COL = 3 AND SUMMA <> 0) > 0 

	----Раздел3_4	
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 12, DEFAULT, DEFAULT) WHERE COL = 5 AND SUMMA <> 0) > 0 -- информ. технол.
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_4_ДляОрганизацийСМИ>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СведенияПоВидуДеятельности>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
					SELECT @lcFNAME, CASE T.COL 
					WHEN 1 THEN SPACE(6) + '<НомерПП>' + LTRIM(RTRIM(T.ROW)) + '</НомерПП>'
					WHEN 2 THEN SPACE(6) + '<НаименованиеВидаЭД>' + LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</НаименованиеВидаЭД>' + CHAR(10) +
								SPACE(6) + '<КодПоОКВЭД>' + LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</КодПоОКВЭД>'
					WHEN 5 THEN SPACE(6) + '<ДоходыПоВидуЭД>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</ДоходыПоВидуЭД>'
					WHEN 6 THEN	SPACE(6) + '<ДоляДоходовПоВидуЭД>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</ДоляДоходовПоВидуЭД>'		
					END
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, DEFAULT, DEFAULT) T where T.ROW IN (1,2,3,4,5,6,7,8,9,10) and T.COL IN (1,2,5,6) ORDER BY T.ROW, t.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СведенияПоВидуДеятельности>'
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ИтогоПоВсемВидамДеятельности>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) +'</ИтогоПоВсемВидамДеятельности>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 11, 5) T ORDER BY T.COL
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СведенияИзРеестраСМИ>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 4 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
					WHEN 7 THEN SPACE(6) + '<ДатаЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,'\ \.\ \.\  '))) + '</ДатаЗаписиВреестре>'
					WHEN 8 THEN SPACE(6) + '<НомерЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</НомерЗаписиВреестре>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 12, DEFAULT) T WHERE T.COL IN (4,7,8) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СведенияИзРеестраСМИ>'
		
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_4_ДляОрганизацийСМИ>'
	END --IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 12, DEFAULT, DEFAULT) WHERE COL = 5 AND SUMMA <> 0) > 0 
	

----Раздел3_5	
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 13, DEFAULT, DEFAULT) WHERE COL = 3 AND SUMMA <> 0) > 0 -- информ. технол.
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_5_ДляОрганизацийПрименяющихУСН>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, SPACE(5) + 
				'<СуммаДоходаПоСтатье346_15НКвсего>' + CHAR(10) + 
					SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' + CHAR(10) + 
					SPACE(6) + '<СуммаДохода>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДохода>' + CHAR(10) +
				+ SPACE(5) +'</СуммаДоходаПоСтатье346_15НКвсего>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 3) T ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, SPACE(5) + 
				'<СуммаДоходаПоСтатье58ИзНих>' + CHAR(10) + 
					SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' + CHAR(10) + 
					SPACE(6) + '<СуммаДохода>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДохода>' + CHAR(10) +
				+ SPACE(5) +'</СуммаДоходаПоСтатье58ИзНих>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 2, 3) T ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, SPACE(5) + 
				'<ДоляДоходаПоСтатье58>' + CHAR(10) + 
					SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' + CHAR(10) + 
					SPACE(6) + '<ДоляДохода>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</ДоляДохода>' + CHAR(10) +
				+ SPACE(5) +'</ДоляДоходаПоСтатье58>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 3, 3) T ORDER BY T.COL

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_5_ДляОрганизацийПрименяющихУСН>'
	END -- IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 11, DEFAULT, DEFAULT) WHERE COL = 3 AND SUMMA <> 0) > 0
	
	
----Раздел3_6	
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 13, DEFAULT, DEFAULT) WHERE COL in (4,5) AND SUMMA <> 0) > 0 -- информ. технол.
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_6_ДляНекоммерческихОрганизацийПрименяющихУСН>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовВсего>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' 
					WHEN 4 THEN	SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 4, DEFAULT) T WHERE T.COL IN (3,4,5) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СуммаДоходовВсего>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовВвидеЦелевыхПоступлений>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' 
					WHEN 4 THEN	SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 5, DEFAULT) T WHERE T.COL IN (3,4,5) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СуммаДоходовВвидеЦелевыхПоступлений>'
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовВвидеГрантов>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' 
					WHEN 4 THEN	SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 6, DEFAULT) T WHERE T.COL IN (3,4,5) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СуммаДоходовВвидеГрантов>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовОтОсуществленияОпределенныхВЭД>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' 
					WHEN 4 THEN	SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 7, DEFAULT) T WHERE T.COL IN (3,4,5) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СуммаДоходовОтОсуществленияОпределенныхВЭД>'
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ДоляДоходов>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' 
					WHEN 4 THEN SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 8, DEFAULT) T WHERE T.COL IN (3,4,5) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ДоляДоходов>'
	

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_6_ДляНекоммерческихОрганизацийПрименяющихУСН>'
	END


	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '</Раздел3РасчетНаПравоПримененияПониженногоТарифа2014>'

END --	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 10, DEFAULT, 3) WHERE SUMMA <> 0) > 0 -- инвалиды


---РАЗДЕЛ_4 Стр.12
CREATE TABLE #DONACHISL (
	LINK INT,OSN int,CODE_OSN INT, YEAR_D VARCHAR(4), MON int, SUM_STR_14 NUMERIC(18,2), SUM_STR_LIM_14 NUMERIC(18,2), SUM_STR NUMERIC(18,2), SUM_STR_LIM NUMERIC(18,2), SUM_NAK NUMERIC(18,2), SUM_STR_D1 NUMERIC(18,2), SUM_STR_D2 NUMERIC(18,2), SUM_STR_D2_1 NUMERIC(18,2), SUM_MED_STR NUMERIC(18,2))

CREATE TABLE #TAB14 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
INSERT INTO #TAB14 (ROW_CODE, COL, SUMMA, STR_VAL)
SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

INSERT INTO #DONACHISL (OSN,CODE_OSN, YEAR_D, MON,SUM_STR_14, SUM_STR_LIM_14, SUM_STR, SUM_STR_LIM, SUM_NAK ,SUM_STR_D1 , SUM_STR_D2, SUM_STR_D2_1, SUM_MED_STR)
SELECT DISTINCT 
	OSN = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 2 AND T.ROW_CODE = T14.ROW_CODE),
	CODE_OSN = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 3 AND T.ROW_CODE = T14.ROW_CODE),
	YEAR_D = (SELECT TOP 1 STR_VAL FROM #TAB14 T WHERE T.COL = 4 AND T.ROW_CODE = T14.ROW_CODE),
	MON = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 5 AND T.ROW_CODE = T14.ROW_CODE),
	SUM_STR_14 = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 6 AND T.ROW_CODE = T14.ROW_CODE), 
	SUM_STR_LIM_14 = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 7 AND T.ROW_CODE = T14.ROW_CODE),
	SUM_STR = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 8 AND T.ROW_CODE = T14.ROW_CODE),
	SUM_STR_LIM = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 9 AND T.ROW_CODE = T14.ROW_CODE),
	SUM_NAK = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 10 AND T.ROW_CODE = T14.ROW_CODE),
	SUM_STR_D1 = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 11 AND T.ROW_CODE = T14.ROW_CODE),
	SUM_STR_D2 = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 12 AND T.ROW_CODE = T14.ROW_CODE),
	SUM_STR_D2_1 = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 13 AND T.ROW_CODE = T14.ROW_CODE),
	SUM_MED_STR = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 14 AND T.ROW_CODE = T14.ROW_CODE)
FROM
	#TAB14 T14

DROP TABLE #TAB14


--Проставить номера попорядку
DECLARE @NEXT_NUM1 INT
SET @NEXT_NUM1 = 0
UPDATE #DONACHISL SET @NEXT_NUM1 = @NEXT_NUM1 + 1, LINK = @NEXT_NUM1

--IF (SELECT COUNT(*) FROM #DONACHISL) > 0 -- инвалиды
--	OR (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 13, DEFAULT, DEFAULT) WHERE COL = 4 AND SUMMA <> 0) > 0 -- информ. технол.
--BEGIN


	IF (SELECT COUNT(*) FROM #DONACHISL) > 0 -- инвалиды
	BEGIN
	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<Раздел4СуммыДоначисленныхСтраховыхВзносов2014>'

		UNION ALL SELECT @lcFNAME, 
			SPACE(3) + '<СуммаДоначисленныхВзносовЗаПериодНачинаяС2014>' + CHAR(10) +
				SPACE(4) + '<НомерПП>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(LINK,0)))) + '</НомерПП>' + CHAR(10) +			
				SPACE(4) + '<ОснованиеДляДоначисления>' + LTRIM(RTRIM(CONVERT(VARCHAR(1),ISNULL(OSN,0)))) + '</ОснованиеДляДоначисления>' + CHAR(10) +	
				SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(YEAR_D,''))) + '</Год>' + CHAR(10) + 		
				SPACE(4) + '<Месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(2),ISNULL(MON,0)))) + '</Месяц>' + CHAR(10) + 	
				SPACE(4) + '<СуммаДоначисленныхВзносовОПС2014всего>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_14,0)))) + '</СуммаДоначисленныхВзносовОПС2014всего>' + CHAR(10) + 
				SPACE(4) + '<СуммаДоначисленныхВзносовОПС2014превыщающие>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_LIM_14,0)))) + '</СуммаДоначисленныхВзносовОПС2014превыщающие>' + CHAR(10) + 
				SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховуюВсего>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR,0)))) + '</СуммаДоначисленныхВзносовНаСтраховуюВсего>' + CHAR(10) + 
				SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховуюПревышающие>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_LIM,0)))) + '</СуммаДоначисленныхВзносовНаСтраховуюПревышающие>' + CHAR(10) + 
				SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_NAK,0)))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10) +
				SPACE(4) + '<СтраховыхДоначисленныхВзносовПоДопТарифуЧ1>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_D1,0)))) + '</СтраховыхДоначисленныхВзносовПоДопТарифуЧ1>' + CHAR(10) +
				SPACE(4) + '<СтраховыхДоначисленныхВзносовПоДопТарифуЧ2>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_D2,0)))) + '</СтраховыхДоначисленныхВзносовПоДопТарифуЧ2>' + CHAR(10) +								
				SPACE(4) + '<СтраховыхДоначисленныхВзносовПоДопТарифуЧ2_1>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_D2_1,0))))  + '</СтраховыхДоначисленныхВзносовПоДопТарифуЧ2_1>' + CHAR(10) +								
				SPACE(4) + '<СтраховыеВзносыОМС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_MED_STR,0)))) + '</СтраховыеВзносыОМС>' + CHAR(10) +	
				/*SPACE(4) + '<СуммаДоначисленныхСтраховыхВзносов>' + CHAR(10) +
					SPACE(5) + '<ОПСстраховаяЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR,0)))) + '</ОПСстраховаяЧасть>' + CHAR(10) + 										
					SPACE(5) + '<ОПСстраховаяЧастьСвышеПределаБазы>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_LIM,0)))) + '</ОПСстраховаяЧастьСвышеПределаБазы>' + CHAR(10) + 										
					SPACE(5) + '<ОПСнакопительнаяЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_NAK,0)))) + '</ОПСнакопительнаяЧасть>' + CHAR(10) +
					SPACE(5) + '<ОПСстраховаяЧастьПоДопТар1>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_D1,0)))) + '</ОПСстраховаяЧастьПоДопТар1>' + CHAR(10) +
					SPACE(5) + '<ОПСстраховаяЧастьПоДопТар2>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_D2,0)))) + '</ОПСстраховаяЧастьПоДопТар2>' + CHAR(10) +
					SPACE(5) + '<СтраховыеВзносыОМС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_MED_STR,0)))) + '</СтраховыеВзносыОМС>' + CHAR(10) +	
				SPACE(4) + '</СуммаДоначисленныхСтраховыхВзносов>' + CHAR(10) +
			*/SPACE(3) + '</СуммаДоначисленныхВзносовЗаПериодНачинаяС2014>'
		FROM #DONACHISL				


		UNION ALL SELECT @lcFNAME,
			SPACE(3) + '<ИтогоДоначисленоНачинаяС2014>' + CHAR(10) +
				SPACE(4) + '<СуммаДоначисленныхВзносовОПС2014всего>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_14,0))))) + '</СуммаДоначисленныхВзносовОПС2014всего>' + CHAR(10) + 
				SPACE(4) + '<СуммаДоначисленныхВзносовОПС2014превыщающие>' +LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_LIM_14,0))))) + '</СуммаДоначисленныхВзносовОПС2014превыщающие>' + CHAR(10) + 
				SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховуюВсего>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR,0))))) + '</СуммаДоначисленныхВзносовНаСтраховуюВсего>' + CHAR(10) + 
				SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховуюПревышающие>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_LIM,0))))) + '</СуммаДоначисленныхВзносовНаСтраховуюПревышающие>' + CHAR(10) + 
				SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_NAK,0))))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10) +
				SPACE(4) + '<СтраховыхДоначисленныхВзносовПоДопТарифуЧ1>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_D1,0))))) + '</СтраховыхДоначисленныхВзносовПоДопТарифуЧ1>' + CHAR(10) +
				SPACE(4) + '<СтраховыхДоначисленныхВзносовПоДопТарифуЧ2>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_D2,0))))) + '</СтраховыхДоначисленныхВзносовПоДопТарифуЧ2>' + CHAR(10) +								
				SPACE(4) + '<СтраховыхДоначисленныхВзносовПоДопТарифуЧ2_1>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_D2_1,0))))) + '</СтраховыхДоначисленныхВзносовПоДопТарифуЧ2_1>' + CHAR(10) +								
				SPACE(4) + '<СтраховыеВзносыОМС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_MED_STR,0))))) + '</СтраховыеВзносыОМС>' + CHAR(10) +	
			SPACE(3) + '</ИтогоДоначисленоНачинаяС2014>'
		
		
			/*SPACE(3) + '<ИтогоДоначислено>' + CHAR(10) +
					SPACE(4) + '<ОПСстраховаяЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR,0))))) + '</ОПСстраховаяЧасть>' + CHAR(10) +			
					SPACE(4) + '<ОПСстраховаяЧастьСвышеПределаБазы>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_LIM,0))))) + '</ОПСстраховаяЧастьСвышеПределаБазы>' + CHAR(10) + 										
					SPACE(4) + '<ОПСнакопительнаяЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_NAK,0))))) + '</ОПСнакопительнаяЧасть>' + CHAR(10) +
					SPACE(4) + '<ОПСстраховаяЧастьПоДопТар1>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_D1,0))))) + '</ОПСстраховаяЧастьПоДопТар1>' + CHAR(10) +
					SPACE(4) + '<ОПСстраховаяЧастьПоДопТар2>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_D2,0))))) + '</ОПСстраховаяЧастьПоДопТар2>' + CHAR(10) +
					SPACE(4) + '<СтраховыеВзносыОМС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_MED_STR,0))))) + '</СтраховыеВзносыОМС>' + CHAR(10) +
			SPACE(3) + '</ИтогоДоначислено>' */
		FROM #DONACHISL	

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '</Раздел4СуммыДоначисленныхСтраховыхВзносов2014>'	
	END

--end



---РАЗДЕЛ_5 Стр.13_1
CREATE TABLE #STUD (
	LINK INT, FIO VARCHAR(254), FIO2 VARCHAR(254), NUM_SPR1 VARCHAR(30), DATE_SPR1 VARCHAR(10),NUM_SPR2 VARCHAR(30), DATE_SPR2 VARCHAR(10), 
	SM_ALL 	NUMERIC(18,2), SM1 NUMERIC(18,2), SM2 NUMERIC(18,2), SM3 NUMERIC(18,2) )

CREATE TABLE #TAB15 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
INSERT INTO #TAB15 (ROW_CODE, COL, SUMMA, STR_VAL)
SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

INSERT INTO #STUD (FIO2, NUM_SPR1, DATE_SPR1,NUM_SPR2, DATE_SPR2, 
	SM_ALL, SM1, SM2, SM3 )
SELECT DISTINCT 
	FIO2 = (SELECT TOP 1 REPLACE(STR_VAL,SPACE(1), ', ') FROM #TAB15 T WHERE T.COL = 2 AND T.ROW_CODE = T15.ROW_CODE),
	NUM_SPR1 = (SELECT TOP 1 LEFT(LTRIM(RTRIM(dbo.SA_GET_WORD_NUM(STR_VAL,1,' '))),30) FROM #TAB15 T WHERE T.COL = 3 AND T.ROW_CODE = T15.ROW_CODE),
	DATE_SPR1 = (SELECT TOP 1 LEFT(LTRIM(RTRIM(dbo.SA_GET_WORD_NUM(STR_VAL,2,' '))),10) FROM #TAB15 T WHERE T.COL = 3 AND T.ROW_CODE = T15.ROW_CODE),
	NUM_SPR2 = (SELECT TOP 1 LEFT(LTRIM(RTRIM(dbo.SA_GET_WORD_NUM(STR_VAL,1,' '))),30) FROM #TAB15 T WHERE T.COL = 4 AND T.ROW_CODE = T15.ROW_CODE),
	DATE_SPR2 = (SELECT TOP 1 LEFT(LTRIM(RTRIM(dbo.SA_GET_WORD_NUM(STR_VAL,2,' '))),10) FROM #TAB15 T WHERE T.COL = 4 AND T.ROW_CODE = T15.ROW_CODE),
	SM_ALL = (SELECT TOP 1 SUMMA FROM #TAB15 T WHERE T.COL = 5 AND T.ROW_CODE = T15.ROW_CODE),
	SM1 = (SELECT TOP 1 SUMMA FROM #TAB15 T WHERE T.COL = 6 AND T.ROW_CODE = T15.ROW_CODE),
	SM2 = (SELECT TOP 1 SUMMA FROM #TAB15 T WHERE T.COL = 7 AND T.ROW_CODE = T15.ROW_CODE),
	SM3 = (SELECT TOP 1 SUMMA FROM #TAB15 T WHERE T.COL = 8 AND T.ROW_CODE = T15.ROW_CODE)
FROM
	#TAB15 T15

DROP TABLE #TAB15

--Проставить номера попорядку
DECLARE @NEXT_NUM2 INT
SET @NEXT_NUM2 = 0
UPDATE #STUD SET @NEXT_NUM2 = @NEXT_NUM2 + 1, LINK = @NEXT_NUM2

--количество обучающихся
DECLARE @COUNT_STUD INT
set @COUNT_STUD = (select count(*) from #STUD ) 


--IF (SELECT COUNT(*) FROM #STUD) > 0 -- студенты
--	OR (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 15, DEFAULT, DEFAULT) WHERE COL = 5 AND SUMMA <> 0) > 0 -- оплата студентам
--BEGIN

IF (SELECT COUNT(*) FROM #STUD) > 0 -- студенты
BEGIN
	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<Раздел5СведенияОВыплатахВпользуОбучающихся2014>'
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<КоличествоОбучающихся>' + LTRIM(RTRIM(CONVERT(VARCHAR(5),ISNULL(@COUNT_STUD,0)))) + '</КоличествоОбучающихся>' 			
		UNION ALL SELECT @lcFNAME, 
			SPACE(4) + '<СведенияОбОбучающемся>' + CHAR(10) +		
				SPACE(5) + '<НомерПП>' + LTRIM(RTRIM(CONVERT(VARCHAR(5),ISNULL(link,0)))) + '</НомерПП>' + CHAR(10) + 		
				SPACE(5) + '<ФИО>' + CHAR(10) + 
					SPACE(6) + '<Фамилия>' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,1,','),'')))) + '</Фамилия>' + CHAR(10) + 		
					SPACE(6) + '<Имя>' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,2,','),'')))) + '</Имя>' + CHAR(10) + 		
					SPACE(6) + '<Отчество>' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,3,','),'')))) + '</Отчество>' + CHAR(10) + 										
				SPACE(5) + '</ФИО>' + CHAR(10) + 
				SPACE(5) + '<НомерСправкиОчленствеВстудОтряде>' + LTRIM(RTRIM(ISNULL(NUM_SPR1,''))) + '</НомерСправкиОчленствеВстудОтряде>' + CHAR(10) + 										
				SPACE(5) + '<ДатаВыдачиСправкиОчленствеВстудОтряде>' + LTRIM(RTRIM(ISNULL(DATE_SPR1,''))) + '</ДатаВыдачиСправкиОчленствеВстудОтряде>' + CHAR(10) + 	
				SPACE(5) + '<НомерСправкиОбОчномОбучении>' + LTRIM(RTRIM(ISNULL(NUM_SPR2,''))) + '</НомерСправкиОбОчномОбучении>' + CHAR(10) + 										
				SPACE(5) + '<ДатаВыдачиСправкиОбОчномОбучении>' + LTRIM(RTRIM(ISNULL(DATE_SPR2,''))) + '</ДатаВыдачиСправкиОбОчномОбучении>' + CHAR(10) + 										
				SPACE(5) + '<СуммыВыплатИвознаграждений>' + CHAR(10) + 
					SPACE(6) + '<СуммаВсегоСначалаРасчетногоПериода>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM_ALL,0)))) + '</СуммаВсегоСначалаРасчетногоПериода>' + CHAR(10) +
					SPACE(6) + '<СуммаПоследние1месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM1,0)))) + '</СуммаПоследние1месяц>' + CHAR(10) +	
					SPACE(6) + '<СуммаПоследние2месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM2,0)))) + '</СуммаПоследние2месяц>' + CHAR(10) +	
					SPACE(6) + '<СуммаПоследние3месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM3,0)))) + '</СуммаПоследние3месяц>' + CHAR(10) +	
				SPACE(5) + '</СуммыВыплатИвознаграждений>' + CHAR(10) + 
			SPACE(4) + '</СведенияОбОбучающемся>'
		FROM #STUD				


		UNION ALL SELECT @lcFNAME, 
			SPACE(4) + '<ИтогоВыплат>' + CHAR(10) +
					SPACE(5) + '<СуммаВсегоСначалаРасчетногоПериода>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SM_ALL,0))))) + '</СуммаВсегоСначалаРасчетногоПериода>' + CHAR(10) +			
					SPACE(5) + '<СуммаПоследние1месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SM1,0))))) + '</СуммаПоследние1месяц>' + CHAR(10) +
					SPACE(5) + '<СуммаПоследние2месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SM2,0))))) + '</СуммаПоследние2месяц>' + CHAR(10) +
					SPACE(5) + '<СуммаПоследние3месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SM3,0))))) + '</СуммаПоследние3месяц>' + CHAR(10) +
			SPACE(4) + '</ИтогоВыплат>' 
		FROM #STUD	

	if (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 16, 1, DEFAULT) WHERE COL = 3 and str_VAL <> '' ) > 0 
	begin
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<СведенияИзРеестраМДОО>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 2 THEN SPACE(5) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
								SPACE(5) + '<РеквизитыЗаписиВреестре>'
						WHEN 3 THEN SPACE(6) + '<ДатаЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</ДатаЗаписиВреестре>'
						WHEN 4 THEN	SPACE(6) + '<НомерЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</НомерЗаписиВреестре>' + CHAR(10) +	
								SPACE(5) + '</РеквизитыЗаписиВреестре>'
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, 1, DEFAULT) T WHERE T.COL IN (2,3,4) ORDER BY T.COL
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</СведенияИзРеестраМДОО>'
	end

	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '</Раздел5СведенияОВыплатахВпользуОбучающихся2014>'	
END

--end

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) 
SELECT @lcFNAME, 
	SPACE(3) + '<ЛицоПодтверждающееСведения>1</ЛицоПодтверждающееСведения>' + CHAR(10) +
	SPACE(3) + '<ФИОлицаПодтверждающегоСведения>' + CHAR(10) +
		SPACE(4) + '<Фамилия>' + UPPER(LTRIM(RTRIM(ISNULL(O.FM,'')))) + '</Фамилия>' + CHAR(10) +
		SPACE(4) + '<Имя>' + UPPER(LTRIM(RTRIM(ISNULL(O.IM,'')))) + '</Имя>' + CHAR(10) +
		SPACE(4) + '<Отчество>' + UPPER(LTRIM(RTRIM(ISNULL(O.OT,'')))) + '</Отчество>' + CHAR(10) +
	SPACE(3) + '</ФИОлицаПодтверждающегоСведения>' + CHAR(10) +
	SPACE(3) + '<НаименованиеОрганизацииПредставителя>' + UPPER(LTRIM(RTRIM(ISNULL(d.FULL_NAME,'')))) + '</НаименованиеОрганизацииПредставителя>' + CHAR(10) +
	SPACE(3) + '<ДокументПодтверждающийПолномочияПредставителя>' + CHAR(10) +
		SPACE(4) + '<НаименованиеУдостоверяющего>' + UPPER(LTRIM(RTRIM(ISNULL(F.NAME,'')))) + '</НаименованиеУдостоверяющего>' + CHAR(10) +
		SPACE(4) + '<СерияРимскиеЦифры>' + case when f.code='21' then substring(p.doc_num,1,2) else ' ' end + '</СерияРимскиеЦифры>' + CHAR(10) +
		SPACE(4) + '<СерияРусскиеБуквы>' + case when f.code='21' then substring(p.doc_num,4,2) else ' ' end + '</СерияРусскиеБуквы>' + CHAR(10) +
		SPACE(4) + '<НомерУдостоверяющего>' + LTRIM(RTRIM(case when f.code='21' then substring(p.doc_num,7,7) else ' ' end)) + '</НомерУдостоверяющего>' + CHAR(10) +
		SPACE(4) + '<ДатаВыдачи>' + LTRIM(RTRIM(ISNULL(convert(varchar(10),p.doc_date,104),''))) + '</ДатаВыдачи>' + CHAR(10) +
		SPACE(4) + '<КемВыдан>' + UPPER(LTRIM(RTRIM(ISNULL(p.DOC_WHOM,'')))) + '</КемВыдан>' + CHAR(10) +
	SPACE(3) + '</ДокументПодтверждающийПолномочияПредставителя>' 
FROM dbo.GetOtvFaceData(@LINK_DEP, 'Руководитель') O
inner join EMPL e on e.link = o.link_empl
inner join PERSON p on p.link = e.pers_link
inner join FACE_DOCUMENT f on f.link = p.doc_link
inner join DICTIONARY_DEPARTMENT d on d.link = @LINK_DEP


INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) 
SELECT @lcFNAME, SPACE(3) + '<ДатаЗаполнения>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),@modify_date,104),''))) + '</ДатаЗаполнения>'

--Заверешение
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(2) + '</РАСЧЕТ_ПО_СТРАХОВЫМ_ВЗНОСАМ_НА_ОПС_И_ОМС_ПЛАТЕЛЬЩИКАМИ_ПРОИЗВОДЯЩИМИ_ВЫПЛАТЫ_ФЛ_2014>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(1) + '</ПачкаВходящихДокументов>'
	UNION ALL SELECT @lcFNAME, SPACE(0) + '</ФайлПФР>'	


/*-----------------------------------------------------------------------------------------------*/


--Раздел_6 


--ОПИСЬ

CREATE TABLE #OPIS (
	LINK INT, [TYPE] INT, NOM_PP INT, NOM_PACH VARCHAR(10), SUM_BASE NUMERIC(18,2), SUM_STR NUMERIC(18,2), PERS_CNT NUMERIC(5), DATE_DOC VARCHAR(10), 
	PER VARCHAR(1), YEAR_BEGIN VARCHAR(4), PER_EDT VARCHAR(1), YEAR_EDT VARCHAR(4), F_NAME varchar(100), link_doc int)

CREATE TABLE #TAB16 (ROW_CODE VARCHAR(10), COL INT, SUMMA NUMERIC(18), SUMMA2 NUMERIC(18,2), STR_VAL VARCHAR(254))
INSERT INTO #TAB16 (ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL)
SELECT ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, DEFAULT, DEFAULT) T WHERE T.COL >= 3 ORDER BY T.COL

CREATE TABLE #TAB17 (ROW_CODE VARCHAR(10), COL INT, SUMMA NUMERIC(18), SUMMA2 NUMERIC(18,2), STR_VAL VARCHAR(254))
INSERT INTO #TAB17 (ROW_CODE, COL, SUMMA,SUMMA2, STR_VAL)
SELECT ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, DEFAULT, DEFAULT) T WHERE T.COL >= 3 ORDER BY T.COL


INSERT INTO #OPIS ([TYPE], NOM_PACH, SUM_BASE, SUM_STR, PERS_CNT, DATE_DOC,	PER, YEAR_BEGIN,F_NAME, link_doc)
SELECT DISTINCT 
	[TYPE] = (SELECT TOP 1 summa FROM #TAB16 T WHERE T.COL = 8 AND T.ROW_CODE = T16.ROW_CODE),
	NOM_PACH = (SELECT TOP 1 LTRIM(RTRIM(ROW_CODE)) FROM #TAB16 T WHERE T.COL = 3 AND T.ROW_CODE = T16.ROW_CODE),
	SUM_BASE = (SELECT TOP 1 SUMMA2 FROM #TAB16 T WHERE T.COL = 3 AND T.ROW_CODE = T16.ROW_CODE),
	SUM_STR = (SELECT TOP 1 SUMMA2 FROM #TAB16 T WHERE T.COL = 4 AND T.ROW_CODE = T16.ROW_CODE),
	PERS_CNT = (SELECT TOP 1 SUMMA FROM #TAB16 T WHERE T.COL = 5 AND T.ROW_CODE = T16.ROW_CODE),
	DATE_DOC = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB16 T WHERE T.COL = 7 AND T.ROW_CODE = T16.ROW_CODE),
	PER = (SELECT TOP 1 LTRIM(RTRIM(str(SUMMA))) FROM #TAB16 T WHERE T.COL = 9 AND T.ROW_CODE = T16.ROW_CODE),
	YEAR_BEGIN = (SELECT TOP 1 LTRIM(RTRIM(str(SUMMA))) FROM #TAB16 T WHERE T.COL = 10 AND T.ROW_CODE = T16.ROW_CODE),
	F_NAME = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB16 T WHERE T.COL = 6 AND T.ROW_CODE = T16.ROW_CODE),
	LINK_DOC = (SELECT TOP 1 SUMMA FROM #TAB16 T WHERE T.COL = 11 AND T.ROW_CODE = T16.ROW_CODE)
FROM
	#TAB16 T16

INSERT INTO #OPIS ([TYPE], NOM_PACH, SUM_BASE, SUM_STR, PERS_CNT, DATE_DOC,	PER, YEAR_BEGIN, PER_EDT, YEAR_EDT,F_NAME, link_doc)
SELECT DISTINCT 
	[TYPE] = (SELECT TOP 1 summa FROM #TAB17 T WHERE T.COL = 11 AND T.ROW_CODE = T17.ROW_CODE),
	NOM_PACH = (SELECT TOP 1 LTRIM(RTRIM(ROW_CODE)) FROM #TAB17 T WHERE T.COL = 3 AND T.ROW_CODE = T17.ROW_CODE),
	SUM_BASE = (SELECT TOP 1 SUMMA2 FROM #TAB17 T WHERE T.COL = 14 AND T.ROW_CODE = T17.ROW_CODE),
	SUM_STR = (SELECT TOP 1 SUMMA2 FROM #TAB17 T WHERE T.COL = 15 AND T.ROW_CODE = T17.ROW_CODE),
	PERS_CNT = (SELECT TOP 1 SUMMA FROM #TAB17 T WHERE T.COL = 8 AND T.ROW_CODE = T17.ROW_CODE),
	DATE_DOC = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 10 AND T.ROW_CODE = T17.ROW_CODE),
	PER = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 12 AND T.ROW_CODE = T17.ROW_CODE),
	YEAR_BEGIN = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 13 AND T.ROW_CODE = T17.ROW_CODE),
	PER_EDT = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 3 AND T.ROW_CODE = T17.ROW_CODE),
	YEAR_EDT = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 4 AND T.ROW_CODE = T17.ROW_CODE),
	F_NAME = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 9 AND T.ROW_CODE = T17.ROW_CODE),
	LINK_DOC = (SELECT TOP 1 SUMMA FROM #TAB17 T WHERE T.COL = 16 AND T.ROW_CODE = T17.ROW_CODE)
FROM
	#TAB17 T17	



DROP TABLE #TAB16
DROP TABLE #TAB17


--Проставить номера попорядку
DECLARE @NEXT_NUM3 INT
SET @NEXT_NUM3 = 0
UPDATE #OPIS SET @NEXT_NUM3 = @NEXT_NUM3 + 1, LINK = @NEXT_NUM3

DECLARE @NEXT_NUM4 INT
SET @NEXT_NUM4 = 0
UPDATE #OPIS SET @NEXT_NUM4 = @NEXT_NUM4 + 1, NOM_PP = @NEXT_NUM4
WHERE TYPE = 1


SET @NEXT_NUM4 = 0
UPDATE #OPIS SET @NEXT_NUM4 = @NEXT_NUM4 + 1, NOM_PP = @NEXT_NUM4
WHERE TYPE = 2


---------------------------------------------------------------
----------------------------------------------------------------
DECLARE @Cur3 CURSOR, @Cur4 CURSOR, @LINK_OP INT, @NGROUP int /*Номер пачки*/, @lcF_NAME varchar(254) /*наименование файла*/,
	@NOM_PP INT, @TYP_D varchar(20), @DATE_DOC VARCHAR(10),@SUM_BASE NUMERIC(18,2), @SUM_STR NUMERIC(18,2), @PERS_CNT NUMERIC(5),
	@PER VARCHAR(1), @YEAR_BEGIN VARCHAR(4), @PER_EDT VARCHAR(1), @YEAR_EDT VARCHAR(4)


	CREATE TABLE #TAB61 (LINK INT , FM VARCHAR(100), IM VARCHAR(100), OT VARCHAR(100), SNILS VARCHAR(14), CODE VARCHAR(14), SNILS1 VARCHAR(14), [TYPE] TINYINT , NGROUP VARCHAR(10), FNAME varchar(80), doc_date varchar(10))
	INSERT INTO #TAB61 (CODE, SNILS, FM, IM, OT, SNILS1, [TYPE], NGROUP, FNAME, doc_date)
	exec dbo.RSA_RSV_1_PERS_UCH_SZV @Begin_Date , @END_Date , @LINK_DEP, 0 , @Link


	SET @NEXT_NUM3 = 0
	UPDATE #TAB61 SET @NEXT_NUM3 = @NEXT_NUM3 + 1, LINK = @NEXT_NUM3

	CREATE TABLE #TAB64 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18), SUMMA2 NUMERIC(18,2), STR_VAL VARCHAR(254))
	INSERT INTO #TAB64 (ROW_CODE, COL, SUMMA,SUMMA2, STR_VAL)
	SELECT ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 18, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

	CREATE TABLE #P_64 (
								LINK INT, [TYPE] varchar(15), NOM_PP INT, SNILS VARCHAR(14), CODE_STR int, CODE_KAT varchar(5), INSUR NUMERIC(18,2), B_BEF NUMERIC(18,2), GB_BEF NUMERIC(18,2),B_AFT NUMERIC(18,2),
								PER VARCHAR(1), YEAR_BEGIN VARCHAR(4), PER_EDT VARCHAR(1), YEAR_EDT VARCHAR(4), FM varchar(100), IM varchar(100), OT varchar(100),
								k_PER_EDT1 VARCHAR(1), k_YEAR_EDT1 VARCHAR(4), k_INSUR1 NUMERIC(18,2), k_INSUR_1 NUMERIC(18,2), k_GAIN1 NUMERIC(18,2),
								k_PER_EDT2 VARCHAR(1), k_YEAR_EDT2 VARCHAR(4), k_INSUR2 NUMERIC(18,2), k_INSUR_2 NUMERIC(18,2), k_GAIN2 NUMERIC(18,2),
								k_PER_EDT3 VARCHAR(1), k_YEAR_EDT3 VARCHAR(4), k_INSUR3 NUMERIC(18,2), k_INSUR_3 NUMERIC(18,2), k_GAIN3 NUMERIC(18,2),
								k_PER_EDT4 VARCHAR(1), k_YEAR_EDT4 VARCHAR(4), k_INSUR4 NUMERIC(18,2), k_INSUR_4 NUMERIC(18,2), k_GAIN4 NUMERIC(18,2),
								k_PER_EDT5 VARCHAR(1), k_YEAR_EDT5 VARCHAR(4), k_INSUR5 NUMERIC(18,2), k_INSUR_5 NUMERIC(18,2), k_GAIN5 NUMERIC(18,2),SUM_VZNOS NUMERIC(18,2))
	
	INSERT INTO #P_64 (/*LINK,*/ [TYPE], NOM_PP,SNILS,CODE_STR,CODE_KAT,INSUR,B_BEF, GB_BEF, B_AFT,
							PER,YEAR_BEGIN,PER_EDT,YEAR_EDT,FM,IM,OT,
							k_PER_EDT1,k_YEAR_EDT1,k_INSUR1,k_INSUR_1,k_GAIN1,k_PER_EDT2,k_YEAR_EDT2,k_INSUR2,k_INSUR_2,k_GAIN2,
							k_PER_EDT3,k_YEAR_EDT3,k_INSUR3,k_INSUR_3,k_GAIN3,k_PER_EDT4,k_YEAR_EDT4,k_INSUR4,k_INSUR_4,k_GAIN4,
							k_PER_EDT5,k_YEAR_EDT5,k_INSUR5,k_INSUR_5,k_GAIN5,SUM_VZNOS)
	SELECT 
				---LINK = dEnse_RANK() OVER (ORDER BY  [type],snils ),
				[TYPE],
				NOM_PP = ROW_NUMBER() OVER (PARTITION BY SNILS, [TYPE] ORDER BY CODE_STR),
				SNILS,CODE_STR,CODE_KAT,INSUR,B_BEF, GB_BEF, B_AFT,
							PER,YEAR_BEGIN,PER_EDT,YEAR_EDT,FM,IM,OT,
							k_PER_EDT1,k_YEAR_EDT1,k_INSUR1,k_INSUR_1,k_GAIN1,k_PER_EDT2,k_YEAR_EDT2,k_INSUR2,k_INSUR_2,k_GAIN2,
							k_PER_EDT3,k_YEAR_EDT3,k_INSUR3,k_INSUR_3,k_GAIN3,k_PER_EDT4,k_YEAR_EDT4,k_INSUR4,k_INSUR_4,k_GAIN4,
							k_PER_EDT5,k_YEAR_EDT5,k_INSUR5,k_INSUR_5,k_GAIN5,SUM_VZNOS

		FROM
	(
	SELECT DISTINCT 
		[TYPE] = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 12 AND T.ROW_CODE = T64.ROW_CODE),
		SNILS = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 2 AND T.ROW_CODE = T64.ROW_CODE),
		CODE_STR = convert(int, (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 4 AND T.ROW_CODE = T64.ROW_CODE)),
		CODE_KAT = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 5 AND T.ROW_CODE = T64.ROW_CODE),
		INSUR = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 6 AND T.ROW_CODE = T64.ROW_CODE),
		B_BEF = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 7 AND T.ROW_CODE = T64.ROW_CODE ),
		GB_BEF = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 8 AND T.ROW_CODE = T64.ROW_CODE ),
		B_AFT = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 9 AND T.ROW_CODE = T64.ROW_CODE ),
		PER = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL))FROM #TAB64 T WHERE T.COL = 10 AND T.ROW_CODE = T64.ROW_CODE),
		YEAR_BEGIN = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 11 AND T.ROW_CODE = T64.ROW_CODE),
		PER_EDT = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 13 AND T.ROW_CODE = T64.ROW_CODE),
		YEAR_EDT = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 14 AND T.ROW_CODE = T64.ROW_CODE),
		FM= (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 16 AND T.ROW_CODE = T64.ROW_CODE),
		IM= (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 17 AND T.ROW_CODE = T64.ROW_CODE),
		OT= (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 18 AND T.ROW_CODE = T64.ROW_CODE),
		k_PER_EDT1 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 19 AND T.ROW_CODE = T64.ROW_CODE ),
		k_YEAR_EDT1 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 20 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR1 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 21 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR_1 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 22 AND T.ROW_CODE = T64.ROW_CODE ),
		k_GAIN1 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 23 AND T.ROW_CODE = T64.ROW_CODE),
		
		k_PER_EDT2= (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 24 AND T.ROW_CODE = T64.ROW_CODE ),
		k_YEAR_EDT2 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA)))FROM #TAB64 T WHERE T.COL = 25 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR2 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 26 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR_2 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 27 AND T.ROW_CODE = T64.ROW_CODE ),
		k_GAIN2 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 28 AND T.ROW_CODE = T64.ROW_CODE),
		k_PER_EDT3 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 29 AND T.ROW_CODE = T64.ROW_CODE ),
		k_YEAR_EDT3 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 30 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR3 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 31 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR_3 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 32 AND T.ROW_CODE = T64.ROW_CODE ),
		k_GAIN3 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 33 AND T.ROW_CODE = T64.ROW_CODE),
		k_PER_EDT4 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 34 AND T.ROW_CODE = T64.ROW_CODE ),
		k_YEAR_EDT4 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 35 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR4 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 36 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR_4 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 37 AND T.ROW_CODE = T64.ROW_CODE ),
		k_GAIN4 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 38 AND T.ROW_CODE = T64.ROW_CODE),
		k_PER_EDT5 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 39 AND T.ROW_CODE = T64.ROW_CODE ),
		k_YEAR_EDT5 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 40 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR5 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 41 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR_5 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 42 AND T.ROW_CODE = T64.ROW_CODE ),
		k_GAIN5 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 43 AND T.ROW_CODE = T64.ROW_CODE),
		SUM_VZNOS = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 44 AND T.ROW_CODE = T64.ROW_CODE)
		
	FROM
	#TAB64 T64	
		) T	


	SET @NEXT_NUM3 = 0
	UPDATE  p  SET  LINK = (select top 1 link from #TAB61 where ltrim(rtrim(SNILS)) = ltrim(rtrim(p.SNILS)) 
																						 and  ltrim(rtrim(FM)) = ltrim(rtrim(p.FM)) 
																						 and ltrim(rtrim(IM)) = ltrim(rtrim(p.IM))	 and ltrim(rtrim(OT)) = ltrim(rtrim(p.OT))
																						 and [type] = (case p.[type] when 'ИСХОДНАЯ' then 1 when 'КОРРЕКТИРУЮЩАЯ' then 2 else 3 end))
	FROM #P_64 p   



--DELETE FROM #P_64 WHERE ISNULL(INSUR,0) = 0

	CREATE TABLE #PACHKA_64 (
								LINK INT, [TYPE] varchar(15), NOM_PP INT, SNILS VARCHAR(14), CODE_STR int, CODE_KAT varchar(5), INSUR NUMERIC(18,2), B_BEF NUMERIC(18,2), GB_BEF NUMERIC(18,2),B_AFT NUMERIC(18,2),
								PER VARCHAR(1), YEAR_BEGIN VARCHAR(4), PER_EDT VARCHAR(1), YEAR_EDT VARCHAR(4), FM varchar(100), IM varchar(100), OT varchar(100),
								k_PER_EDT1 VARCHAR(1), k_YEAR_EDT1 VARCHAR(4), k_INSUR1 NUMERIC(18,2), k_INSUR_1 NUMERIC(18,2), k_GAIN1 NUMERIC(18,2),
								k_PER_EDT2 VARCHAR(1), k_YEAR_EDT2 VARCHAR(4), k_INSUR2 NUMERIC(18,2), k_INSUR_2 NUMERIC(18,2), k_GAIN2 NUMERIC(18,2),
								k_PER_EDT3 VARCHAR(1), k_YEAR_EDT3 VARCHAR(4), k_INSUR3 NUMERIC(18,2), k_INSUR_3 NUMERIC(18,2), k_GAIN3 NUMERIC(18,2),
								k_PER_EDT4 VARCHAR(1), k_YEAR_EDT4 VARCHAR(4), k_INSUR4 NUMERIC(18,2), k_INSUR_4 NUMERIC(18,2), k_GAIN4 NUMERIC(18,2),
								k_PER_EDT5 VARCHAR(1), k_YEAR_EDT5 VARCHAR(4), k_INSUR5 NUMERIC(18,2), k_INSUR_5 NUMERIC(18,2), k_GAIN5 NUMERIC(18,2),SUM_VZNOS NUMERIC(18,2))
	
	INSERT INTO #PACHKA_64 (LINK , [TYPE], NOM_PP,SNILS,CODE_STR,CODE_KAT,INSUR,B_BEF, GB_BEF, B_AFT,
							PER,YEAR_BEGIN,PER_EDT,YEAR_EDT,FM,IM,OT,
							k_PER_EDT1,k_YEAR_EDT1,k_INSUR1,k_INSUR_1,k_GAIN1,k_PER_EDT2,k_YEAR_EDT2,k_INSUR2,k_INSUR_2,k_GAIN2,
							k_PER_EDT3,k_YEAR_EDT3,k_INSUR3,k_INSUR_3,k_GAIN3,k_PER_EDT4,k_YEAR_EDT4,k_INSUR4,k_INSUR_4,k_GAIN4,
							k_PER_EDT5,k_YEAR_EDT5,k_INSUR5,k_INSUR_5,k_GAIN5,SUM_VZNOS)

	SELECT 
				LINK,
				[TYPE],
				NOM_PP = ROW_NUMBER() OVER (PARTITION BY SNILS, [TYPE] ORDER BY CODE_STR),
				SNILS,CODE_STR,CODE_KAT,INSUR,B_BEF, GB_BEF, B_AFT,
				PER,YEAR_BEGIN,PER_EDT,YEAR_EDT,FM,IM,OT,
				k_PER_EDT1,k_YEAR_EDT1,k_INSUR1,k_INSUR_1,k_GAIN1,k_PER_EDT2,k_YEAR_EDT2,k_INSUR2,k_INSUR_2,k_GAIN2,
				k_PER_EDT3,k_YEAR_EDT3,k_INSUR3,k_INSUR_3,k_GAIN3,k_PER_EDT4,k_YEAR_EDT4,k_INSUR4,k_INSUR_4,k_GAIN4,
				k_PER_EDT5,k_YEAR_EDT5,k_INSUR5,k_INSUR_5,k_GAIN5,SUM_VZNOS		
	FROM
	(
		SELECT DISTINCT LINK , [TYPE],SNILS,CODE_STR,CODE_KAT,INSUR,B_BEF, GB_BEF, B_AFT,
							PER,YEAR_BEGIN,PER_EDT,YEAR_EDT,FM,IM,OT,
							k_PER_EDT1,k_YEAR_EDT1,k_INSUR1,k_INSUR_1,k_GAIN1,k_PER_EDT2,k_YEAR_EDT2,k_INSUR2,k_INSUR_2,k_GAIN2,
							k_PER_EDT3,k_YEAR_EDT3,k_INSUR3,k_INSUR_3,k_GAIN3,k_PER_EDT4,k_YEAR_EDT4,k_INSUR4,k_INSUR_4,k_GAIN4,
							k_PER_EDT5,k_YEAR_EDT5,k_INSUR5,k_INSUR_5,k_GAIN5,SUM_VZNOS
		FROM
		#P_64 T64	
	) T	


DROP TABLE #P_64
DROP TABLE #TAB64


	CREATE TABLE #TAB66 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18), SUMMA2 NUMERIC(18,2), STR_VAL VARCHAR(254))
	INSERT INTO #TAB66 (ROW_CODE, COL, SUMMA,SUMMA2, STR_VAL)
	SELECT ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 19, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL
	

	CREATE TABLE #TAB67 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18), SUMMA2 NUMERIC(18,2), STR_VAL VARCHAR(254))
	INSERT INTO #TAB67 (ROW_CODE, COL, SUMMA,SUMMA2, STR_VAL)
	SELECT ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 20, DEFAULT, DEFAULT) T  ORDER BY T.COL	

	CREATE TABLE #PACHKA_67 (
								LINK INT, [TYPE] INT , NOM_PP INT, SNILS VARCHAR(14), CODE_STR INT, CODE_SPO varchar(5), INC_T1M NUMERIC(18,2), INC_T2M NUMERIC(18,2), 
								DATE_BEGIN1 varchar(10),DATE_END1 VARCHAR(10),TU_CODE1 VARCHAR(10), OS_CODE1 VARCHAR(20), EX_CODE1 VARCHAR(10), f_is_dop1 VARCHAR(100), P_CODE1 varchar(10), f_ud_dop1 varchar(100),
								DATE_BEGIN2 varchar(10),DATE_END2 VARCHAR(10),TU_CODE2 VARCHAR(10), OS_CODE2 VARCHAR(20), EX_CODE2 VARCHAR(10), f_is_dop2 VARCHAR(100), P_CODE2 varchar(10), f_ud_dop2 varchar(100),
								DATE_BEGIN3 varchar(10),DATE_END3 VARCHAR(10),TU_CODE3 VARCHAR(10), OS_CODE3 VARCHAR(20), EX_CODE3 VARCHAR(10), f_is_dop3 VARCHAR(100), P_CODE3 varchar(10), f_ud_dop3 varchar(100),
								DATE_BEGIN4 varchar(10),DATE_END4 VARCHAR(10),TU_CODE4 VARCHAR(10), OS_CODE4 VARCHAR(20), EX_CODE4 VARCHAR(10), f_is_dop4 VARCHAR(100), P_CODE4 varchar(10), f_ud_dop4 varchar(100)
							)
	
	INSERT INTO #PACHKA_67 (LINK, [TYPE], NOM_PP,SNILS,CODE_STR,CODE_SPO,INC_T1M,INC_T2M,
								DATE_BEGIN1,DATE_END1,TU_CODE1, OS_CODE1, EX_CODE1, f_is_dop1, P_CODE1, f_ud_dop1,
								DATE_BEGIN2,DATE_END2,TU_CODE2, OS_CODE2, EX_CODE2, f_is_dop2, P_CODE2, f_ud_dop2,
								DATE_BEGIN3,DATE_END3,TU_CODE3, OS_CODE3, EX_CODE3, f_is_dop3, P_CODE3, f_ud_dop3,
								DATE_BEGIN4,DATE_END4,TU_CODE4, OS_CODE4, EX_CODE4, f_is_dop4, P_CODE4, f_ud_dop4)
	SELECT 
				LINK = dEnse_RANK() OVER (ORDER BY  [type],snils ),
				[TYPE],
				NOM_PP = ROW_NUMBER() OVER (PARTITION BY SNILS, [TYPE] ORDER BY CODE_STR),
								SNILS,CODE_STR,CODE_SPO,INC_T1M,INC_T2M,
								DATE_BEGIN1,DATE_END1,TU_CODE1, OS_CODE1, EX_CODE1, f_is_dop1, P_CODE1, f_ud_dop1,
								DATE_BEGIN2,DATE_END2,TU_CODE2, OS_CODE2, EX_CODE2, f_is_dop2, P_CODE2, f_ud_dop2,
								DATE_BEGIN3,DATE_END3,TU_CODE3, OS_CODE3, EX_CODE3, f_is_dop3, P_CODE3, f_ud_dop3,
								DATE_BEGIN4,DATE_END4,TU_CODE4, OS_CODE4, EX_CODE4, f_is_dop4, P_CODE4, f_ud_dop4		
	FROM
	(
		SELECT DISTINCT 
			[TYPE] = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB67 T WHERE T.COL = 9 AND T.ROW_CODE = T67.ROW_CODE),
			SNILS = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 7 AND T.ROW_CODE = T67.ROW_CODE),
			CODE_STR = CONVERT( int ,(SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 3 AND T.ROW_CODE = T67.ROW_CODE)),
			CODE_SPO = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 4 AND T.ROW_CODE = T67.ROW_CODE),
			INC_T1M = (SELECT TOP 1 SUMMA2 FROM #TAB67 T WHERE T.COL = 5 AND T.ROW_CODE = T67.ROW_CODE),
			INC_T2M = (SELECT TOP 1 SUMMA2 FROM #TAB67 T WHERE T.COL = 6 AND T.ROW_CODE = T67.ROW_CODE ),

			DATE_BEGIN1 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 10 AND T.ROW_CODE = T67.ROW_CODE ),
			DATE_END1 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 11 AND T.ROW_CODE = T67.ROW_CODE),
			TU_CODE1 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 12 AND T.ROW_CODE = T67.ROW_CODE),
			OS_CODE1 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 13 AND T.ROW_CODE = T67.ROW_CODE ),
			EX_CODE1 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 14 AND T.ROW_CODE = T67.ROW_CODE),
			f_is_dop1 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 15 AND T.ROW_CODE = T67.ROW_CODE ),
			P_CODE1 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 16 AND T.ROW_CODE = T67.ROW_CODE),
			f_ud_dop1 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 17 AND T.ROW_CODE = T67.ROW_CODE),
			
			DATE_BEGIN2 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 18 AND T.ROW_CODE = T67.ROW_CODE ),
			DATE_END2 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 19 AND T.ROW_CODE = T67.ROW_CODE),
			TU_CODE2 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 20 AND T.ROW_CODE = T67.ROW_CODE),
			OS_CODE2 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 21 AND T.ROW_CODE = T67.ROW_CODE ),
			EX_CODE2 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 22 AND T.ROW_CODE = T67.ROW_CODE),
			f_is_dop2 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 23 AND T.ROW_CODE = T67.ROW_CODE ),
			P_CODE2 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 24 AND T.ROW_CODE = T67.ROW_CODE),
			f_ud_dop2 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 25 AND T.ROW_CODE = T67.ROW_CODE),
			
			DATE_BEGIN3 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 26 AND T.ROW_CODE = T67.ROW_CODE ),
			DATE_END3 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 27 AND T.ROW_CODE = T67.ROW_CODE),
			TU_CODE3 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 28 AND T.ROW_CODE = T67.ROW_CODE),
			OS_CODE3 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 29 AND T.ROW_CODE = T67.ROW_CODE ),
			EX_CODE3 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 30 AND T.ROW_CODE = T67.ROW_CODE),
			f_is_dop3 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 31 AND T.ROW_CODE = T67.ROW_CODE ),
			P_CODE3 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 32 AND T.ROW_CODE = T67.ROW_CODE),
			f_ud_dop3 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 33 AND T.ROW_CODE = T67.ROW_CODE),
			
			DATE_BEGIN4 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 34 AND T.ROW_CODE = T67.ROW_CODE ),
			DATE_END4 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 35 AND T.ROW_CODE = T67.ROW_CODE),
			TU_CODE4 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 36 AND T.ROW_CODE = T67.ROW_CODE),
			OS_CODE4 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 37 AND T.ROW_CODE = T67.ROW_CODE ),
			EX_CODE4 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 38 AND T.ROW_CODE = T67.ROW_CODE),
			f_is_dop4 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 39 AND T.ROW_CODE = T67.ROW_CODE ),
			P_CODE4 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 40 AND T.ROW_CODE = T67.ROW_CODE),
			f_ud_dop4 = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB67 T WHERE T.COL = 41 AND T.ROW_CODE = T67.ROW_CODE)
		FROM
		#TAB67 T67	
	) T	

	--SET @NEXT_NUM3 = 0
	--UPDATE  p  SET  LINK = (select top 1 link from #TAB61 where ltrim(rtrim(SNILS)) = ltrim(rtrim(p.SNILS)) 
	--														 and [type] = p.[type])
	--FROM #PACHKA_67 p   


----------------------

-------------------------
--exec SA_RSV1_EXPORT_0700_2014 41964
--exec SA_RSV1_EXPORT_0700_2014 2522
DROP TABLE #TAB67


	CREATE TABLE #TAB68 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18), SUMMA2 NUMERIC(18,2), STR_VAL VARCHAR(254))
	INSERT INTO #TAB68	(ROW_CODE, COL, SUMMA,SUMMA2, STR_VAL)
	SELECT ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 21, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL	

	SELECT T1.LINK , t1.NGROUP , T1.FNAME, T1.DOC_DATE, t2.[TYPE],t2.SNILS, t2.NOM_PP,t2.CODE_STR,t2.CODE_KAT,t2.INSUR,t2.B_BEF, t2.GB_BEF, t2.B_AFT,
							t2.PER,t2.YEAR_BEGIN,t2.PER_EDT,t2.YEAR_EDT,t2.FM,t2.IM,t2.OT,
							t2.k_PER_EDT1,t2.k_YEAR_EDT1,t2.k_INSUR1,t2.k_INSUR_1,t2.k_GAIN1,t2.k_PER_EDT2,t2.k_YEAR_EDT2,t2.k_INSUR2,t2.k_INSUR_2,t2.k_GAIN2,
							t2.k_PER_EDT3,t2.k_YEAR_EDT3,t2.k_INSUR3,t2.k_INSUR_3,t2.k_GAIN3,t2.k_PER_EDT4,t2.k_YEAR_EDT4,t2.k_INSUR4,t2.k_INSUR_4,t2.k_GAIN4,
							t2.k_PER_EDT5,t2.k_YEAR_EDT5,t2.k_INSUR5,t2.k_INSUR_5,t2.k_GAIN5, t2.SUM_VZNOS
	INTO #RES
	FROM #TAB61 t1 inner join #PACHKA_64 t2
	ON 	t1.link= t2.link and t1.FM = t2.FM  and t1.IM = t2.IM and  t1.OT = t2.OT and t1.SNILS = t2.SNILS 
	WHERE 
	(	
		ISNULL(t2.INSUR,0) <> 0 
		OR EXISTS (
			SELECT *
			FROM 
				dbo.SA_SZV4_SVEDENIA s INNER JOIN  dbo.SA_SZV4_STAZH st ON S.link1 = ST.link
			WHERE 
				s.link = (SELECT TOP 1 SUMMA FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, DEFAULT, 11))
				AND T1.NGROUP = S.PACHKA
				AND  s.FM = t2.FM and s.IM = t2.IM  and s.OT = t2.OT AND  s.PF_NUM= t2.SNILS 
		)
	)
	order by T1.LINK, t2.link , t2.[type] , t2.fm, t2.IM, t2.OT, t2.CODE_STR
--
	SELECT T1.LINK , t1.NGROUP , T1.FNAME, T1.DOC_DATE,t1.FM,t1.IM,t1.OT, t2.[TYPE],t2.SNILS, t2.NOM_PP,t2.CODE_STR,t2.CODE_SPO,t2.INC_T1M,t2.INC_T2M,
								t2.DATE_BEGIN1,t2.DATE_END1,t2.TU_CODE1, t2.OS_CODE1, t2.EX_CODE1, t2.f_is_dop1, t2.P_CODE1, t2.f_ud_dop1,
								t2.DATE_BEGIN2,t2.DATE_END2,t2.TU_CODE2, t2.OS_CODE2, t2.EX_CODE2, t2.f_is_dop2, t2.P_CODE2, t2.f_ud_dop2,
								t2.DATE_BEGIN3,t2.DATE_END3,t2.TU_CODE3, t2.OS_CODE3, t2.EX_CODE3, t2.f_is_dop3, t2.P_CODE3, t2.f_ud_dop3,
								t2.DATE_BEGIN4,t2.DATE_END4,t2.TU_CODE4, t2.OS_CODE4, t2.EX_CODE4, t2.f_is_dop4, t2.P_CODE4, t2.f_ud_dop4
	INTO #RES1
	FROM #PACHKA_67 t2  inner join #TAB61 t1  
	on 	/*t1.link= t2.link and*/ t1.SNILS = t2.SNILS
	order by T1.LINK, t2.link , t2.[type], t1.fm, t1.IM, t1.OT, t2.CODE_STR
	

DECLARE	@LINK_R int, @TYPE_R varchar(15),@SNILS_R varchar(14),@CODE_STR_R varchar(4), 
		@CODE_KAT_R varchar(5),@FM_R varchar(100),@IM_R varchar(100),@OT_R varchar(100),
		@PER_R varchar(1),@YEAR_BEGIN_R varchar(4),@PER_EDT_R varchar(1),@YEAR_EDT_R varchar(4),
		@DATE_DOC_R varchar (10) ,  @FNAME_R varchar(150), @NOM_PACH_R varchar(4), @LINK_DOC_OP INT




SET @Cur3 = CURSOR FORWARD_ONLY
FOR 
select 	
	LINK , 
	[TYPE] = case [TYPE] when 1 then 'ИСХОДНАЯ' WHEN 2 then 'КОРРЕКТИРУЮЩАЯ' else 'ОТМЕНЯЮЩАЯ' end , 
	NOM_PP, 
	NOM_PACH, 
	SUM_BASE, 
	SUM_STR, 
	PERS_CNT, 
	DATE_DOC, 
	PER  = CASE [TYPE] when 2 then (CASE per WHEN 3 THEN 1 WHEN 6 THEN 2 WHEN 9 THEN 3 ELSE 0 end) else PER end, 
	YEAR_BEGIN , 
	PER_EDT = CASE [TYPE] when 2 then (CASE PER_EDT WHEN 3 THEN 1 WHEN 6 THEN 2 WHEN 9 THEN 3 ELSE 0 end) else PER_EDT end, 
	YEAR_EDT, 
	F_NAME,
	LINK_DOC
from #OPIS order by LINK,[TYPE], NOM_PP 


OPEN @Cur3
FETCH NEXT FROM @Cur3 INTO @LINK_OP, @TYP_D, @NOM_PP, @NGROUP /*Номер пачки*/,@SUM_BASE, @SUM_STR, @PERS_CNT,@DATE_DOC,@PER, @YEAR_BEGIN, @PER_EDT, @YEAR_EDT, @lcFNAME/*наименование файла*/ , @LINK_DOC_OP


WHILE (@@fetch_status <> -1)
BEGIN
	
	IF (@@fetch_status <> -2)
	BEGIN	
---------------------------------------------------------------
----------------------------------------------------------------

			-- Начало второго входящего документа (расширение блока входящий документ)
			IF (SELECT COUNT(*) FROM #OPIS) > 0 -- 
			BEGIN

				IF (SELECT COUNT (*) FROM #RES WHERE LTRIM(RTRIM([TYPE])) = LTRIM(RTRIM(@TYP_D)) 
										AND  LTRIM(RTRIM(PER)) = LTRIM(RTRIM(ISNULL(@PER,'0'))) 
										AND  LTRIM(RTRIM(YEAR_BEGIN)) = LTRIM(RTRIM(ISNULL(@YEAR_BEGIN,'0'))) 
										and LTRIM(RTRIM(PER_EDT)) =  LTRIM(RTRIM(ISNULL(@PER_EDT,'0'))) and LTRIM(RTRIM(YEAR_EDT)) =  LTRIM(RTRIM(ISNULL(@YEAR_EDT,'0'))) 
										and  LTRIM(RTRIM(DOC_DATE)) = LTRIM(RTRIM(@DATE_DOC)) and LTRIM(RTRIM(FNAME)) = LTRIM(RTRIM(@lcFNAME)) and LTRIM(RTRIM(NGROUP)) = LTRIM(RTRIM(@NGROUP))) > 0
				BEGIN

					SET @PERS_CNT  = (select distinct COUNT (*) FROM 
					(select distinct link , ngroup, snils from #RES WHERE LTRIM(RTRIM([TYPE])) = LTRIM(RTRIM(@TYP_D)) and LTRIM(RTRIM(PER)) = LTRIM(RTRIM(ISNULL(@PER,'0'))) and LTRIM(RTRIM(YEAR_BEGIN)) = LTRIM(RTRIM(ISNULL(@YEAR_BEGIN,'0'))) 
										and LTRIM(RTRIM(PER_EDT)) =  LTRIM(RTRIM(ISNULL(@PER_EDT,'0'))) and LTRIM(RTRIM(YEAR_EDT)) =  LTRIM(RTRIM(ISNULL(@YEAR_EDT,'0'))) 
										and  LTRIM(RTRIM(DOC_DATE)) = LTRIM(RTRIM(@DATE_DOC)) and LTRIM(RTRIM(FNAME)) = LTRIM(RTRIM(@lcFNAME)) and LTRIM(RTRIM(NGROUP)) = LTRIM(RTRIM(@NGROUP))
										GROUP BY link , ngroup , SNILS) s)
				
						
				DECLARE @NUM_PACH_PP INT 
				SET @NUM_PACH_PP = 1
				
				--exec SA_RSV1_EXPORT_0700_2014    2565
			
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				 SELECT @lcFNAME, 'OEM' --Имя файла
				 UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="Windows-1251" ?>'
				 UNION ALL SELECT @lcFNAME, SPACE(0) + '<ФайлПФР>'
					UNION ALL SELECT @lcFNAME, SPACE(1) + '<ИмяФайла>' + RTRIM(LTRIM(@lcFNAME)) + '</ИмяФайла>'
					UNION ALL SELECT @lcFNAME, SPACE(1) + '<ЗаголовокФайла>'
					 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ВерсияФормата>07.00</ВерсияФормата>'
					 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ТипФайла>ВНЕШНИЙ</ТипФайла>'
					 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ПрограммаПодготовкиДанных>'
						UNION ALL SELECT @lcFNAME, SPACE(3) + '<НазваниеПрограммы>' + @NAME_PROG + '</НазваниеПрограммы>'
						UNION ALL SELECT @lcFNAME, SPACE(3) + '<Версия>' + @VERS_PROG + '</Версия>'
					 UNION ALL SELECT @lcFNAME, SPACE(2) + '</ПрограммаПодготовкиДанных>'
					 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ИсточникДанных>СТРАХОВАТЕЛЬ</ИсточникДанных> '
					UNION ALL SELECT @lcFNAME, SPACE(1) + '</ЗаголовокФайла>'
					UNION ALL SELECT @lcFNAME, SPACE(1) + '<ПачкаВходящихДокументов Окружение="В составе файла" Стадия="До обработки">'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
					SELECT @lcFNAME, SPACE(2) + '<СВЕДЕНИЯ_ПО_ПАЧКЕ_ДОКУМЕНТОВ_РАЗДЕЛА_6>' 


				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
					SELECT @lcFNAME, SPACE(3) + '<НомерВпачке>'+ RTRIM(LTRIM(STR(@NUM_PACH_PP)))+'</НомерВпачке>' + CHAR(10) + 
						SPACE(3) + '<ТипВходящейОписи>ОПИСЬ ПАЧКИ</ТипВходящейОписи>' + CHAR(10) + 
						SPACE(3) + '<СоставительПачки>' + CHAR(10) + 
							SPACE(4) + '<НалоговыйНомер>' + CHAR(10) + 
								SPACE(5) + '<ИНН>' + LTRIM(RTRIM(ISNULL((select TOP 1 INN1 FROM #DEP_DATA),'')))+ '</ИНН>' + CHAR(10) + 
								SPACE(5) + '<КПП>' + LTRIM(RTRIM(ISNULL((SELECT TOP 1 KPP1 FROM #DEP_DATA),''))) + '</КПП>' + CHAR(10) + 
							SPACE(4) + '</НалоговыйНомер>' + CHAR(10) + 
							SPACE(4) + '<НаименованиеОрганизации>' + LTRIM(RTRIM(ISNULL((SELECT TOP 1 CONVERT(varchar(50),FULL_NAME) FROM #DEP_DATA),'')))+ '</НаименованиеОрганизации>' + CHAR(10) + 
							SPACE(4) + '<НаименованиеКраткое>' + LTRIM(RTRIM(ISNULL( (SELECT TOP 1 ORGNAME FROM #DEP_DATA),''))) + '</НаименованиеКраткое>' + CHAR(10) + 
							SPACE(4) + '<РегистрационныйНомер>' + LTRIM(RTRIM(ISNULL( (SELECT TOP 1 PFNUMBER FROM #DEP_DATA),''))) + '</РегистрационныйНомер>' + CHAR(10) + 
						SPACE(3) + '</СоставительПачки>' + CHAR(10) + 
						SPACE(3) + '<НомерПачки>' + CHAR(10) + 
							SPACE(4) + '<Основной>'+LTRIM(RTRIM(@NGROUP))+'</Основной>' + CHAR(10) + 	
						SPACE(3) + '</НомерПачки>' + CHAR(10) + 	
						SPACE(3) + '<СоставДокументов>' + CHAR(10) + 	
							SPACE(4) + '<Количество>' + '1' /*@DOCCOUNT*/ + '</Количество>' + CHAR(10) + 	
							SPACE(4) + '<НаличиеДокументов>' + CHAR(10) + 	
								SPACE(5) + '<ТипДокумента>СВЕДЕНИЯ_О_СУММЕ_ВЫПЛАТ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ</ТипДокумента>' + CHAR(10) + 	
								SPACE(5) + '<Количество>' + RTRIM(LTRIM(STR(@PERS_CNT)))+ '</Количество>' + CHAR(10) + 	
							SPACE(4) + '</НаличиеДокументов>' + CHAR(10) + 	
						SPACE(3) + '</СоставДокументов>' + CHAR(10) + 		

						SPACE(3) + '<ДатаСоставления>' + CONVERT(VARCHAR(10),@DATE_DOC,104)+ '</ДатаСоставления>' + CHAR(10) + 	
						SPACE(3) + '<ТипСведений>' + RTRIM(LTRIM(@TYP_D)) + '</ТипСведений>' + CHAR(10) + 	

						SPACE(3) + '<ОтчетныйПериод>'+ CHAR(10) + 	
							SPACE(4) + '<Квартал>' + CASE @PER WHEN '1' THEN '3' 
															 WHEN '2' THEN '6' 
															 WHEN '3' THEN '9'
															 ELSE '0' 
													 END + '</Квартал>' + CHAR(10) + 	
							SPACE(4) + '<Год>' + @YEAR_BEGIN + '</Год>' + CHAR(10) + 	
							SPACE(4) + '<Название>' 
										+	CASE @PER 
													WHEN '1' THEN 'С 01.01.'+@YEAR_BEGIN+' ПО 31.03.'+@YEAR_BEGIN
													WHEN '2' THEN 'С 01.01.'+@YEAR_BEGIN+' ПО 30.06.'+@YEAR_BEGIN
													WHEN '3' THEN 'С 01.01.'+@YEAR_BEGIN+' ПО 30.09.'+@YEAR_BEGIN
													WHEN '4' THEN 'С 01.01.'+@YEAR_BEGIN+' ПО 31.12.'+@YEAR_BEGIN
													ELSE ''
											END									
											+ '</Название>' + CHAR(10) + 	
						SPACE(3) + '</ОтчетныйПериод>' + CHAR(10) + 
											
						CASE WHEN @TYP_D = 'КОРРЕКТИРУЮЩАЯ' and @PER_EDT IS NOT NULL THEN ( SPACE(3) + '<КорректируемыйОтчетныйПериод>' + CHAR(10) + 
																SPACE(4) + '<Квартал>' + CASE @PER_EDT  WHEN '1' THEN '3' 
																									 WHEN '2' THEN '6'
																									 WHEN '3' THEN '9'	
																									 ELSE '0' 
																						 END+ '</Квартал>' + CHAR(10) + 
																SPACE(4) + '<Год>' + @YEAR_EDT + '</Год>' + CHAR(10) + 
																SPACE(4) + '<Название>' + 
																			CASE @PER_EDT 
																					WHEN '1' THEN 'С 01.01.'+@YEAR_EDT+' ПО 31.03.'+@YEAR_EDT
																					WHEN '2' THEN 'С 01.01.'+@YEAR_EDT+' ПО 30.06.'+@YEAR_EDT
																					WHEN '3' THEN 'С 01.01.'+@YEAR_EDT+' ПО 30.09.'+@YEAR_EDT
																					WHEN '4' THEN 'С 01.01.'+@YEAR_EDT+' ПО 31.12.'+@YEAR_EDT
																					ELSE ''
																			END									
																			+ '</Название>' + CHAR(10) + 
															SPACE(3) + '</КорректируемыйОтчетныйПериод>' ) ELSE '' END + CHAR(10) + 
													SPACE(3) + '<БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + RTRIM(LTRIM(STR(COALESCE(@SUM_BASE,0),15,2))) + '</БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + CHAR(10) + 
													SPACE(3) + '<СтраховыхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(@SUM_STR,0),15,2))) + '</СтраховыхВзносовОПС>' 
				
						INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
						SELECT @lcFNAME,SPACE(2) + '</СВЕДЕНИЯ_ПО_ПАЧКЕ_ДОКУМЕНТОВ_РАЗДЕЛА_6>'									


						DECLARE @NUM_l INT, @num_old INT
						SET @NUM_l = 0
						SET @num_old = 0
						
						SET @Cur4 = CURSOR FORWARD_ONLY
						FOR 
						SELECT LINK,[TYPE],SNILS,PER,YEAR_BEGIN,PER_EDT,YEAR_EDT,FM,IM,OT, DOC_DATE/*, FNAME, NGROUP*/
						FROM #RES where  LTRIM(RTRIM([TYPE])) = LTRIM(RTRIM(@TYP_D)) and LTRIM(RTRIM(PER)) = LTRIM(RTRIM(ISNULL(@PER,'0'))) and LTRIM(RTRIM(YEAR_BEGIN)) = LTRIM(RTRIM(ISNULL(@YEAR_BEGIN,'0'))) 
										and LTRIM(RTRIM(PER_EDT)) =  LTRIM(RTRIM(ISNULL(@PER_EDT,'0'))) and LTRIM(RTRIM(YEAR_EDT)) =  LTRIM(RTRIM(ISNULL(@YEAR_EDT,'0'))) 
										and  LTRIM(RTRIM(DOC_DATE)) = LTRIM(RTRIM(@DATE_DOC)) and LTRIM(RTRIM(FNAME)) = LTRIM(RTRIM(@lcFNAME)) and LTRIM(RTRIM(NGROUP)) = LTRIM(RTRIM(@NGROUP))  
						group BY LINK,[TYPE],SNILS,PER,YEAR_BEGIN,PER_EDT,YEAR_EDT,FM,IM,OT, DOC_DATE/*, FNAME, NGROUP*/
						order by link , fm, IM, OT, SNILS , [type]

						OPEN @Cur4
						FETCH NEXT FROM @Cur4 INTO @LINK_R, @TYPE_R,@SNILS_R,@PER_R,@YEAR_BEGIN_R,@PER_EDT_R,@YEAR_EDT_R, 
													@FM_R,@IM_R,@OT_R, @DATE_DOC_R/*, @FNAME_R, @NOM_PACH_R*/
						WHILE (@@fetch_status <> -1)
						BEGIN
							
							IF (@@fetch_status <> -2)
							BEGIN	
									set @NUM_PACH_PP = @NUM_PACH_PP + 1 					
								
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME, SPACE(2) + '<СВЕДЕНИЯ_О_СУММЕ_ВЫПЛАТ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ>' 
							
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME, SPACE(3) + '<НомерВпачке>'+ RTRIM(LTRIM(STR(@NUM_PACH_PP)))+'</НомерВпачке>'
										UNION ALL SELECT @lcFNAME, SPACE(3) + '<ТипСведений>'+ UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),''))))+ '</ТипСведений>' 
										UNION ALL SELECT @lcFNAME, SPACE(3) + '<РегистрационныйНомер>'+ LTRIM(RTRIM(ISNULL( (SELECT TOP 1 PFNUMBER FROM #DEP_DATA),''))) +'</РегистрационныйНомер>'
										UNION ALL SELECT @lcFNAME, SPACE(3) + '<СтраховойНомер>'+ LTRIM(RTRIM(ISNULL( @SNILS_R,''))) +'</СтраховойНомер>'
										UNION ALL SELECT @lcFNAME, SPACE(3) + '<ФИО>' 
											UNION ALL SELECT @lcFNAME, SPACE(4) + '<Фамилия>' + UPPER(LTRIM(RTRIM(ISNULL(@FM_R,''))))+ '</Фамилия>' 
											UNION ALL SELECT @lcFNAME, SPACE(4) + '<Имя>' + UPPER(LTRIM(RTRIM(ISNULL(@iM_R,''))))+ '</Имя>' 
											UNION ALL SELECT @lcFNAME, SPACE(4) + '<Отчество>' + UPPER(LTRIM(RTRIM(ISNULL(@OT_R,''))))+ '</Отчество>' 
										UNION ALL SELECT @lcFNAME, SPACE(3) + '</ФИО>' 	
										UNION ALL SELECT @lcFNAME, SPACE(3) + '<ОтчетныйПериод>'
											UNION ALL SELECT @lcFNAME, SPACE(4) + '<Квартал>' + CASE @PER_r WHEN '1' THEN '3' 
																										  WHEN '2' THEN '6' 
																										  WHEN '3' THEN '9'
																										  ELSE '0' 
																										  END 
																				+ '</Квартал>' 	
											UNION ALL SELECT @lcFNAME, SPACE(4) + '<Год>' + @YEAR_BEGIN_r + '</Год>'	
											UNION ALL SELECT @lcFNAME, SPACE(4) + '<Название>' +	CASE @PER_R 
																											WHEN '1' THEN 'С 01.01.'+@YEAR_BEGIN_R+' ПО 31.03.'+@YEAR_BEGIN_R
																											WHEN '2' THEN 'С 01.01.'+@YEAR_BEGIN_R+' ПО 30.06.'+@YEAR_BEGIN_R
																											WHEN '3' THEN 'С 01.01.'+@YEAR_BEGIN_R+' ПО 30.09.'+@YEAR_BEGIN_R
																											WHEN '4' THEN 'С 01.01.'+@YEAR_BEGIN_R+' ПО 31.12.'+@YEAR_BEGIN_R
																											ELSE ''
																									END									
																				+ '</Название>' 	
											UNION ALL SELECT @lcFNAME,SPACE(3) + '</ОтчетныйПериод>' 
											
											IF UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'КОРРЕКТИРУЮЩАЯ'
												INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														 SELECT @lcFNAME, SPACE(3) + '<КорректируемыйОтчетныйПериод>' + CHAR(10) + CHAR(13) + 
																				SPACE(4) + '<Квартал>' + CASE @PER_EDT_R WHEN '1' THEN '3' 
																														 WHEN '2' THEN '6'
																														 WHEN '3' THEN '9'	
																														 ELSE '0' 
																										END
																						+ '</Квартал>' + CHAR(10) + CHAR(13) + 
																				SPACE(4) + '<Год>' + @YEAR_EDT_R + '</Год>' + CHAR(10) + CHAR(13) +
																				SPACE(4) + '<Название>' + 
																							CASE @PER_EDT_R 
																										WHEN '1' THEN 'С 01.01.'+@YEAR_EDT_R+' ПО 31.03.'+@YEAR_EDT_R
																										WHEN '2' THEN 'С 01.01.'+@YEAR_EDT_R+' ПО 30.06.'+@YEAR_EDT_R
																										WHEN '3' THEN 'С 01.01.'+@YEAR_EDT_R+' ПО 30.09.'+@YEAR_EDT_R
																										WHEN '4' THEN 'С 01.01.'+@YEAR_EDT_R+' ПО 31.12.'+@YEAR_EDT_R
																										ELSE ''
																							END									
																						+ '</Название>' + CHAR(10) + CHAR(13) +
																		SPACE(3) + '</КорректируемыйОтчетныйПериод>' + CHAR(10) + CHAR(13) +
																		SPACE(3) + '<РегистрационныйНомерКорректируемогоПериода>'+ LTRIM(RTRIM(ISNULL( (SELECT TOP 1 PFNUMBER FROM #DEP_DATA),''))) +'</РегистрационныйНомерКорректируемогоПериода>'
											
																					
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT @lcFNAME ,SPACE(3) + '<СведенияОсуммеВыплатИвознагражденийВпользуЗЛ>' + CHAR(10)+
																			 SPACE(4) + '<НомерСтроки>' + LTRIM(RTRIM(ISNULL( ( ROW_NUMBER() OVER (ORDER BY CODE_STR) ),''))) + '</НомерСтроки>' + CHAR(10)+
																			 SPACE(4) + '<ТипСтроки>' + LTRIM(RTRIM(ISNULL( (CASE WHEN CODE_STR = '400' OR CODE_STR = '410' OR CODE_STR = '420' THEN 'ИТОГ' ELSE 'МЕСЦ' END),''))) + '</ТипСтроки>' + CHAR(10)+
																			 SPACE(4) + (CASE WHEN CODE_STR = '400' OR CODE_STR ='410' OR CODE_STR ='420' THEN ''
																							  else  ( '<Месяц>' +	(CASE WHEN CODE_STR = '400' OR CODE_STR ='410' OR CODE_STR ='420' THEN ''
																							   
																														  WHEN CODE_STR = '401' OR CODE_STR ='411' OR CODE_STR ='421' THEN  
																														  						(CASE WHEN UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'ИСХОДНАЯ' 
																														  							  THEN (CASE @PER_r WHEN '1' THEN '1'
																														  												WHEN '2' THEN '4'
																														  												WHEN '3' THEN '7'
																														  												ELSE '10' end)
																														  							  ELSE (CASE @PER_EDT_R WHEN '1' THEN '1'
																														  													WHEN '2' THEN '4'
																														  													WHEN '3' THEN '7'
																														  													ELSE '10' end)    
																														  						END)
																																														
																														  WHEN CODE_STR = '402' OR CODE_STR ='412' OR CODE_STR ='422' THEN 
																														  						(CASE WHEN UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'ИСХОДНАЯ' 
																														  							  THEN (CASE @PER_r WHEN '1' THEN '2'
																														  												WHEN '2' THEN '5'
																														  												WHEN '3' THEN '8'
																														  												ELSE '11' end)
																														  							  ELSE (CASE @PER_EDT_R WHEN '1' THEN '2'
																														  													WHEN '2' THEN '5'
																														  													WHEN '3' THEN '8'
																														  													ELSE '11' end)    
																														  						END)
																														 
																														  ELSE 					(CASE WHEN UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'ИСХОДНАЯ' 
																														  							  THEN (CASE @PER_r WHEN '1' THEN '3'
																														  												WHEN '2' THEN '6'
																														  												WHEN '3' THEN '9'
																														  												ELSE '12' end)
																														  							  ELSE (CASE @PER_EDT_R WHEN '1' THEN '3'
																														  													WHEN '2' THEN '6'
																														  													WHEN '3' THEN '9'
																														  													ELSE '12' end)    
																														  						END)  
																							                     	      end ) + '</Месяц>'  ) 
																							  END)   + CHAR(10)+
																									
																			 SPACE(4) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(CODE_STR,''))) + '</КодСтроки>' + CHAR(10)+
																			 SPACE(4) + '<КодКатегории>' + LTRIM(RTRIM(ISNULL(CODE_KAT,''))) + '</КодКатегории>' + CHAR(10)+
																			 SPACE(4) + '<СуммаВыплатИныхВознаграждений>' + RTRIM(LTRIM(STR(COALESCE(INSUR,0),15,2))) + '</СуммаВыплатИныхВознаграждений>' + CHAR(10)+
																			 SPACE(4) + '<НеПревышающиеВсего>' + RTRIM(LTRIM(STR(COALESCE(B_BEF,0),15,2))) + '</НеПревышающиеВсего>' + CHAR(10)+
																			 SPACE(4) + '<НеПревышающиеПоДоговорам>' + RTRIM(LTRIM(STR(COALESCE(GB_BEF,0),15,2))) + '</НеПревышающиеПоДоговорам>' + CHAR(10)+
																			 SPACE(4) + '<ПревышающиеПредельную>' + RTRIM(LTRIM(STR(COALESCE(B_AFT,0),15,2))) + '</ПревышающиеПредельную>' + CHAR(10)+
																	  SPACE(3) + '</СведенияОсуммеВыплатИвознагражденийВпользуЗЛ>'	
													FROM #RES 
													WHERE 
														link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
															and OT = @OT_R AND PER = @PER_R AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R 
															AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R /*and FNAME = @FNAME_R */and LTRIM(RTRIM(NGROUP)) = LTRIM(RTRIM(@NGROUP))
															AND 
																(
																CODE_STR LIKE '4[0,1,2]0'
																OR
																CODE_STR NOT LIKE '4[0,1,2]0' AND ISNULL(INSUR,0) <> 0
																)

											
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT @lcFNAME, SPACE(3) + '<СуммаВзносовНаОПС>' + RTRIM(LTRIM(STR(COALESCE(SUM(SUM_VZNOS),0),15,2))) + '</СуммаВзносовНаОПС>' 
													FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND PER = @PER_R AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R 
																	AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R */and LTRIM(RTRIM(NGROUP)) = LTRIM(RTRIM(@NGROUP)) 
																	AND CODE_STR IN ('400','410','420')
						
												
											IF UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) IN ( 'ИСХОДНАЯ', 'КОРРЕКТИРУЮЩАЯ')
											BEGIN

												
												--exec SA_RSV1_EXPORT_0700_2014    414
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT  @lcFNAME,
															(CASE WHEN (k_INSUR1 <> 0 or k_GAIN1 <> 0) AND  K_YEAR_EDT1 <> 0
															THEN
																	+ SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																				 SPACE(4) + '<НомерСтроки>' + '1' + '</НомерСтроки>' + CHAR(10)+
																				 SPACE(4) + '<ТипСтроки>'+'МЕСЦ'+'</ТипСтроки>' + CHAR(10)+
																				 SPACE(4) + '<Квартал>' +	CASE WHEN K_YEAR_EDT1 >= 2014 
																													THEN (CASE WHEN k_per_edt1 = '1' THEN '3' 
																																WHEN k_per_edt1 = '2' THEN '6' 
																																WHEN k_per_edt1 = '3' THEN '9'
																																ELSE '0'  end ) 
																													ELSE k_per_edt1  END + '</Квартал>' + CHAR(10)+
																				 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(K_YEAR_EDT1,''))) + '</Год>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR1,0),15,2))) + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR_1,0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(k_GAIN1,0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																		  SPACE(3) + '</СведенияОкорректировках>'	
															ELSE 
																''																
															END	)
														FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																		and OT = @OT_R AND PER = @PER_R AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R 
																		AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																		AND CODE_STR = '400' 

												

													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT  @lcFNAME, 
															(CASE WHEN (k_INSUR2 <> 0 OR k_GAIN2 <> 0) AND  K_YEAR_EDT2 <> 0
															THEN		
																+ SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																				 SPACE(4) + '<НомерСтроки>' + '2' + '</НомерСтроки>' + CHAR(10)+
																				 SPACE(4) + '<ТипСтроки>'+'МЕСЦ'+'</ТипСтроки>' + CHAR(10)+
																				 SPACE(4) + '<Квартал>' +	CASE WHEN K_YEAR_EDT2 >= 2014 
																													THEN (CASE WHEN k_per_edt2 = '1' THEN '3' 
																																WHEN k_per_edt2 = '2' THEN '6' 
																																WHEN k_per_edt2 = '3' THEN '9'
																																ELSE '0'  end ) 
																													ELSE k_per_edt2  END  + '</Квартал>' + CHAR(10)+
																				 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(K_YEAR_EDT2,''))) + '</Год>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR2,0),15,2))) + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR_2,0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(k_GAIN2,0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																		  SPACE(3) + '</СведенияОкорректировках>'	
															ELSE 
																''
															END	)			  
																		  
														FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																		and OT = @OT_R AND PER = @PER_R AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R 
																		AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																		AND CODE_STR = '400' 

												

													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT  @lcFNAME, 
														    (CASE WHEN (k_INSUR3 <> 0 OR k_GAIN3 <> 0) AND  K_YEAR_EDT3 <> 0
																  THEN
																		+ SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																				 SPACE(4) + '<НомерСтроки>' + '3' + '</НомерСтроки>' + CHAR(10)+
																				 SPACE(4) + '<ТипСтроки>'+'МЕСЦ'+'</ТипСтроки>' + CHAR(10)+
																				 SPACE(4) + '<Квартал>' +	CASE WHEN K_YEAR_EDT3 >= 2014 
																													THEN (CASE WHEN k_per_edt3 = '1' THEN '3' 
																																WHEN k_per_edt3 = '2' THEN '6' 
																																WHEN k_per_edt3 = '3' THEN '9'
																																ELSE '0'  end ) 
																													ELSE k_per_edt3  END + '</Квартал>' + CHAR(10)+
																				 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(K_YEAR_EDT3,''))) + '</Год>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR3,0),15,2))) + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR_3,0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(k_GAIN3,0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																		  SPACE(3) + '</СведенияОкорректировках>'
																ELSE 
																	''
																END	)			  
																																			  	
														FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																		and OT = @OT_R AND PER = @PER_R AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R 
																		AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																		AND CODE_STR = '400' 

												
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
															SELECT  @lcFNAME, 
																			  
																	(CASE WHEN (k_INSUR4 <> 0 OR k_GAIN4 <> 0) AND  K_YEAR_EDT4 <> 0
																		  THEN  
																			+ SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																					 SPACE(4) + '<НомерСтроки>' + '4' + '</НомерСтроки>' + CHAR(10)+
																					 SPACE(4) + '<ТипСтроки>'+'МЕСЦ'+'</ТипСтроки>' + CHAR(10)+
																					 SPACE(4) + '<Квартал>' +	CASE WHEN K_YEAR_EDT4 >= 2014 
																													THEN (CASE WHEN k_per_edt4 = '1' THEN '3' 
																																WHEN k_per_edt4 = '2' THEN '6' 
																																WHEN k_per_edt4 = '3' THEN '9'
																																ELSE '0'  end ) 
																													ELSE k_per_edt4  END + '</Квартал>' + CHAR(10)+
																					 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(K_YEAR_EDT4,''))) + '</Год>' + CHAR(10)+
																					 SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR4,0),15,2))) + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																					 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR_4,0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																					 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(k_GAIN4,0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																			  SPACE(3) + '</СведенияОкорректировках>'	
																	  ELSE 
																		''
																	  END	)			  
																				  
															FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																			and OT = @OT_R AND PER = @PER_R AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R 
																			AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																			AND CODE_STR = '400' 																															


													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT  @lcFNAME,
																(CASE WHEN (k_INSUR5 <> 0 OR k_GAIN5 <> 0) AND  K_YEAR_EDT5 <> 0
																	  THEN  
																		+	SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																				 SPACE(4) + '<НомерСтроки>' + '5' + '</НомерСтроки>' + CHAR(10)+
																				 SPACE(4) + '<ТипСтроки>'+'МЕСЦ'+'</ТипСтроки>' + CHAR(10)+
																				 SPACE(4) + '<Квартал>' +	CASE WHEN K_YEAR_EDT5 >= 2014 
																													THEN (CASE WHEN k_per_edt5 = '1' THEN '3' 
																																WHEN k_per_edt5 = '2' THEN '6' 
																																WHEN k_per_edt5 = '3' THEN '9'
																																ELSE '0'  end ) 
																													ELSE k_per_edt5  END + '</Квартал>' + CHAR(10)+
																				 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(K_YEAR_EDT5,''))) + '</Год>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR5,0),15,2))) + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR_5,0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(k_GAIN5,0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																		  SPACE(3) + '</СведенияОкорректировках>'	
																	  ELSE 
																		''
																	  END	)  
														FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																		and OT = @OT_R AND PER = @PER_R AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R 
																		AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																		AND CODE_STR = '400' 

												
												INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT  @lcFNAME,
															(CASE WHEN (k_INSUR1<>0 or k_INSUR2 <> 0 OR k_INSUR3<>0 OR k_INSUR4<>0 OR k_INSUR5 <> 0) OR (k_INSUR_1<>0 or k_INSUR_2 <> 0 OR k_INSUR_3<>0 OR k_INSUR_4<>0 OR k_INSUR_5 <> 0)
																  THEN  
																	+ SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																			 SPACE(4) + '<НомерСтроки>' + (CASE WHEN k_INSUR1<>0 OR k_INSUR_1<>0 and k_INSUR2 = 0 and k_INSUR3 = 0 and k_INSUR4 = 0 AND k_INSUR5 = 0 THEN '2'
																												WHEN k_INSUR2 <> 0 OR k_INSUR_2<>0 and k_INSUR3 = 0 and k_INSUR4 = 0 AND k_INSUR5 = 0 THEN '3'
																												WHEN k_INSUR3 <> 0 OR k_INSUR_3<>0 and k_INSUR4 = 0 AND k_INSUR5 = 0 THEN '4'
																												WHEN k_INSUR4 <> 0 OR k_INSUR_4<>0 AND k_INSUR5 = 0 THEN '5'
																												WHEN k_INSUR5 <> 0 OR k_INSUR_5<>0 THEN '6' ELSE '6' end) + '</НомерСтроки>' + CHAR(10)+
																			 SPACE(4) + '<ТипСтроки>'+'ИТОГ'+'</ТипСтроки>' + CHAR(10)+
																			/* SPACE(4) + '<Квартал>'  +	(CASE WHEN per_edt = '1' THEN '3' 
																										WHEN per_edt = '2' THEN '6' 
																										WHEN per_edt = '3' THEN '9'
																										ELSE '0'  end ) + '</Квартал>' + CHAR(10)+ 
																			 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(YEAR_EDT,''))) + '</Год>' + CHAR(10)+
																			 */SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + CASE WHEN K_YEAR_EDT1 >=2014 or K_YEAR_EDT2 >=2014 or K_YEAR_EDT3 >=2014 or K_YEAR_EDT4 >=2014 or K_YEAR_EDT5 >=2014 then RTRIM(LTRIM(STR(COALESCE((k_INSUR1+k_INSUR2+k_INSUR3+k_INSUR4+k_INSUR5),0),15,2))) 
																																		ELSE '0.00' end + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																			 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE((k_INSUR_1+k_INSUR_2+k_INSUR_3+k_INSUR_4+k_INSUR_5),0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																			 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE((k_GAIN1+k_GAIN2+k_GAIN3+k_GAIN4+k_GAIN5),0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																	  SPACE(3) + '</СведенияОкорректировках>'
															ELSE 
																''
															END		)	  	
													FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND PER = @PER_R AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R 
																	AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																	AND CODE_STR = '400'  
												
				
												
											end  
											--IF (SELECT COUNT (*) FROM #RES1 WHERE [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
											--						and OT = @OT_R AND DOC_DATE = @DATE_DOC_R ) > 1
											--BEGIN
											
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT  @lcFNAME, SPACE(3) + '<СведенияОсуммеВыплатИвознагражденийПоДопТарифу>' + CHAR(10)+
																			 SPACE(4) + '<НомерСтроки>' + LTRIM(RTRIM(ISNULL( NOM_PP,''))) + '</НомерСтроки>' + CHAR(10)+
																			 SPACE(4) + '<ТипСтроки>' + LTRIM(RTRIM(ISNULL( (CASE WHEN CODE_STR = '700' OR CODE_STR = '710' OR CODE_STR = '720' THEN 'ИТОГ' ELSE 'МЕСЦ' END),''))) + '</ТипСтроки>' + CHAR(10)+
																			 SPACE(4) + (CASE WHEN CODE_STR = '700' OR CODE_STR ='710' OR CODE_STR ='720' THEN '' 
																							else ('<Месяц>' +	(CASE WHEN CODE_STR = '700' OR CODE_STR ='710' OR CODE_STR ='720' THEN '' 
																									WHEN CODE_STR = '701' OR CODE_STR ='711' OR CODE_STR ='721' THEN  
																										(CASE WHEN UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'ИСХОДНАЯ' 
																											  THEN (CASE @PER_r WHEN '1' THEN '1'
																																WHEN '2' THEN '4'
																																WHEN '3' THEN '7'
																																ELSE '10' end)
						  																					  ELSE (CASE @PER_EDT_R WHEN '1' THEN '1'
						  																											WHEN '2' THEN '4'
						  																											WHEN '3' THEN '7'
						  																											ELSE '10' end)    
						  																					  END)
																									WHEN CODE_STR = '702' OR CODE_STR ='712' OR CODE_STR ='722' THEN 
																													(CASE WHEN UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'ИСХОДНАЯ' 
						  																								  THEN (CASE @PER_r WHEN '1' THEN '2'
						  																													WHEN '2' THEN '5'
						  																													WHEN '3' THEN '8'
						  																													ELSE '11' end)
						  																								  ELSE (CASE @PER_EDT_R WHEN '1' THEN '2'
						  																														WHEN '2' THEN '5'
						  																														WHEN '3' THEN '8'
						  																														ELSE '11' end)    
						  																								  END)
																									ELSE (CASE WHEN UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'ИСХОДНАЯ' 
						  																						  THEN (CASE @PER_r WHEN '1' THEN '3'
						  																											WHEN '2' THEN '6'
						  																											WHEN '3' THEN '9'
						  																											ELSE '12' end)
						  																						  ELSE (CASE @PER_EDT_R WHEN '1' THEN '3'
						  																												WHEN '2' THEN '6'
						  																												WHEN '3' THEN '9'
						  																												ELSE '12' end)    
						  																					   END)    
																							      end ) + '</Месяц>') 
																							end)		+ CHAR(10)+

										
																			 SPACE(4) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(CODE_STR,''))) + '</КодСтроки>' + CHAR(10)+
																			 SPACE(4) + '<КодСпециальнойОценкиУсловийТруда>' + LTRIM(RTRIM(ISNULL(CODE_SPO,'пустое'))) + '</КодСпециальнойОценкиУсловийТруда>' + CHAR(10)+
																			 SPACE(4) + '<СуммаВыплатПоДопТарифу27-1>' + RTRIM(LTRIM(STR(COALESCE(INC_T1M,0),15,2))) + '</СуммаВыплатПоДопТарифу27-1>' + CHAR(10)+
																			 SPACE(4) + '<СуммаВыплатПоДопТарифу27-2-18>' + RTRIM(LTRIM(STR(COALESCE(INC_T2M,0),15,2))) + '</СуммаВыплатПоДопТарифу27-2-18>' + CHAR(10)+
																	  SPACE(3) + '</СведенияОсуммеВыплатИвознагражденийПоДопТарифу>'	
													FROM #RES1 WHERE link = @LINK_R 	AND [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND DOC_DATE = @DATE_DOC_R  
																	AND ((SELECT top 1 isnull(INC_T1M,0) FROM #RES1 WHERE [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND DOC_DATE = @DATE_DOC_R AND CODE_STR = '700' ) > 0 OR
																		 (SELECT top 1 isnull(INC_T2M,0) FROM #RES1 WHERE [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND DOC_DATE = @DATE_DOC_R AND CODE_STR = '700' ) > 0 )
																	  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
											 --END	

															--exec SA_RSV1_EXPORT_0700_2014   19853	
													CREATE TABLE #STAZH_TMP ( link INt, FM VARCHAR(100), IM VARCHAR(100), OT VARCHAR(100), SNILS VARCHAR(14), date1 VARCHAR(10), date2 VARCHAR(10), 
																			  T_DOG int , [TU_CODE] VARCHAR (31) ,ter_koef NUMERIC(18,2),[OS_CODE] VARCHAR(94),[EX_CODE] VARCHAR (10), 
																			  osob_spis VARCHAR(20), is_dop_m TINYINT,is_dop_d TINYINT , is_dop VARCHAR(20), 
																			  [f_is_dop] VARCHAR(63),[P_CODE] VARCHAR(10),ud_dop_m INT,ud_dop_d INT  , ud_dop_k NUMERIC(18,2) , [f_ud_dop] VARCHAR(54)) 
													INSERT INTO #STAZH_TMP  (link , FM , IM, OT, SNILS, date1, date2,T_DOG, [TU_CODE],ter_koef, [OS_CODE],
																			  [EX_CODE], osob_spis, is_dop_m,is_dop_d, is_dop,[f_is_dop],[P_CODE],ud_dop_m,ud_dop_d, ud_dop_k, [f_ud_dop])
													SELECT	link = ROW_NUMBER() OVER (/*PARTITION */ ORDER BY ST.date1),--st.orders,
															FM = S.FM,
															IM = S.IM,
															OT = S.OT,
															SNILS = S.PF_NUM,
															date1 = convert(varchar(10),ST.date1, 104),
															date2 = convert(varchar(10),ST.date2, 104),
															T_DOG= s.forma,
															[TU_CODE] = st.f_ter_usl ,
															st.ter_koef,
															[OS_CODE] = st.f_osob_usl,
															[EX_CODE] = st.is_osnov,
															osob_spis = RTRIM(LTRIM(COALESCE(st.osob_k1,''))) + RTRIM(LTRIM(COALESCE(st.osob_k2,''))) + RTRIM(LTRIM(COALESCE(st.osob_k3,''))),
															is_dop_m = st.is_dop_m,
															is_dop_d = st.is_dop_d,
															is_dop = st.is_dop,
															[f_is_dop] = st.f_is_dop,
															[P_CODE] = st.ud_osnov,
															ud_dop_m = st.ud_dop_m,
															ud_dop_d = st.ud_dop_d,
															ud_dop_k = st.ud_dop_k,
															[f_ud_dop] 
													FROM dbo.SA_SZV4_SVEDENIA s 
													LEFT JOIN  dbo.SA_SZV4_STAZH st ON S.link1 = ST.link
													WHERE s.link = @LINK_DOC_OP AND  s.FM = @FM_R and s.IM = @IM_R  and s.OT = @OT_R 
														AND  s.PF_NUM= @SNILS_R  
														AND ((s.forma = 2  and NOT EXISTS (	select * FROM dbo.SA_SZV4_SVEDENIA s 
																							LEFT JOIN  dbo.SA_SZV4_STAZH st ON S.link1 = ST.link
																							WHERE s.link = @LINK_DOC_OP AND  s.FM = @FM_R and s.IM = @IM_R  and s.OT = @OT_R 
																								AND  s.PF_NUM= @SNILS_R  AND   s.forma = 1)
																				AND EXISTS (select * FROM dbo.SA_SZV4_SVEDENIA s 
																							LEFT JOIN  dbo.SA_SZV4_STAZH st ON S.link1 = ST.link
																							WHERE s.link = @LINK_DOC_OP AND  s.FM = @FM_R and s.IM = @IM_R  and s.OT = @OT_R 
																								AND  s.PF_NUM= @SNILS_R  AND   s.forma = 2))
															  or s.forma = 1  )
														
														
													ORDER BY  ST.date1, st.orders  
															  
													  
															  
								
													/*первая строка*/
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													Select @lcFNAME,
													CASE WHEN @TYPE_R <> 'ОТМЕНЯЮЩАЯ' THEN	
													/*CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' 	THEN	''
													ELSE*/	
														(CASE WHEN DATE1 <> '' THEN  
														+	SPACE(3) + '<СтажевыйПериод>' + CHAR(10)
														+		SPACE(4) + '<НомерСтроки>' + ltrim(rtrim(CONVERT(VARCHAR(2),link))) + '</НомерСтроки>' + CHAR(10)
														+		SPACE(4) + '<ДатаНачалаПериода>' + CONVERT(VARCHAR(10),DATE1,104) + '</ДатаНачалаПериода>' + CHAR(10)
														+		SPACE(4) + '<ДатаКонцаПериода>' + CONVERT(VARCHAR(10),DATE2,104) + '</ДатаКонцаПериода>' + CHAR(10)
														+				CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE([OS_CODE],''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE,''))) <> '' THEN 
														+		SPACE(4) + '<КоличествоЛьготныхСоставляющих>' + CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE,''))) <> '' THEN '1' ELSE '0' END + '</КоличествоЛьготныхСоставляющих>' + CHAR(10)		
														+		SPACE(4) + '<ЛьготныйСтаж>' + CHAR(10)
														+			SPACE(5) + '<НомерСтроки>1</НомерСтроки>' + CHAR(10)		
														+ 			SPACE(5) + '<ОсобенностиУчета>' + CHAR(10)
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE,''))) <> '' THEN
																			SPACE(7) + '<ТерриториальныеУсловия>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеТУ>' + RTRIM(LTRIM(COALESCE(TU_CODE,''))) + '</ОснованиеТУ>' + CHAR(10)
														+						CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE,''))) not in ('Ч31','Ч33','Ч34','Ч35','Ч36') then
																				(CASE WHEN RTRIM(LTRIM(COALESCE(STR(ter_koef,4,2),''))) <> '0.00' then SPACE(8) + '<Коэффициент>' + RTRIM(LTRIM(COALESCE(STR(ter_koef,4,2),''))) + '</Коэффициент>' + CHAR(10) else '' end)
																				else '' end
														+ 					SPACE(7) + '</ТерриториальныеУсловия>' + CHAR(10)
																			ELSE '' END
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(OS_CODE,''))) <> '' THEN
																			SPACE(7) + '<ОсобыеУсловияТруда>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеОУТ>' + LEFT(RTRIM(LTRIM(COALESCE(OS_CODE,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE,'')))) -1 )  + '</ОснованиеОУТ>' + CHAR(10)
														+						CASE WHEN LEFT(RTRIM(LTRIM(COALESCE(OS_CODE,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE,'')))) -1 ) = '27-1' or LEFT(RTRIM(LTRIM(COALESCE(OS_CODE,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE,'')))) -1 ) = '27-2' THEN
																					SPACE(8) + '<ПозицияСписка>' + UPPER(RTRIM(LTRIM(COALESCE(osob_spis,'')))) + '</ПозицияСписка>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ОсобыеУсловияТруда>' + CHAR(10)
																			ELSE '' END					
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(EX_CODE,''))) <> '' THEN
																			SPACE(7) + '<ИсчисляемыйСтаж>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеИС>' + RTRIM(LTRIM(COALESCE(EX_CODE,''))) + '</ОснованиеИС>' + CHAR(10)
														+						CASE WHEN COALESCE(f_is_dop,'') LIKE '%Ч.%' OR COALESCE(f_is_dop,'') LIKE '%МИН.%' THEN
																				SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
														+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE(is_dop_m,0),3))) + '</Часы>' + CHAR(10)
														+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE(is_dop_d,0),3))) + '</Минуты>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																				ELSE '' END
														+						CASE WHEN COALESCE(f_is_dop,'') LIKE '%МЕС.%' OR COALESCE(f_is_dop,'') LIKE '%ДН.%' THEN
																				SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
														+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
														+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE(is_dop_m,0),3))) + '</ВсеМесяцы>' + CHAR(10)
														+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE(is_dop_d,0),3))) + '</ВсеДни>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ИсчисляемыйСтаж>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE(is_dop,''))) <> '' THEN					
														+					SPACE(7) + '<ДекретДети>' + RTRIM(LTRIM(COALESCE(is_dop,''))) + '</ДекретДети>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE(is_dop,''))) <> '' and RTRIM(LTRIM(COALESCE(is_dop,''))) <> 'НЕОПЛ'  THEN
															+ 					(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_m,0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_d,0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_m,0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_d,0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(ud_dop_k,0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_k,0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																				WHEN RTRIM(LTRIM(COALESCE(is_dop,''))) = '' THEN
																				(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_m,0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_d,0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_m,0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_d,0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(ud_dop_k,0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_k,0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																			ELSE '' END
														+			SPACE(5) + '</ОсобенностиУчета>' + CHAR(10)
														+		SPACE(4) + '</ЛьготныйСтаж>' + CHAR(10)
																	ELSE '' END
														+	SPACE(3) + '</СтажевыйПериод>'
														ELSE '' END)
													/*END*/
													ELSE '' END
													FROM #STAZH_TMP
													WHERE SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R and OT = @OT_R  AND 
																( (T_DOG = 2 AND  NOT EXISTS (SELECT *  FROM #STAZH_TMP WHERE SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R and OT = @OT_R  AND T_DOG = 1)
																			AND  EXISTS (SELECT *  FROM #STAZH_TMP WHERE SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R and OT = @OT_R  AND T_DOG = 2))
																	OR  T_DOG = 1 	)	
													order by link , date1
																						
											/*		CREATE TABLE #STAZH_TMP ( link INt, FM VARCHAR(100), IM VARCHAR(100), OT VARCHAR(100), SNILS VARCHAR(14), date1 VARCHAR(10), date2 VARCHAR(10), ter_koef NUMERIC(18,2),osob_spis VARCHAR(20), is_dop_m TINYINT, 
															is_dop_d TINYINT , is_dop VARCHAR(20), ud_dop_m INT,ud_dop_d INT  , ud_dop_k NUMERIC(18,2)) 
													INSERT INTO #STAZH_TMP  (FM, IM, OT, SNILS, date1, date2, ter_koef,osob_spis, is_dop_m, 
															is_dop_d, is_dop, ud_dop_m,ud_dop_d, ud_dop_k)
													SELECT	FM = S.FM,
															IM = S.IM,
															OT = S.OT,
															SNILS = S.PF_NUM,
															date1 = convert(varchar(10),ST.date1, 104),
															date2 = convert(varchar(10),ST.date2, 104),
															st.ter_koef,
															osob_spis = RTRIM(LTRIM(COALESCE(st.osob_k1,''))) + RTRIM(LTRIM(COALESCE(st.osob_k2,''))) + RTRIM(LTRIM(COALESCE(st.osob_k3,''))),
															is_dop_m = st.is_dop_m,
															is_dop_d = st.is_dop_d,
															is_dop = st.is_dop,
															ud_dop_m = st.ud_dop_m,
															ud_dop_d = st.ud_dop_d,
															ud_dop_k = st.ud_dop_k
													FROM dbo.SA_SZV4_SVEDENIA s 
													LEFT JOIN  dbo.SA_SZV4_STAZH st ON S.link1 = ST.link
													WHERE s.link = @LINK_DOC_OP AND  s.FM = @FM_R and s.IM = @IM_R  and s.OT = @OT_R 
														AND  s.PF_NUM= @SNILS_R 
													ORDER BY ST.date1
													
													SET @NEXT_NUM3 = 0
													UPDATE #STAZH_TMP SET @NEXT_NUM3 = @NEXT_NUM3 + 1, link = @NEXT_NUM3

													
													/*первая строка*/
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													Select @lcFNAME,
													CASE WHEN @TYPE_R <> 'ОТМЕНЯЮЩАЯ' THEN	
													/*CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' 	THEN	''
													ELSE*/	
														(CASE WHEN DATE_BEGIN1 <> '' THEN  
														+	SPACE(3) + '<СтажевыйПериод>' + CHAR(10)
														+		SPACE(4) + '<НомерСтроки>' + '1' + '</НомерСтроки>' + CHAR(10)
														+		SPACE(4) + '<ДатаНачалаПериода>' + CONVERT(VARCHAR(10),DATE_BEGIN1,104) + '</ДатаНачалаПериода>' + CHAR(10)
														+		SPACE(4) + '<ДатаКонцаПериода>' + CONVERT(VARCHAR(10),DATE_END1,104) + '</ДатаКонцаПериода>' + CHAR(10)
														+				CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE1,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE1,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE1,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop1,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE1,''))) <> '' THEN 
														+		SPACE(4) + '<КоличествоЛьготныхСоставляющих>' + CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE1,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE1,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE1,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop1,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE1,''))) <> '' THEN '1' ELSE '0' END + '</КоличествоЛьготныхСоставляющих>' + CHAR(10)		
														+		SPACE(4) + '<ЛьготныйСтаж>' + CHAR(10)
														+			SPACE(5) + '<НомерСтроки>1</НомерСтроки>' + CHAR(10)		
														+ 			SPACE(5) + '<ОсобенностиУчета>' + CHAR(10)
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE1,''))) <> '' THEN
																			SPACE(7) + '<ТерриториальныеУсловия>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеТУ>' + RTRIM(LTRIM(COALESCE(TU_CODE1,''))) + '</ОснованиеТУ>' + CHAR(10)
														+						CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE1,''))) not in ('Ч31','Ч33','Ч34','Ч35','Ч36') then
																				(CASE WHEN RTRIM(LTRIM(COALESCE(STR((SELECT ter_koef FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),4,2),''))) <> '0.00' then SPACE(8) + '<Коэффициент>' + RTRIM(LTRIM(COALESCE(STR((SELECT ter_koef FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),4,2),''))) + '</Коэффициент>' + CHAR(10) else '' end)
																				else '' end
														+ 					SPACE(7) + '</ТерриториальныеУсловия>' + CHAR(10)
																			ELSE '' END
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(OS_CODE1,''))) <> '' THEN
																			SPACE(7) + '<ОсобыеУсловияТруда>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеОУТ>' + LEFT(RTRIM(LTRIM(COALESCE(OS_CODE1,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE1,'')))) -1 )  + '</ОснованиеОУТ>' + CHAR(10)
														+						CASE WHEN LEFT(RTRIM(LTRIM(COALESCE(OS_CODE1,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE1,'')))) -1 ) = '27-1' or LEFT(RTRIM(LTRIM(COALESCE(OS_CODE1,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE1,'')))) -1 ) = '27-2' THEN
																					SPACE(8) + '<ПозицияСписка>' + UPPER(RTRIM(LTRIM(COALESCE((SELECT osob_spis FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),'')))) + '</ПозицияСписка>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ОсобыеУсловияТруда>' + CHAR(10)
																			ELSE '' END					
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(EX_CODE1,''))) <> '' THEN
																			SPACE(7) + '<ИсчисляемыйСтаж>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеИС>' + RTRIM(LTRIM(COALESCE(EX_CODE1,''))) + '</ОснованиеИС>' + CHAR(10)
														+						CASE WHEN COALESCE(f_is_dop1,'') LIKE '%Ч.%' OR COALESCE(f_is_dop1,'') LIKE '%МИН.%' THEN
																				SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
														+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</Часы>' + CHAR(10)
														+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</Минуты>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																				ELSE '' END
														+						CASE WHEN COALESCE(f_is_dop1,'') LIKE '%МЕС.%' OR COALESCE(f_is_dop1,'') LIKE '%ДН.%' THEN
																				SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
														+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
														+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</ВсеМесяцы>' + CHAR(10)
														+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</ВсеДни>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ИсчисляемыйСтаж>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),''))) <> '' THEN					
														+					SPACE(7) + '<ДекретДети>' + RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),''))) + '</ДекретДети>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),''))) <> '' and RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),''))) <> 'НЕОПЛ'  THEN
															+ 					(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE1,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE1,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop1,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop1,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop1,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop1,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																				WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),''))) = '' THEN
																				(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE1,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE1,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop1,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop1,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop1,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop1,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN1 AND date2 = r.DATE_END1 AND link = 1),0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																			ELSE '' END
														+			SPACE(5) + '</ОсобенностиУчета>' + CHAR(10)
														+		SPACE(4) + '</ЛьготныйСтаж>' + CHAR(10)
																	ELSE '' END
														+	SPACE(3) + '</СтажевыйПериод>'
														ELSE '' END)
													/*END*/
													ELSE '' END
													FROM #RES1 r
													WHERE link = @LINK_R 	AND [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																	and CODE_STR  ='700'													

													/*вторая строка*/
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													Select @lcFNAME,
													CASE WHEN @TYPE_R <> 'ОТМЕНЯЮЩАЯ' THEN	
													/*CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' 	THEN	''
													ELSE*/	
														(CASE WHEN DATE_BEGIN2 <> '' THEN  
														+	SPACE(3) + '<СтажевыйПериод>' + CHAR(10)
														+		SPACE(4) + '<НомерСтроки>' + '2' + '</НомерСтроки>' + CHAR(10)
														+		SPACE(4) + '<ДатаНачалаПериода>' + CONVERT(VARCHAR(10),DATE_BEGIN2,104) + '</ДатаНачалаПериода>' + CHAR(10)
														+		SPACE(4) + '<ДатаКонцаПериода>' + CONVERT(VARCHAR(10),DATE_END2,104) + '</ДатаКонцаПериода>' + CHAR(10)
														+				CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE2,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE2,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE2,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop2,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE2,''))) <> '' THEN 
														+		SPACE(4) + '<КоличествоЛьготныхСоставляющих>' + CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE2,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE2,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE2,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop2,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE2,''))) <> '' THEN '1' ELSE '0' END + '</КоличествоЛьготныхСоставляющих>' + CHAR(10)		
														+		SPACE(4) + '<ЛьготныйСтаж>' + CHAR(10)
														+			SPACE(5) + '<НомерСтроки>1</НомерСтроки>' + CHAR(10)		
														+ 			SPACE(5) + '<ОсобенностиУчета>' + CHAR(10)
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE2,''))) <> '' THEN
																			SPACE(7) + '<ТерриториальныеУсловия>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеТУ>' + RTRIM(LTRIM(COALESCE(TU_CODE2,''))) + '</ОснованиеТУ>' + CHAR(10)
														+						CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE2,''))) not in ('Ч31','Ч33','Ч34','Ч35','Ч36') then
																				(CASE WHEN RTRIM(LTRIM(COALESCE(STR((SELECT ter_koef FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),4,2),''))) <> '0.00' then SPACE(8) + '<Коэффициент>' + RTRIM(LTRIM(COALESCE(STR((SELECT ter_koef FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),4,2),''))) + '</Коэффициент>' + CHAR(10) else '' end)
																				else '' end
														+ 					SPACE(7) + '</ТерриториальныеУсловия>' + CHAR(10)
																			ELSE '' END
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(OS_CODE2,''))) <> '' THEN
																			SPACE(7) + '<ОсобыеУсловияТруда>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеОУТ>' + LEFT(RTRIM(LTRIM(COALESCE(OS_CODE2,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE2,''))))  -1) + '</ОснованиеОУТ>' + CHAR(10)
														+						CASE WHEN LEFT(RTRIM(LTRIM(COALESCE(OS_CODE2,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE2,''))))  -1) = '27-1' or LEFT(RTRIM(LTRIM(COALESCE(OS_CODE2,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE2,''))))  -1) = '27-2' THEN
																					SPACE(8) + '<ПозицияСписка>' + UPPER(RTRIM(LTRIM(COALESCE((SELECT osob_spis FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),'')))) + '</ПозицияСписка>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ОсобыеУсловияТруда>' + CHAR(10)
																			ELSE '' END					
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(EX_CODE2,''))) <> '' THEN
																			SPACE(7) + '<ИсчисляемыйСтаж>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеИС>' + RTRIM(LTRIM(COALESCE(EX_CODE2,''))) + '</ОснованиеИС>' + CHAR(10)
														+						CASE WHEN COALESCE(f_is_dop2,'') LIKE '%Ч.%' OR COALESCE(f_is_dop2,'') LIKE '%МИН.%' THEN
																				SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
														+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</Часы>' + CHAR(10)
														+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</Минуты>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																				ELSE '' END
														+						CASE WHEN COALESCE(f_is_dop2,'') LIKE '%МЕС.%' OR COALESCE(f_is_dop2,'') LIKE '%ДН.%' THEN
																				SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
														+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
														+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</ВсеМесяцы>' + CHAR(10)
														+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</ВсеДни>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ИсчисляемыйСтаж>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),''))) <> '' THEN					
														+					SPACE(7) + '<ДекретДети>' + RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),''))) + '</ДекретДети>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),''))) <> '' and RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),''))) <> 'НЕОПЛ'  THEN
															+ 					(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE2,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE2,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop2,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop2,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop2,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop2,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																				WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),''))) = '' THEN
																				(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE2,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE2,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop2,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop2,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop2,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop2,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN2 AND date2 = r.DATE_END2 AND link = 2),0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																			ELSE '' END
														+			SPACE(5) + '</ОсобенностиУчета>' + CHAR(10)
														+		SPACE(4) + '</ЛьготныйСтаж>' + CHAR(10)
																	ELSE '' END
														+	SPACE(3) + '</СтажевыйПериод>'
														ELSE '' END)
													/*END*/
													ELSE '' END
													FROM #RES1 r
													WHERE link = @LINK_R 	AND [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																	and CODE_STR  ='700'				
													
													/*третья строка*/
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													Select @lcFNAME,
													CASE WHEN @TYPE_R <> 'ОТМЕНЯЮЩАЯ' THEN	
													/*CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' 	THEN	''
													ELSE*/	
														(CASE WHEN DATE_BEGIN3 <> '' THEN  
														+	SPACE(3) + '<СтажевыйПериод>' + CHAR(10)
														+		SPACE(4) + '<НомерСтроки>' + '3' + '</НомерСтроки>' + CHAR(10)
														+		SPACE(4) + '<ДатаНачалаПериода>' + CONVERT(VARCHAR(10),DATE_BEGIN3,104) + '</ДатаНачалаПериода>' + CHAR(10)
														+		SPACE(4) + '<ДатаКонцаПериода>' + CONVERT(VARCHAR(10),DATE_END3,104) + '</ДатаКонцаПериода>' + CHAR(10)
														+				CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE3,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE3,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE3,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop3,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE3,''))) <> '' THEN 
														+		SPACE(4) + '<КоличествоЛьготныхСоставляющих>' + CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE3,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE3,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE3,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop3,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE3,''))) <> '' THEN '1' ELSE '0' END + '</КоличествоЛьготныхСоставляющих>' + CHAR(10)		
														+		SPACE(4) + '<ЛьготныйСтаж>' + CHAR(10)
														+			SPACE(5) + '<НомерСтроки>1</НомерСтроки>' + CHAR(10)		
														+ 			SPACE(5) + '<ОсобенностиУчета>' + CHAR(10)
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE3,''))) <> '' THEN
																			SPACE(7) + '<ТерриториальныеУсловия>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеТУ>' + RTRIM(LTRIM(COALESCE(TU_CODE3,''))) + '</ОснованиеТУ>' + CHAR(10)
														+						CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE3,''))) not in ('Ч31','Ч33','Ч34','Ч35','Ч36') then
																				(CASE WHEN RTRIM(LTRIM(COALESCE(STR((SELECT ter_koef FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),4,2),''))) <> '0.00' then SPACE(8) + '<Коэффициент>' + RTRIM(LTRIM(COALESCE(STR((SELECT ter_koef FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),4,2),''))) + '</Коэффициент>' + CHAR(10) else '' end)
																				else '' end
														+ 					SPACE(7) + '</ТерриториальныеУсловия>' + CHAR(10)
																			ELSE '' END
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(OS_CODE3,''))) <> '' THEN
																			SPACE(7) + '<ОсобыеУсловияТруда>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеОУТ>' + LEFT(RTRIM(LTRIM(COALESCE(OS_CODE3,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE3,''))))  -1 ) + '</ОснованиеОУТ>' + CHAR(10)
														+						CASE WHEN LEFT(RTRIM(LTRIM(COALESCE(OS_CODE3,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE3,''))))  -1 ) = '27-1' or LEFT(RTRIM(LTRIM(COALESCE(OS_CODE3,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE3,''))))  -1 ) = '27-2' THEN
																					SPACE(8) + '<ПозицияСписка>' + UPPER(RTRIM(LTRIM(COALESCE((SELECT osob_spis FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),'')))) + '</ПозицияСписка>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ОсобыеУсловияТруда>' + CHAR(10)
																			ELSE '' END					
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(EX_CODE3,''))) <> '' THEN
																			SPACE(7) + '<ИсчисляемыйСтаж>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеИС>' + RTRIM(LTRIM(COALESCE(EX_CODE3,''))) + '</ОснованиеИС>' + CHAR(10)
														+						CASE WHEN COALESCE(f_is_dop3,'') LIKE '%Ч.%' OR COALESCE(f_is_dop3,'') LIKE '%МИН.%' THEN
																				SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
														+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</Часы>' + CHAR(10)
														+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</Минуты>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																				ELSE '' END
														+						CASE WHEN COALESCE(f_is_dop3,'') LIKE '%МЕС.%' OR COALESCE(f_is_dop3,'') LIKE '%ДН.%' THEN
																				SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
														+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
														+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</ВсеМесяцы>' + CHAR(10)
														+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</ВсеДни>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ИсчисляемыйСтаж>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),''))) <> '' THEN					
														+					SPACE(7) + '<ДекретДети>' + RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),''))) + '</ДекретДети>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),''))) <> '' and RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),''))) <> 'НЕОПЛ'  THEN
															+ 					(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE3,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE3,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop3,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop3,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop3,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop3,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																				WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),''))) = '' THEN
																				(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE3,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE3,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop3,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop3,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop3,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop3,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN3 AND date2 = r.DATE_END3 AND link = 3),0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																			ELSE '' END
														+			SPACE(5) + '</ОсобенностиУчета>' + CHAR(10)
														+		SPACE(4) + '</ЛьготныйСтаж>' + CHAR(10)
																	ELSE '' END
														+	SPACE(3) + '</СтажевыйПериод>'
														ELSE '' END ) 
													/*END*/
													ELSE '' END
													FROM #RES1 r
													WHERE link = @LINK_R 	AND [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																	and CODE_STR  ='700'	

													/*четвертая строка*/
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													Select @lcFNAME,
													CASE WHEN @TYPE_R <> 'ОТМЕНЯЮЩАЯ' THEN	
													/*CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' 	THEN	''
													ELSE*/	
														(CASE WHEN DATE_BEGIN4 <> '' THEN  
														+	SPACE(3) + '<СтажевыйПериод>' + CHAR(10)
														+		SPACE(4) + '<НомерСтроки>' + '4' + '</НомерСтроки>' + CHAR(10)
														+		SPACE(4) + '<ДатаНачалаПериода>' + CONVERT(VARCHAR(10),DATE_BEGIN4,104) + '</ДатаНачалаПериода>' + CHAR(10)
														+		SPACE(4) + '<ДатаКонцаПериода>' + CONVERT(VARCHAR(10),DATE_END4,104) + '</ДатаКонцаПериода>' + CHAR(10)
														+				CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE4,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE4,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE4,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop4,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE4,''))) <> '' THEN 
														+		SPACE(4) + '<КоличествоЛьготныхСоставляющих>' + CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE4,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE4,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE4,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop4,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE4,''))) <> '' THEN '1' ELSE '0' END + '</КоличествоЛьготныхСоставляющих>' + CHAR(10)		
														+		SPACE(4) + '<ЛьготныйСтаж>' + CHAR(10)
														+			SPACE(5) + '<НомерСтроки>1</НомерСтроки>' + CHAR(10)		
														+ 			SPACE(5) + '<ОсобенностиУчета>' + CHAR(10)
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE4,''))) <> '' THEN
																			SPACE(7) + '<ТерриториальныеУсловия>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеТУ>' + RTRIM(LTRIM(COALESCE(TU_CODE4,''))) + '</ОснованиеТУ>' + CHAR(10)
														+						CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE4,''))) not in ('Ч31','Ч33','Ч34','Ч35','Ч36') then
																				(CASE WHEN RTRIM(LTRIM(COALESCE(STR((SELECT ter_koef FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),4,2),''))) <> '0.00' then SPACE(8) + '<Коэффициент>' + RTRIM(LTRIM(COALESCE(STR((SELECT ter_koef FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),4,2),''))) + '</Коэффициент>' + CHAR(10) else '' end)
																				else '' end
														+ 					SPACE(7) + '</ТерриториальныеУсловия>' + CHAR(10)
																			ELSE '' END
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(OS_CODE4,''))) <> '' THEN
																			SPACE(7) + '<ОсобыеУсловияТруда>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеОУТ>' + LEFT(RTRIM(LTRIM(COALESCE(OS_CODE4,''))), CHARINDEX(',',RTRIM(LTRIM(COALESCE(OS_CODE4,''))))  -1 ) + '</ОснованиеОУТ>' + CHAR(10)
														+						CASE WHEN LEFT(RTRIM(LTRIM(COALESCE(OS_CODE4,''))), CHARINDEX(',',RTRIM(LTRIM(COALESCE(OS_CODE4,''))))  -1 ) = '27-1' or LEFT(RTRIM(LTRIM(COALESCE(OS_CODE4,''))), CHARINDEX(',',RTRIM(LTRIM(COALESCE(OS_CODE4,''))))  -1 ) = '27-2' THEN
																					SPACE(8) + '<ПозицияСписка>' + UPPER(RTRIM(LTRIM(COALESCE((SELECT osob_spis FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),'')))) + '</ПозицияСписка>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ОсобыеУсловияТруда>' + CHAR(10)
																			ELSE '' END					
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(EX_CODE4,''))) <> '' THEN
																			SPACE(7) + '<ИсчисляемыйСтаж>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеИС>' + RTRIM(LTRIM(COALESCE(EX_CODE4,''))) + '</ОснованиеИС>' + CHAR(10)
														+						CASE WHEN COALESCE(f_is_dop4,'') LIKE '%Ч.%' OR COALESCE(f_is_dop4,'') LIKE '%МИН.%' THEN
																				SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
														+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</Часы>' + CHAR(10)
														+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</Минуты>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																				ELSE '' END
														+						CASE WHEN COALESCE(f_is_dop4,'') LIKE '%МЕС.%' OR COALESCE(f_is_dop4,'') LIKE '%ДН.%' THEN
																				SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
														+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
														+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</ВсеМесяцы>' + CHAR(10)
														+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT is_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</ВсеДни>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ИсчисляемыйСтаж>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),''))) <> '' THEN					
														+					SPACE(7) + '<ДекретДети>' + RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),''))) + '</ДекретДети>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),''))) <> '' and RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),''))) <> 'НЕОПЛ'  THEN
															+ 					(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE4,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE4,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop4,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop4,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop4,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop4,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																				WHEN RTRIM(LTRIM(COALESCE((SELECT is_dop FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),''))) = '' THEN
																				(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE4,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE4,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop4,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop4,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop4,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop4,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_m FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_d FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE((SELECT ud_dop_k FROM #STAZH_TMP WHERE date1 = r.DATE_BEGIN4 AND date2 = r.DATE_END4 AND link = 4),0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																			ELSE '' END
														+			SPACE(5) + '</ОсобенностиУчета>' + CHAR(10)
														+		SPACE(4) + '</ЛьготныйСтаж>' + CHAR(10)
																	ELSE '' END
														+	SPACE(3) + '</СтажевыйПериод>'
														ELSE '' END ) 	
													/*END*/
													ELSE '' END
													FROM #RES1 r
													WHERE link = @LINK_R 	AND [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R 
																	and OT = @OT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																	and CODE_STR  ='700'	
												*/
												DROP TABLE #STAZH_TMP
												

												INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) 
												SELECT @lcFNAME, SPACE(3) + '<ДатаЗаполнения>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),@modify_date,104),''))) + '</ДатаЗаполнения>'		

										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME,SPACE(2) + '</СВЕДЕНИЯ_О_СУММЕ_ВЫПЛАТ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ>'									
							end

							FETCH NEXT FROM @Cur4 INTO @LINK_R, @TYPE_R,@SNILS_R,@PER_R,@YEAR_BEGIN_R,@PER_EDT_R,@YEAR_EDT_R, 
													@FM_R,@IM_R,@OT_R, @DATE_DOC_R/*, @FNAME_R, @NOM_PACH_R*/
						END
						CLOSE @Cur4
						DEALLOCATE @Cur4		

				------- окончание файла (Документы раздела 6 РСВ-1)
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, SPACE(1) + '</ПачкаВходящихДокументов>'
				UNION ALL SELECT @lcFNAME, SPACE(0) + '</ФайлПФР>'	
				END
			END
	end
	


	FETCH NEXT FROM @Cur3 INTO @LINK_OP, @TYP_D, @NOM_PP, @NGROUP /*Номер пачки*/,@SUM_BASE, @SUM_STR, @PERS_CNT,@DATE_DOC,@PER, @YEAR_BEGIN, @PER_EDT, @YEAR_EDT, @lcFNAME/*наименование файла*/ , @LINK_DOC_OP

	
end

CLOSE @Cur3
DEALLOCATE @Cur3


				
SET NOCOUNT OFF

select * from #OUTPUT order by [ID]
--exec SA_RSV1_EXPORT_0700_2014 41964
    


GO


GRANT EXECUTE ON dbo.[SA_RSV1_EXPORT_0700_2014] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[KIR_EXEC_KADR_TABEL_REPORT]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KIR_EXEC_KADR_TABEL_REPORT]

GO
/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE [dbo].KIR_EXEC_KADR_TABEL_REPORT
	@varKSPARAM_NAME VARCHAR(254),
	@varKSnOption1 INT= 1,
	@varKSnCheck1 INT = 0,
	@nSort3 int = 0 /*сортировка 3*/,
	@nCheck3 tinyint = 0 /*Фио полностью*/,
	@nCheck5 tinyint = 0 /* Пустой табель */,
	@nOption1 tinyint = 0 /*Форма табеля */	
AS
BEGIN

	DECLARE @varKSnLINKDoc INT, @varKSSUBDIV VARCHAR(254), @varKSSUBDIV_CODE VARCHAR(10)
	SET @varKSnLINKDoc = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE USERS = SUSER_SID() AND PROPERTY = 
		(SELECT LINK FROM S_PROPERTY WHERE CODE='SQUERY_NASTR_VALUE' ) AND LINK_UP=
		(SELECT LINK FROM OBJECT_VAR WHERE CODE='SYS_T13_FORM_MAIN_PARAM' ) )



	DECLARE
		@varKSDIV_CODE VARCHAR(10), @varKSDIV_NAME VARCHAR(254),
		@varKSTI_CODE VARCHAR(10), @varKSTI_NAME VARCHAR(254),
		@varKSEXP_CODE VARCHAR(10), @varKSEXP_NAME VARCHAR(254)

	IF @nOption1 = 1
		EXEC dbo.SA_PRINT_TABEL_T13 @varKSnLINKDoc, @varKSnOption1, @varKSnCheck1, @nSort3, @nCheck3,@nCheck5,
			@varKSSUBDIV OUTPUT, @varKSSUBDIV_CODE OUTPUT,
			@varKSDIV_CODE OUTPUT, @varKSDIV_NAME OUTPUT,
			@varKSTI_CODE OUTPUT, @varKSTI_NAME OUTPUT,
			@varKSEXP_CODE OUTPUT, @varKSEXP_NAME OUTPUT	
	ELSE  	

		IF @nOption1 <= 5  	

			EXEC dbo.SA_PRINT_TABEL @varKSnLINKDoc, @varKSnOption1, @varKSnCheck1, @nSort3, @nCheck3,@nCheck5,
				@varKSSUBDIV OUTPUT, @varKSSUBDIV_CODE OUTPUT,
				@varKSDIV_CODE OUTPUT, @varKSDIV_NAME OUTPUT,
				@varKSTI_CODE OUTPUT, @varKSTI_NAME OUTPUT,
				@varKSEXP_CODE OUTPUT, @varKSEXP_NAME OUTPUT

		ELSE			
		
			IF @nOption1 = 6
				
				EXEC dbo.SA_PRINT_TABEL_421m @varKSnLINKDoc, @varKSnOption1, @varKSnCheck1, @nSort3, @nCheck3,@nCheck5,
					@varKSSUBDIV OUTPUT, @varKSSUBDIV_CODE OUTPUT,
					@varKSDIV_CODE OUTPUT, @varKSDIV_NAME OUTPUT,
					@varKSTI_CODE OUTPUT, @varKSTI_NAME OUTPUT,
					@varKSEXP_CODE OUTPUT, @varKSEXP_NAME OUTPUT

			ELSE
				IF @nOption1 = 7
					EXEC dbo.SA_PRINT_TABEL_148n @varKSnLINKDoc, @varKSnOption1, @varKSnCheck1, @nSort3, @nCheck3,@nCheck5,
						@varKSSUBDIV OUTPUT, @varKSSUBDIV_CODE OUTPUT,
						@varKSDIV_CODE OUTPUT, @varKSDIV_NAME OUTPUT,
						@varKSTI_CODE OUTPUT, @varKSTI_NAME OUTPUT,
						@varKSEXP_CODE OUTPUT, @varKSEXP_NAME OUTPUT
				ELSE
					
					EXEC dbo.SA_PRINT_TABEL_NEW @varKSnLINKDoc, @varKSnOption1, @varKSnCheck1, @nSort3, @nCheck3,@nCheck5,
						@varKSSUBDIV OUTPUT, @varKSSUBDIV_CODE OUTPUT,
						@varKSDIV_CODE OUTPUT, @varKSDIV_NAME OUTPUT,
						@varKSTI_CODE OUTPUT, @varKSTI_NAME OUTPUT,
						@varKSEXP_CODE OUTPUT, @varKSEXP_NAME OUTPUT
						

	DECLARE @varKSstart_date DATETIME, @varKSEND_DATE DATETIME
	SET  @varKSstart_date  = (SELECT TOP 1  PERIOD FROM TABELS WHERE LINK_DOC = @varKSnLINKDoc )
	SELECT @varKSEND_DATE  = dbo.dateEndOfMonth(@varKSstart_date)
		--DATEADD( 
		--	DAY, 
		--	ISNULL ( 
		--		(SELECT MAX(DAY) FROM DAYSHOURS DH, TABELS T WHERE DOP_TAB = 0 AND DH.LINK_UP = T.LINK AND T.LINK_DOC = @varKSnLINKDoc), 
		--		1
		--	) -1,
		--	@varKSstart_date
		--)

	SELECT 
		DD.FULL_NAME, 
		DD.OKPO AS OKPO,
		@varKSSUBDIV AS SUBDIV,
		@varKSSUBDIV_CODE AS CODE_SUB,
		@varKSDIV_CODE AS CODE_FKR_D,
		@varKSDIV_NAME AS NAME_FKR_D,
		@varKSTI_CODE AS CODE_FKR_T,
		@varKSTI_NAME AS NAME_FKR_T,
		@varKSEXP_CODE AS CODE_FKR_E,
		@varKSEXP_NAME AS NAME_FKR_E,
		D.DATE AS DOC_DATE,  D.NUMBER AS DOC_NUM,
		@varKSstart_date AS START_DATE, @varKSEND_DATE AS END_DATE,
		MONTH( @varKSstart_date) AS N_MONTH, 
		YEAR( @varKSstart_date) AS N_YEAR
	FROM dbo.DICTIONARY_DEPARTMENT DD, SDOC D
	WHERE 
		DD.LINK = D.LINK_DEP
		AND D.LINK = @varKSnLINKDoc

END




GO


GRANT EXECUTE ON dbo.[KIR_EXEC_KADR_TABEL_REPORT] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_O_OTHER_FILL]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_O_OTHER_FILL]

GO

CREATE   PROCEDURE dbo.SD_O_OTHER_FILL
@LINK INT
AS  

DECLARE @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

--
DECLARE @ESNTR_OPTIONS_OPT5 INT
SET @ESNTR_OPTIONS_OPT5 = dbo.SA_GET_OPTION_BY_CODE('ESNTR_OPTIONS_OPT5')

--Предоставленные скидки с предыдущего места работы
CREATE TABLE #PREV_DED (LINK_PERS INT, LINK_INC INT, SUMMA NUMERIC(18,2))
--
INSERT INTO #PREV_DED (LINK_PERS, LINK_INC, SUMMA)
SELECT E.PERS_LINK, LINK_INC = T.LINK, SUMMA = SUM(PD.SUMMA_DED)
FROM 
	dbo.SD_EMPL_PREV_DED PD
	INNER JOIN dbo.DICTIONARY_TYP_INCOMS T with (nolock) ON T.REF_DEDUCT = PD.LINK_DED
	INNER JOIN dbo.EMPL E with (nolock) ON E.LINK = PD.LINK_EMPL
	INNER JOIN dbo.ITEM_MOVE IM with (nolock) ON IM.EMPL_LINK = E.LINK AND IM.ACTIVE = 1 AND IM.NEW_FACE=1
WHERE
	E.DEP_LINK = @DEP_LINK
	AND
	YEAR(IM.DATE_begin) = @varKSYear
	AND
	@ESNTR_OPTIONS_OPT5 = 1 --Учитывать вычеты, предоставленные на предыдущем месте работы
GROUP BY
	E.PERS_LINK, T.LINK

-- Расчёт скидки за месяц по физлицам в разрезе кодов дохода и источников
INSERT INTO dbo.SDOC_DOT_SKIDKI (LINK_UP, LINK_TAX, LINK_PERS, LINK_INC, LINK_VKR, LINK_EKR, SUMMA, [PERCENT])
SELECT 
	@LINK, S2.LINK_TAX, S2.LINK_PERS, S2.LINK_INC, S.LINK_VKR, S.LINK_EKR,
	--Остаток скидки в пределах месячного дохода
	--CASE WHEN S2.SUMMA_M > CASE WHEN ISNULL(SP.SUMMA,0) < SK.PREDEL THEN (SK.PREDEL - ISNULL(SP.SUMMA,0)) * (S.SUMMA_M / S2.SUMMA_M) ELSE 0 END
	--	THEN CASE WHEN ISNULL(SP.SUMMA,0) < SK.PREDEL THEN (SK.PREDEL - ISNULL(SP.SUMMA,0)) * (S.SUMMA_M / S2.SUMMA_M) ELSE 0 END
	--	ELSE S2.SUMMA_M
	--END,
	(
		CASE WHEN
			--Всего надо скидку
			(CASE WHEN ISNULL(S2.SUMMA,0) > ISNULL(SK.PREDEL,0) THEN ISNULL(SK.PREDEL,0) ELSE ISNULL(S2.SUMMA,0) END) > 0 
		THEN
		(
			--Всего надо скидку
			(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) - ISNULL(PD.SUMMA,0)
		)	
			----пропорционально кодам доходов
			* (S.SUMMA_M / S2.SUMMA_M)
		ELSE
		0 
		END	
	),
	[PERCENT] = ISNULL(I.[PERCENT],DR.[PERCENT])
FROM 
	#RANGE DR --Ставка налога
	INNER JOIN #SUMMA2 S2 ON -- Базовые суммы по физлицам в разрезе кодов дохода
							S2.LINK_TAX = DR.LINK_PAYS
	INNER JOIN #SUMMA S ON --Базовые суммы по физлицам в разрезе кодов дохода и источников
							S.LINK_TAX = S2.LINK_TAX AND S.LINK_PERS = S2.LINK_PERS AND S.LINK_INC = S2.LINK_INC
	INNER JOIN #SKIDKA SK ON --Информация о предельном размере скидки
							SK.LINK_INC = S.LINK_INC
	LEFT JOIN #SKIDKA_PREV SP ON -- Размер уже предоставленной скидки с начала года в разрезе кодов дохода
							SP.LINK_TAX = S2.LINK_TAX AND SP.LINK_PERS = S2.LINK_PERS AND SP.LINK_INC = S2.LINK_INC
	LEFT JOIN #PREV_DED PD ON --Предоставленные скидки с предыдущего места работы
						PD.LINK_PERS = S2.LINK_PERS AND PD.LINK_INC = S2.LINK_INC								
	LEFT JOIN #INV I ON --Инвалиды и процент по ним
						I.LINK = S2.LINK_PERS
WHERE
	S2.SUMMA_M <> 0
	

--===РАСЧЁТ ВЫЧЕТОВ
--Информация о предельном размере ВЫЧЕТА
CREATE TABLE #VYCHET (LINK_DED INT, PREDEL NUMERIC(18,2))
INSERT INTO #VYCHET (LINK_DED, PREDEL)
SELECT TI.LINK, D.PREDEL
FROM 
	dbo.Salary_deduct_esn(@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, LINK_EKR, SUMMA = SUM(SUMMA) FROM dbo.SDOC_DOT_VYCHET 
		WHERE LINK_UP = @LINK GROUP BY LINK_TAX, LINK_PERS, LINK_VKR, LINK_EKR
	) V
	ON V.LINK_TAX = DR.LINK_PAYS AND V.LINK_PERS = S.LINK_PERS AND V.LINK_VKR = S.LINK_VKR AND V.LINK_EKR = S.LINK_EKR
	LEFT JOIN #INV I ON I.LINK = S.LINK_PERS
GROUP BY
	ISNULL(I.[PERCENT],DR.[PERCENT]),
	DR.LINK_PAYS,
	P.CODE,
	P.NAME,
	S.LINK_VKR,
	F.CODE,
	S.LINK_EKR,
	G.CODE

DROP TABLE #SKIDKA
DROP TABLE #BASE
DROP TABLE #SUMMA
DROP TABLE #SUMMA2
DROP TABLE #SKIDKA_PREV
DROP TABLE #INV
DROP TABLE #TMP_VYCH
DROP TABLE #TMP_DOH
DROP TABLE #RANGE




GO


GRANT EXECUTE ON dbo.[SD_O_OTHER_FILL] TO PUBLIC

GO

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SZV4_PACHKA_CALC_Buffer3]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZV4_PACHKA_CALC_Buffer3]

GO

CREATE   PROCEDURE [dbo].SA_SZV4_PACHKA_CALC_Buffer3 (@BufferCode varchar(10), @link int, @Year int, @Month tinyint) 
AS

DECLARE @SQL VARCHAR(1000)

SET @SQL = '
delete from dbo.Buffer
where RTRIM(LTRIM(ID)) = RTRIM(LTRIM( ''' + @BufferCode + ''' ))
	and link IN (select S.link_pers from dbo.SZV4_SVEDENIA S where S.link_up = ' + CONVERT(VARCHAR(20),@LINK) + ')'
--EXEC (@SQL)	

CREATE TABLE #PERSON (LINK INT)	

SET @SQL = '
INSERT INTO #PERSON (LINK)
SELECT DISTINCT LINK FROM dbo.Buffer WHERE RTRIM(LTRIM(ID)) = RTRIM(LTRIM(''' + @BufferCode + '''))'
EXEC (@SQL)	

declare @DEP_LINK int
exec dbo.xd_whats_zb @DEP_LINK output

DECLARE @PER TINYINT, @MONTH_END TINYINT, @MONTH_BEG TINYINT, @VID_KOR TINYINT 

SELECT @VID_KOR = VID_KOR
FROM dbo.SZV4_PACHKA WHERE LINK = @link

IF @VID_KOR = 2
begin  
	SELECT @Year = @Year, @PER = PER_EDT, @MONTH_END = @Month
	FROM dbo.SZV4_PACHKA WHERE LINK = @link
end 
else 
begin
	SELECT @Year = YEAR_BEGIN, @PER = PER, @MONTH_END = MONTH_END
	FROM dbo.SZV4_PACHKA WHERE LINK = @link
end 
DECLARE @PeriodBegin datetime, @PeriodEnd datetime

SET @MONTH_BEG = (CASE @PER WHEN 1 THEN 1 WHEN 2 THEN 4 WHEN 3 THEN 7 WHEN 4 THEN 10 END)
SET @MONTH_END = (CASE WHEN @MONTH_END < (@MONTH_BEG+3-1) THEN @MONTH_END ELSE (@MONTH_BEG+3-1) END)

SELECT @PeriodBegin = dbo.ConvertDMY2Date(1,@MONTH_BEG,@Year), @PeriodEnd = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@MONTH_END,@Year))

--ВЫДЕЛЕНИЕ КАТЕГОРИЙ ФИЗ.ЛИЦ
--ИНВАЛИДЫ
DECLARE @LINK_OZOI INT
SET @LINK_OZOI = ISNULL((SELECT TOP 1 LINK FROM dbo.SA_PFR_KATEG WHERE LINK2 = 3 AND @Year BETWEEN YBEG AND YEND),1)

------	у кого была инвалидность в заданном периоде
SELECT PERS_LINK, DATE_BEGIN = MIN(ISNULL(I.DATE_BEGIN,@PeriodBegin)), DATE_END = MAX(ISNULL(I.DATE_END,@PeriodEnd))
INTO #PERS_INV
FROM dbo.PERS_INVALID I
WHERE ISNULL(I.DATE_BEGIN,@PeriodBegin) <= @PeriodEnd AND ISNULL(I.DATE_END,@PeriodEnd) >= @PeriodBegin
GROUP BY PERS_LINK

--forma в отчётности за 2013 год содержит тип договора (1 трудовой, 2 ГПХ)
insert into dbo.SZV4_SVEDENIA (link_up, orders, forma, link_pers, sum_doh, sum_str, sum_nak, sum_dop, dper_vn_m, dper_vn_d,dper_oz_m, dper_oz_d, isum_str, isum_nak, LINK_KATEG, DATE_BEG, DATE_END) 
Select distinct @link, 0, DOG, B.link, 0, 0, 0, 0, 
	DIS_M = 0,
	DIS_D = 0,
	VAC_M = 0,
	VAC_D = 0,
	0,0,
	@LINK_OZOI,
	CASE WHEN ISNULL(I.DATE_BEGIN,@PeriodBegin) < @PeriodBegin THEN @PeriodBegin ELSE ISNULL(I.DATE_BEGIN,@PeriodBegin) END,
	CASE WHEN ISNULL(I.DATE_END,@PeriodEnd) > @PeriodEnd THEN @PeriodEnd ELSE ISNULL(I.DATE_END,@PeriodEnd) END
from 
	(	SELECT B.LINK, DOG = 1 
		FROM 
			#PERSON B
			INNER JOIN dbo.EMPL E ON E.pers_link = B.LINK AND E.DEP_LINK = @DEP_LINK
		UNION 
		SELECT B.LINK, DOG = 2 
		FROM 
			#PERSON B
			INNER JOIN dbo.SALARY_REESTR_DGH DGH ON DGH.PERS_LINK = B.LINK AND DGH.DEP_LINK = @DEP_LINK
	) B
	INNER JOIN #PERS_INV I ON I.PERS_LINK = B.LINK AND ISNULL(I.DATE_BEGIN,@PeriodBegin) <= @PeriodEnd AND ISNULL(I.DATE_END,@PeriodEnd) >= @PeriodBegin		

----ОБЩИЕ
DECLARE @LINK_NR INT
SET @LINK_NR = ISNULL((SELECT TOP 1 LINK FROM dbo.SA_PFR_KATEG WHERE LINK2 = 1 AND @Year BETWEEN YBEG AND YEND),1)

--forma в отчётности за 2013 год содержит тип договора (1 трудовой, 2 ГПХ)	
insert into dbo.SZV4_SVEDENIA (link_up, orders, forma, link_pers, sum_doh, sum_str, sum_nak, sum_dop, dper_vn_m, dper_vn_d,dper_oz_m, dper_oz_d, isum_str, isum_nak, LINK_KATEG, DATE_BEG, DATE_END) 
Select distinct @link, 0, DOG, B.link, 0, 0, 0, 0, 
	DIS_M = 0,
	DIS_D = 0,
	VAC_M = 0,
	VAC_D = 0,
	0,0,
	@LINK_NR,
	CASE WHEN I.PERS_LINK IS NULL OR @PeriodBegin < CASE WHEN ISNULL(I.DATE_BEGIN,@PeriodBegin) < @PeriodBegin THEN @PeriodBegin ELSE ISNULL(I.DATE_BEGIN,@PeriodBegin) END
		THEN @PeriodBegin 
		ELSE CASE WHEN ISNULL(I.DATE_END,@PeriodEnd) > @PeriodEnd THEN @PeriodEnd ELSE ISNULL(I.DATE_END,@PeriodEnd) END + 1
	END,
	CASE WHEN I.PERS_LINK IS NULL OR @PeriodEnd > CASE WHEN ISNULL(I.DATE_END,@PeriodEnd) > @PeriodEnd THEN @PeriodEnd ELSE ISNULL(I.DATE_END,@PeriodEnd) END
		THEN @PeriodEnd
		ELSE CASE WHEN ISNULL(I.DATE_BEGIN,@PeriodBegin) < @PeriodBegin THEN @PeriodBegin ELSE ISNULL(I.DATE_BEGIN,@PeriodBegin) END - 1
	END
from 
	(	
		SELECT B.LINK, DOG = 1 
		FROM 
			#PERSON B
			INNER JOIN dbo.EMPL E ON E.pers_link = B.LINK AND E.DEP_LINK = @DEP_LINK
		UNION 
		SELECT B.LINK, DOG = 2
		FROM 
			#PERSON B
			INNER JOIN dbo.SALARY_REESTR_DGH DGH ON DGH.PERS_LINK = B.LINK AND DGH.DEP_LINK = @DEP_LINK
	) B
	LEFT JOIN #PERS_INV I ON I.PERS_LINK = B.LINK AND ISNULL(I.DATE_BEGIN,@PeriodBegin) <= @PeriodEnd AND ISNULL(I.DATE_END,@PeriodEnd) >= @PeriodBegin		
WHERE --Добавляем если не было инвалидов или инвалидность была не весь период
	I.PERS_LINK IS NULL --не было инвалидов
	OR --инвалидность была не весь период
	CASE WHEN ISNULL(I.DATE_BEGIN,@PeriodBegin) < @PeriodBegin THEN @PeriodBegin ELSE ISNULL(I.DATE_BEGIN,@PeriodBegin) END
		BETWEEN @PeriodBegin+1 AND @PeriodEnd-1
	OR --инвалидность была не весь период
	CASE WHEN ISNULL(I.DATE_END,@PeriodEnd) > @PeriodEnd THEN @PeriodEnd ELSE ISNULL(I.DATE_END,@PeriodEnd) END
		BETWEEN @PeriodBegin+1 AND @PeriodEnd-1	

----ЕНВД
DECLARE @LINK_USEN INT
SET @LINK_USEN = ISNULL((SELECT TOP 1 LINK FROM dbo.SA_PFR_KATEG WHERE LINK2 = 2 AND @Year BETWEEN YBEG AND YEND),1)		
	
insert into dbo.SZV4_SVEDENIA 
	(link_up, orders, forma, link_pers, sum_doh, sum_str, sum_nak, sum_dop, dper_vn_m, dper_vn_d,dper_oz_m, dper_oz_d, isum_str, isum_nak, LINK_KATEG, DATE_BEG, DATE_END) 
SELECT 	
	link_up, orders, forma, link_pers, ISNULL(sum_doh,0), ISNULL(sum_str,0), ISNULL(sum_nak,0), ISNULL(sum_dop,0), ISNULL(dper_vn_m,0), ISNULL(dper_vn_d,0), ISNULL(dper_oz_m,0), ISNULL(dper_oz_d,0), ISNULL(isum_str,0), ISNULL(isum_nak,0), @LINK_USEN, DATE_BEG, DATE_END
FROM
	#PERSON B INNER JOIN dbo.SZV4_SVEDENIA S ON B.LINK = S.link_pers 
WHERE
	link_up = @link
	AND
	LINK_KATEG = @LINK_NR	
	

----СУММЫ ВЗНОСОВ В ЗАВИСИМОСТИ ОТ КАТЕГОРИИ ПО ЖУРНАЛУ ОПЕРАЦИЙ
CREATE TABLE #PERS_SUM_J (LINK_PERS INT, LINK_KATEG INT, DOG TINYINT, MON INT, INCOME NUMERIC(18,2), SUMMA_BASE NUMERIC(18,2), SUMMA_I NUMERIC(18,2), SUMMA_G NUMERIC(18,2))
INSERT INTO #PERS_SUM_J (LINK_PERS, LINK_KATEG, DOG, MON, INCOME, SUMMA_BASE, SUMMA_I, SUMMA_G)
SELECT LINK_PERS, LINK_KATEG, DOG, MON,
	SUM(CASE WHEN [OBJECT] = 1 THEN SUMMA ELSE 0 END), --ВСЕГО ДОХОД (INCOME)
	SUM(CASE WHEN [OBJECT] = 3 AND WAY_CALC = 6 THEN SUMMA_BASE ELSE 0 END),
	SUM(CASE WHEN [OBJECT] = 3 AND WAY_CALC = 6 THEN SUMMA ELSE 0 END),
	SUM(CASE WHEN [OBJECT] = 3 AND WAY_CALC = 7 THEN SUMMA ELSE 0 END)	
FROM
(
	SELECT 
		S.LINK_PERS, P.[WAY_CALC], S.LINK_KATEG, DOG = S.FORMA, P.[OBJECT], MON = MONTH(J.PERIOD_BEGIN), SUMMA_BASE = SUM(SUMMA_BASE), SUMMA = SUM(SUMMA)
	FROM 
		#PERSON B 
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.link_pers = B.LINK
		INNER JOIN dbo.EMPL E ON E.PERS_LINK = S.LINK_PERS
		INNER JOIN dbo.CALCULATE_JURNAL J ON J.LINK_EMPL = E.LINK 
			AND YEAR(J.PERIOD_BEGIN) = @Year AND MONTH(J.PERIOD_BEGIN) BETWEEN MONTH(S.DATE_BEG) AND MONTH(S.DATE_END)
		INNER JOIN dbo.PAYS P ON P.LINK = J.LINK_PAYS
		INNER JOIN dbo.SAL_SFIN F ON F.LINK = J.LINK_VKR
	WHERE
		S.LINK_UP = @link
		AND 
		(
			P.[OBJECT] = 3 AND P.[WAY_CALC] IN (6, 7)
			OR
			P.[OBJECT] = 1
		)
		AND J.LINK_DEP = @DEP_LINK
		AND S.FORMA = 1 --ВИД ДОГОВОРА (ТРУДОВОЙ)
		AND (LINK_KATEG = @LINK_OZOI OR (LINK_KATEG = @LINK_USEN AND F.ENVD = 1) OR (LINK_KATEG = @LINK_NR AND F.ENVD = 0))
	GROUP BY
		S.LINK_PERS, P.[WAY_CALC], S.LINK_KATEG, S.FORMA, P.[OBJECT], J.PERIOD_BEGIN
	UNION ALL	
	SELECT 
		S.LINK_PERS, P.[WAY_CALC], S.LINK_KATEG, DOG = S.FORMA, P.[OBJECT], MON = MONTH(J.PERIOD_BEGIN), SUMMA_BASE = SUM(SUMMA_BASE), SUMMA = SUM(SUMMA)
	FROM 
		#PERSON B 
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
		INNER JOIN dbo.CALCULATE_JURNAL J ON J.PERS_LINK = S.LINK_PERS 
			AND YEAR(J.PERIOD_BEGIN) = @Year AND MONTH(J.PERIOD_BEGIN) BETWEEN MONTH(S.DATE_BEG) AND MONTH(S.DATE_END)
		INNER JOIN dbo.PAYS P ON P.LINK = J.LINK_PAYS
		INNER JOIN dbo.SAL_SFIN F ON F.LINK = J.LINK_VKR
	WHERE
		S.LINK_UP = @link
		AND 
		(
			P.[OBJECT] = 3 AND P.[WAY_CALC] IN (6, 7)
			OR
			P.[OBJECT] = 1
		)
		AND J.LINK_DEP = @DEP_LINK
		AND S.FORMA = 2 --ВИД ДОГОВОРА (ГПХ)
		AND (LINK_KATEG = @LINK_OZOI OR (LINK_KATEG = @LINK_USEN AND F.ENVD = 1) OR (LINK_KATEG = @LINK_NR AND F.ENVD = 0))
	GROUP BY
		S.LINK_PERS, P.[WAY_CALC], S.LINK_KATEG, S.FORMA, P.[OBJECT], J.PERIOD_BEGIN
) T
GROUP BY LINK_PERS, LINK_KATEG, DOG, MON

--
CREATE INDEX #TMP_IDX_#PERS_SUM_J ON #PERS_SUM_J (LINK_PERS, LINK_KATEG)

--рАСЧЁТ ОБЛАГАЕМОЙ СУММЫ ДОХОДА ЗА ПЕРИОД
--в РАСЧЁТ НЕ ДОЛЖНА ПОПАСТЬ СУММА С ПРЕВЫШЕНИЯ СУММЫ ДОХОДА 512 ТЫС С УЧЁТОМ СКИДОК
create table #SPR_ESN ([MONTH_BASE] TINYINT, SUMMA_BASE numeric(12,2) default 0.00, DED_M numeric(12,2) default 0.00, INV_M numeric(12,2) default 0.00, SUMMA numeric(12,2) default 0.00, WAY_CALC int default 0.00, REF_PHYS_PERS int default 0, KATEG TINYINT, DOG TINYINT)

Insert InTo #SPR_ESN ([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG, DOG)
SELECT [MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG, DOG = 1
FROM 
	dbo.SA_ESN_VIEW(@Year, @Month, @DEP_LINK, 0) S
WHERE 
	WAY_CALC IN (6,7,10,11)
	AND EXISTS (SELECT * FROM #PERSON B WHERE B.LINK = S.REF_PHYS_PERS)

--Суммы по договорникам
INSERT INTO #SPR_ESN 
	([MONTH_BASE], SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, KATEG, DOG)
SELECT 
	MONTH(G.[DATE]) AS MONTH_BASE, 
	GT.SUMMA_BASE, 0, 0, GT.SUMMA, GT.WAY_CALC, GT.PERS_LINK, 
	CASE WHEN dbo.is_invalid(GT.PERS_LINK,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,G.[MONTH],@Year))) = 2
		THEN 3
		ELSE
		CASE WHEN F.ENVD = 1 THEN 2 ELSE 1 END
	END, 
	DOG = 2
FROM 
	dbo.DOCUMENTS_DGH G 
	INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
	inner join dbo.PERSON P on GT.PERS_LINK = P.link
	INNER JOIN #PERSON B ON B.LINK = P.LINK
	inner join dbo.SAL_SFIN F on F.LINK = GT.LINK_VKR
WHERE 
	FLAG_JC = 1
	AND GT.WAY_CALC  IN (6,7,10,11)
	AND YEAR(G.[DATE]) = @Year
	AND MONTH(G.[DATE]) <= @Month
	AND LINK_DEP = @DEP_LINK

--
CREATE INDEX #TMP_IDX_SPR_ESN ON #SPR_ESN (REF_PHYS_PERS, KATEG, DOG)

--
DELETE FROM #SPR_ESN
WHERE  EXISTS (SELECT * FROM dbo.KJ_PERS_PENSION K WHERE K.PERS_LINK = REF_PHYS_PERS  and K.CHECK_SZV = 0)

--Информация о ставках
DECLARE @STAVKI TABLE ( LINK_PERS INT, TARIF TINYINT, PREDEL NUMERIC(15,2), [PERCENT] NUMERIC(8,2), WAY_CALC TINYINT)

INSERT INTO @STAVKI (LINK_PERS, TARIF, PREDEL, [PERCENT], WAY_CALC)
SELECT 
	LINK_PERS, TARIF, PREDEL, [PERCENT], WAY_CALC 
FROM 
	dbo.SA_ESN_TARIF(DEFAULT, @PeriodEnd, DEFAULT) S
WHERE 
	WAY_CALC IN (6,7)
	AND EXISTS (SELECT * FROM #PERSON P WHERE P.LINK = S.LINK_PERS)

--	
DECLARE @LIMIT NUMERIC(18,2)
SET @LIMIT = ISNULL((SELECT MIN(PREDEL) FROM @STAVKI WHERE TARIF = 1 AND WAY_CALC = 6),0)

------СУММЫ В ЗАВИСИМОСТИ ОТ КАТЕГОРИИ ПО РАСЧЁТАМ ЕСН С УЧЁТОМ ПРЕВЫШЕНИЯ 512Т.
CREATE TABLE #SUM_PERSON (LINK_PERSON INT, KATEG TINYINT, DOG TINYINT, WAY_CALC TINYINT, [PERCENT] NUMERIC(18,2), MON TINYINT, 
				BAZA NUMERIC(18,2), SUM_LIM NUMERIC(18,2), SUM_KOR NUMERIC(18,2),BAZA2 NUMERIC(18,2),  NALOG NUMERIC(20,6), M BIT)

INSERT INTO #SUM_PERSON (LINK_PERSON, KATEG, DOG, WAY_CALC, [PERCENT], MON, BAZA, NALOG, M)
SELECT
	E.REF_PHYS_PERS, E.KATEG, E.DOG, S.WAY_CALC, S.[PERCENT], E.MONTH_BASE,
	SUM(ISNULL(SUMMA_BASE,0) - ISNULL(DED_M,0) - ISNULL(INV_M,0)) AS BAZA,
	SUM(SUMMA),
	0
FROM 
	#SPR_ESN E
	INNER JOIN @STAVKI S ON S.LINK_PERS = E.REF_PHYS_PERS AND S.WAY_CALC = E.WAY_CALC AND S.TARIF = E.KATEG
WHERE 
	S.PREDEL = @LIMIT
GROUP BY
	E.REF_PHYS_PERS, E.KATEG, E.DOG, S.WAY_CALC, S.[PERCENT], E.MONTH_BASE

--ТОЛЬКО ТЕ, У КОГО ДОХОД ПРЕВЫСИЛ ЛИМИТ
CREATE TABLE #PERS_AFTER (LINK_PERSON INT, KATEG TINYINT, DOG TINYINT)

INSERT INTO #PERS_AFTER (LINK_PERSON, KATEG, DOG)
SELECT LINK_PERSON, KATEG, DOG
FROM #SUM_PERSON 
WHERE WAY_CALC = 6
GROUP BY LINK_PERSON, KATEG, DOG
HAVING SUM(BAZA) > @LIMIT
DECLARE @Cur2 CURSOR, @MON TINYINT, @KATEG TINYINT, @DOG TINYINT

SET @Cur2 = CURSOR FORWARD_ONLY
FOR SELECT DISTINCT MON, KATEG, DOG FROM #SUM_PERSON SP
	ORDER BY MON, KATEG ASC, DOG DESC
OPEN @Cur2
FETCH NEXT FROM @Cur2 INTO @MON, @KATEG, @DOG
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN

		UPDATE SP --ДОХОД С НАКОПЛЕНИЕМ С НАЧАЛА ГОДА
		SET 
			M = 1,
			SUM_LIM = (SELECT SUM(BAZA) FROM #SUM_PERSON SP1 WHERE SP1.LINK_PERSON = SP.LINK_PERSON AND SP1.WAY_CALC = SP.WAY_CALC AND (M=1 OR SP1.MON = SP.MON AND SP1.KATEG = SP.KATEG AND SP1.DOG = SP.DOG))
		FROM #SUM_PERSON SP
		WHERE MON = @MON AND KATEG = @KATEG AND DOG = @DOG
		
		UPDATE #SUM_PERSON --ПРЕВЫШЕНИЕ ЛИМИТА
		SET SUM_KOR = CASE WHEN ISNULL(SUM_LIM,0) > @LIMIT THEN ISNULL(SUM_LIM,0) - @LIMIT ELSE 0 END

		UPDATE #SUM_PERSON
		SET BAZA2 = CASE WHEN (ISNULL(BAZA,0) > ISNULL(SUM_KOR,0) OR ISNULL(BAZA,0) < 0)
							THEN ISNULL(BAZA,0) - ISNULL(SUM_KOR,0) ELSE 0 END
		
		UPDATE SP
		SET NALOG = 
					CASE WHEN BAZA <> BAZA2 
						THEN 
							
							CONVERT(NUMERIC(18,2),
							ISNULL((SELECT SUM(SP1.BAZA2) FROM #SUM_PERSON SP1 WHERE SP1.LINK_PERSON = SP.LINK_PERSON AND SP1.KATEG = SP.KATEG AND SP1.DOG = SP.DOG  AND SP1.WAY_CALC = SP.WAY_CALC AND SP1.MON <= SP.MON),0)
							* ISNULL([PERCENT],0) / 100)
							-
							CONVERT(NUMERIC(18,2),
							ISNULL((SELECT SUM(SP1.BAZA2) FROM #SUM_PERSON SP1 WHERE SP1.LINK_PERSON = SP.LINK_PERSON AND SP1.KATEG = SP.KATEG AND SP1.DOG = SP.DOG  AND SP1.WAY_CALC = SP.WAY_CALC AND SP1.MON < SP.MON),0)
							* ISNULL([PERCENT],0) / 100)

						ELSE 
							(SELECT CASE WHEN SP.WAY_CALC = 6 THEN SUM(SUMMA_I) ELSE SUM(SUMMA_G) END FROM #PERS_SUM_J PS WHERE PS.LINK_PERS = SP.LINK_PERSON AND SP.KATEG = PS.LINK_KATEG AND SP.DOG = PS.DOG AND PS.MON = SP.MON)
					END
					
					--CASE WHEN BAZA <> BAZA2 
					--	THEN ISNULL(BAZA2,0) * ISNULL([PERCENT],0) / 100
					--	ELSE (SELECT CASE WHEN SP.WAY_CALC = 6 THEN SUM(SUMMA_I) ELSE SUM(SUMMA_G) END FROM #PERS_SUM_J PS WHERE PS.LINK_PERS = SP.LINK_PERSON AND SP.KATEG = PS.LINK_KATEG AND PS.MON = SP.MON)
					--END	
		FROM
			#SUM_PERSON SP
		WHERE --ТОЛЬКО У ТЕХ, У КОГО ПРЕВЫШЕНИЕ ЛИМИТА
			EXISTS (SELECT * FROM #PERS_AFTER PA WHERE PA.LINK_PERSON = SP.LINK_PERSON AND PA.KATEG = SP.KATEG AND PA.DOG = SP.DOG)

	END
	FETCH NEXT FROM @Cur2 INTO @MON, @KATEG, @DOG
END

CLOSE @Cur2
DEALLOCATE @Cur2

--СУММЫ В ЗАВИСИМОСТИ ОТ КАТЕГОРИИ
CREATE TABLE #PERS_SUM (LINK_PERS INT, LINK_KATEG INT, DOG TINYINT, SUMMA_BASE NUMERIC(18,2), SUMMA_I NUMERIC(18,2), SUMMA_G NUMERIC(18,2))
INSERT INTO #PERS_SUM (LINK_PERS, LINK_KATEG, DOG, SUMMA_BASE, SUMMA_I, SUMMA_G)
SELECT LINK_PERS, LINK_KATEG, DOG,
	SUM(CASE WHEN WAY_CALC = 6 THEN SUMMA_BASE ELSE 0 END),
	SUM(CASE WHEN WAY_CALC = 6 THEN SUMMA ELSE 0 END),
	SUM(CASE WHEN WAY_CALC = 7 THEN SUMMA ELSE 0 END)	
FROM
(
	SELECT 
		S.LINK_PERS, SP.[WAY_CALC], S.LINK_KATEG, DOG = S.FORMA, SUMMA_BASE = SUM(BAZA2), SUMMA = SUM(NALOG)
	FROM 
		#PERSON B 
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.link_pers = B.LINK
		INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG
		INNER JOIN #SUM_PERSON SP ON SP.LINK_PERSON = S.LINK_PERS AND SP.KATEG = K.LINK2 AND S.FORMA = SP.DOG AND SP.MON BETWEEN MONTH(S.DATE_BEG) AND MONTH(S.DATE_END)
	WHERE
		S.LINK_UP = @link
		AND
		@Year BETWEEN K.YBEG AND K.YEND
	GROUP BY
		S.LINK_PERS, SP.[WAY_CALC], S.LINK_KATEG, S.FORMA
) T
GROUP BY LINK_PERS, LINK_KATEG, DOG

--
UPDATE S SET
	sum_doh = ISNULL(SUMMA_I,0), --После 10 года содержит начисленную страховую часть
	sum_str = 0, --После 10 года должен содержать перечисленную страховую часть, но т.к. ее не знаем - то 0, потом определим
	sum_nak = ISNULL(SUMMA_G,0), --Для все периодов содержит начисленную накопительную часть
	sum_dop = 0 -- После 10 года должен содержать перечисленную накопительную часть, но т.к. ее не знаем - то 0, потом определим
FROM
	dbo.SZV4_SVEDENIA S 
	INNER JOIN #PERS_SUM P ON P.LINK_PERS = S.LINK_PERS AND P.LINK_KATEG = S.LINK_KATEG AND P.DOG = S.FORMA
WHERE
	link_up = @link

---Заполняются суммы по доптарифам
CREATE TABLE #INCOME_T1T2 (
	LINK_PERS INT, 
	KATEG TINYINT,
	DOG TINYINT, 
	INCOME_T1_M1 NUMERIC(18,2),
	INCOME_T2_M1 NUMERIC(18,2),
	INCOME_T1_M2 NUMERIC(18,2),
	INCOME_T2_M2 NUMERIC(18,2),
	INCOME_T1_M3 NUMERIC(18,2),
	INCOME_T2_M3 NUMERIC(18,2)
	)

INSERT INTO #INCOME_T1T2 (LINK_PERS, KATEG, DOG, INCOME_T1_M1, INCOME_T2_M1, INCOME_T1_M2, INCOME_T2_M2, INCOME_T1_M3, INCOME_T2_M3)
SELECT REF_PHYS_PERS, KATEG, E.DOG, 
	INCOME_T1_M1 = SUM(CASE WHEN WAY_CALC = 10 AND MONTH_BASE = (@Month - 2) THEN SUMMA_BASE - DED_M - INV_M ELSE 0 END), 
	INCOME_T2_M1 = SUM(CASE WHEN WAY_CALC = 11 AND MONTH_BASE = (@Month - 2) THEN SUMMA_BASE - DED_M - INV_M ELSE 0 END),
	INCOME_T1_M2 = SUM(CASE WHEN WAY_CALC = 10 AND MONTH_BASE = (@Month - 1) THEN SUMMA_BASE - DED_M - INV_M ELSE 0 END),
	INCOME_T2_M2 = SUM(CASE WHEN WAY_CALC = 11 AND MONTH_BASE = (@Month - 1) THEN SUMMA_BASE - DED_M - INV_M ELSE 0 END),
	INCOME_T1_M3 = SUM(CASE WHEN WAY_CALC = 10 AND MONTH_BASE = @Month THEN SUMMA_BASE - DED_M - INV_M ELSE 0 END),
	INCOME_T2_M3 = SUM(CASE WHEN WAY_CALC = 11 AND MONTH_BASE = @Month THEN SUMMA_BASE - DED_M - INV_M ELSE 0 END)
FROM #SPR_ESN E
WHERE WAY_CALC IN (10,11)	
GROUP BY REF_PHYS_PERS, KATEG, E.DOG

UPDATE S SET
	S.INCOME_T1_M1 = P.INCOME_T1_M1,
	S.INCOME_T2_M1 = P.INCOME_T2_M1,
	S.INCOME_T1_M2 = P.INCOME_T1_M2,
	S.INCOME_T2_M2 = P.INCOME_T2_M2,
	S.INCOME_T1_M3 = P.INCOME_T1_M3,
	S.INCOME_T2_M3 = P.INCOME_T2_M3
FROM
	dbo.SZV4_SVEDENIA S 
	INNER JOIN #INCOME_T1T2 P ON P.LINK_PERS = S.LINK_PERS AND P.KATEG = S.LINK_KATEG AND P.DOG = S.FORMA
WHERE
	link_up = @link

--Всего начислено по физлицам дохода
CREATE TABLE #INCOME(
	LINK_PERS INT, 
	KATEG TINYINT,
	DOG TINYINT, 
	INCOME_M1 NUMERIC(18,2),
	INCOME_M2 NUMERIC(18,2),
	INCOME_M3 NUMERIC(18,2)
	)

INSERT INTO #INCOME (LINK_PERS, KATEG, DOG, INCOME_M1, INCOME_M2, INCOME_M3)
SELECT 
	LINK_PERS, LINK_KATEG, DOG,
	INCOME_M1 = SUM(CASE WHEN MON = (@Month - 2) THEN INCOME ELSE 0 END),
	INCOME_M2 = SUM(CASE WHEN MON = (@Month - 1) THEN INCOME ELSE 0 END),
	INCOME_M3 = SUM(CASE WHEN MON = @Month THEN INCOME ELSE 0 END)
FROM #PERS_SUM_J
GROUP BY 
	LINK_PERS, LINK_KATEG, DOG

UPDATE S SET
	S.INCOME_M1 = P.INCOME_M1,
	S.INCOME_M2 = P.INCOME_M2,
	S.INCOME_M3 = P.INCOME_M3
FROM
	dbo.SZV4_SVEDENIA S 
	INNER JOIN #INCOME P ON P.LINK_PERS = S.LINK_PERS AND P.KATEG = S.LINK_KATEG AND P.DOG = S.FORMA
WHERE
	link_up = @link	

--База для страховых взносов
CREATE TABLE #BASE(
	LINK_PERS INT, 
	KATEG TINYINT,
	DOG TINYINT, 
	BASE_BEFORE_M1 NUMERIC(18,2),
	BASE_AFTER_M1 NUMERIC(18,2),
	BASE_BEFORE_M2 NUMERIC(18,2),
	BASE_AFTER_M2 NUMERIC(18,2),
	BASE_BEFORE_M3 NUMERIC(18,2),
	BASE_AFTER_M3 NUMERIC(18,2)	
	)

INSERT INTO #BASE (LINK_PERS, KATEG, DOG, BASE_BEFORE_M1, BASE_AFTER_M1, BASE_BEFORE_M2, BASE_AFTER_M2, BASE_BEFORE_M3, BASE_AFTER_M3 )
SELECT LINK_PERSON, KATEG, DOG,
	BASE_BEFORE_M1	= SUM(CASE WHEN MON = (@Month - 2) THEN BAZA2 ELSE 0 END),
	BASE_AFTER_M1	= SUM(CASE WHEN MON = (@Month - 2) THEN BAZA - BAZA2 ELSE 0 END),
	BASE_BEFORE_M2	= SUM(CASE WHEN MON = (@Month - 1) THEN BAZA2 ELSE 0 END),
	BASE_AFTER_M2	= SUM(CASE WHEN MON = (@Month - 1) THEN BAZA - BAZA2 ELSE 0 END),
	BASE_BEFORE_M3	= SUM(CASE WHEN MON = @Month THEN BAZA2 ELSE 0 END),
	BASE_AFTER_M3	= SUM(CASE WHEN MON = @Month THEN BAZA - BAZA2 ELSE 0 END)		
FROM #SUM_PERSON 
WHERE 
	WAY_CALC = 6
GROUP BY
	LINK_PERSON, KATEG, DOG

UPDATE S SET
	S.BASE_BEFORE_M1 = P.BASE_BEFORE_M1,
	S.BASE_AFTER_M1 = P.BASE_AFTER_M1,
	S.BASE_BEFORE_M2 = P.BASE_BEFORE_M2,
	S.BASE_AFTER_M2 = P.BASE_AFTER_M2,
	S.BASE_BEFORE_M3 = P.BASE_BEFORE_M3,
	S.BASE_AFTER_M3 = P.BASE_AFTER_M3	
FROM
	dbo.SZV4_SVEDENIA S 
	INNER JOIN #BASE P ON P.LINK_PERS = S.LINK_PERS AND P.KATEG = S.LINK_KATEG AND P.DOG = S.FORMA
WHERE
	link_up = @link	

--У кого нет дохода, но есть стаж
SELECT LINK_PERS, FORMA, LINK_KATEG INTO #TAB FROM dbo.SZV4_SVEDENIA WHERE LINK_UP = @link GROUP BY LINK_PERS, FORMA, LINK_KATEG HAVING SUM(sum_doh) = 0 AND SUM(sum_nak) = 0 AND SUM(INCOME_M1) = 0
--	
DELETE FROM dbo.SZV4_SVEDENIA 
WHERE link_up = @link AND sum_doh = 0 AND sum_nak = 0 AND INCOME_M1 = 0 AND LINK_KATEG NOT IN( @LINK_NR, @LINK_OZOI)

DELETE FROM dbo.SZV4_SVEDENIA
WHERE link_up = @link AND sum_doh = 0 AND sum_nak = 0 AND INCOME_M1 = 0 
	AND NOT EXISTS (SELECT LINK_PERS FROM #TAB T WHERE T.LINK_PERS = dbo.SZV4_SVEDENIA.LINK_PERS AND T.FORMA = dbo.SZV4_SVEDENIA.FORMA AND T.LINK_KATEG = dbo.SZV4_SVEDENIA.LINK_KATEG)

---- РАСПРЕДЕЛЕНИЕ ПЕРЕЧИСЛЕННОЙ СУММЫ ПО ФИЗЛИЦАМ
EXEC [dbo].SA_SZV4_PACHKA_RASPIL @link

IF @VID_KOR != 3
	begin  
	---СВЕДЕНИЯ О СТАЖЕ
	----------------------------------------------------------------------------
	CREATE TABLE #PERIODY (link int identity(1,1), link_face int, LINK_KATEG INT, date1 datetime, date2 datetime, [type] int, NUM_STAKE NUMERIC(5,2), [IS_DOP] VARCHAR(20))

	--/*Стаж сотрудников*/
	INSERT INTO 
		#PERIODY (link_face, LINK_KATEG, date1, date2, type)
	SELECT 	DISTINCT
		PERS_LINK, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when P.DATE_BEGIN >= @PeriodBegin then P.DATE_BEGIN else @PeriodBegin end)
			THEN (case when P.DATE_BEGIN >= @PeriodBegin then P.DATE_BEGIN else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
			THEN (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
			ELSE S.DATE_END
		END,	
		0
	FROM
		#PERSON B
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
		INNER JOIN dbo.EMPL E ON S.LINK_PERS = E.PERS_LINK AND E.DEP_LINK = @DEP_LINK
		INNER JOIN dbo.ITEM_MOVE P on E.link = P.empl_link and P.NEW_FACE = 1 AND P.ACTIVE=1
		LEFT JOIN dbo.ITEM_DIS_FACE U on E.link = U.empl_link AND U.ACTIVE=1
	WHERE
		S.LINK_UP = @link
		AND
		P.DATE_BEGIN <= @PeriodEnd
		AND
		coalesce(U.DIS_DATE,'20990101') >= @PeriodBegin

	/*Стаж договорников*/
	Select DISTINCT
		link_face = DGH.PERS_LINK, LINK_KATEG,
		date1 = CASE WHEN S.DATE_BEG < (case when DGH.DATE1 >= @PeriodBegin then DGH.DATE1 else @PeriodBegin end)
				THEN (case when DGH.DATE1 >= @PeriodBegin then DGH.DATE1 else @PeriodBegin end)
				ELSE S.DATE_BEG
			END,
		date2 = CASE WHEN S.DATE_END > (case when coalesce(DGH.DATE2,@PeriodEnd) <= @PeriodEnd then coalesce(DGH.DATE2,@PeriodEnd) else @PeriodEnd end)
				THEN (case when coalesce(DGH.DATE2,@PeriodEnd) <= @PeriodEnd then coalesce(DGH.DATE2,@PeriodEnd) else @PeriodEnd end)
				ELSE S.DATE_END
			END,
		[type] = 0
	INTO #DGH	
	FROM
		#PERSON B
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
		INNER JOIN dbo.SALARY_REESTR_DGH DGH ON S.LINK_PERS = DGH.PERS_LINK
	WHERE 
		S.LINK_UP = @link
		AND
		DGH.DEP_LINK = @DEP_LINK
		and
		DGH.DATE1 <= @PeriodEnd
		and
		coalesce(DGH.DATE2,'20990101') >= @PeriodBegin

	-- Периоды в сведениях впишем в периоды работы
	SELECT LINK_FACE, DB = MIN(DATE1), DE = MAX(DATE2)
	INTO #WORK
	FROM #PERIODY
	GROUP BY LINK_FACE

	UPDATE S SET 
		S.DATE_BEG = CASE WHEN W.DB < S.DATE_BEG THEN S.DATE_BEG ELSE W.DB END,
		S.DATE_END = CASE WHEN W.DE > S.DATE_END THEN S.DATE_END ELSE W.DE END
	FROM 
		dbo.SZV4_SVEDENIA S INNER JOIN #WORK W ON S.LINK_PERS = W.LINK_FACE
	WHERE 
		S.LINK_UP = @link

	--
	CREATE TABLE #ADD_TYPE (
		[type] INT IDENTITY(1,1),
		[TERR_USL_TRUD] int NULL ,
		[TERR_RK] numeric(3, 2) NULL ,
		[OSOB_USL_TRUD] int NULL ,
		[COD_POS_SPISOK] int NULL ,
		[COD_POS_SPISOK2] int NULL ,
		[USL_DOSROCH_PENS] int NULL ,
		[STAVKA_PED_MED] numeric(3, 2) NULL,
		[VID] VARCHAR(20),
		[IS_DOP] VARCHAR(20),
		[COD_SPO_USL_TRUD] INT NULL
	)	
	--Новые типы
	INSERT INTO #ADD_TYPE 
	SELECT DISTINCT ISNULL(TERR_USL_TRUD,0), ISNULL(TERR_RK,0), ISNULL(OSOB_USL_TRUD,0), ISNULL(COD_POS_SPISOK,0), ISNULL(COD_POS_SPISOK2,0), ISNULL(USL_DOSROCH_PENS,0), ISNULL(STAVKA_PED_MED,0), VID = 'ADD_TYPE', IS_DOP = '', ISNULL([COD_SPO_USL_TRUD],0)
	FROM dbo.staff
	WHERE ISNULL(TERR_USL_TRUD,0) <> 0 OR ISNULL(TERR_RK,0) <> 0 OR ISNULL(OSOB_USL_TRUD,0) <> 0 OR ISNULL(COD_POS_SPISOK,0) <> 0 OR ISNULL(COD_POS_SPISOK2,0) <> 0 OR ISNULL(USL_DOSROCH_PENS,0) <> 0 OR ISNULL(STAVKA_PED_MED,0) <> 0 OR ISNULL([COD_SPO_USL_TRUD],0) <> 0

	--
	DECLARE @MAX_TYPE INT
	SET @MAX_TYPE = ISNULL((SELECT MAX(type) FROM #ADD_TYPE),0)

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	VALUES ('TMP_TYPE', '')

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	VALUES ('PERIOD1', 'ДЕКРЕТ')

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	SELECT DISTINCT
		'PERIOD2',
		ISNULL(V.IS_DOP,'ДЕТИ')
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK 
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID V ON V.LINK = IV.TYPE_LINK
		INNER JOIN (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7 AND ISNULL(VV.NOT_LGOT_EXPIR,0) = 0) VV ON VV.LINK = IV.TYPE_LINK
		left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and coalesce(ivb.active,0) = 1
	where 
		S.LINK_UP = @link
		AND		
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	SELECT DISTINCT
		'PERIOD2LS',
		ISNULL(V.IS_DOP,'ДЕТИ')
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK 
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID V ON V.LINK = IV.TYPE_LINK
		INNER JOIN (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7 AND ISNULL(VV.NOT_LGOT_EXPIR,0) = 1) VV ON VV.LINK = IV.TYPE_LINK
		left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and coalesce(ivb.active,0) = 1
	where 
		S.LINK_UP = @link
		AND		
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin		

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	VALUES ('PERIOD3', 'ВРНЕТРУД')

	INSERT INTO #ADD_TYPE (VID, IS_DOP)
	Select DISTINCT
		'PERIOD4',
		ISNULL(VV.IS_DOP,'АДМИНИСТР')
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK  
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID VV ON VV.LINK = IV.type_link AND VV.NO_SAL = 1
		left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and coalesce(ivb.active,0) = 1
	where
		S.LINK_UP = @link
		AND		 	
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin

	--ПРОЧИЕ КОДЫ ДЛЯ ВИДОВ ОТПУСКОВ
	INSERT INTO #ADD_TYPE (VID, IS_DOP) 	
	SELECT LEFT('P_' + LTRIM(RTRIM(CODE)),20), IS_DOP
	FROM dbo.VACATION_VID 
	WHERE IS_DOP IS NOT NULL
		AND NOT EXISTS (SELECT * FROM #ADD_TYPE WHERE VID = LEFT('P_' + LTRIM(RTRIM(CODE)),20))

	--Периоды работы на должности c параметрами для персучета
	INSERT INTO 
		#PERIODY (link_face, LINK_KATEG, date1, date2, [type], NUM_STAKE)
	SELECT DISTINCT 
		link_face = E.PERS_LINK, S.LINK_KATEG,
		date1 = CASE WHEN S.DATE_BEG < (case when st.DATE_BEGIN >= @PeriodBegin then st.DATE_BEGIN else @PeriodBegin end)
					THEN (case when st.DATE_BEGIN >= @PeriodBegin then st.DATE_BEGIN else @PeriodBegin end)
					ELSE S.DATE_BEG
				END,
		date2 = CASE WHEN 
						(CASE WHEN S.DATE_END > (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
							THEN (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
							ELSE S.DATE_END
						END)
							> (case when st.DATE_END <= @PeriodEnd then st.DATE_END else @PeriodEnd end)
					THEN 
						(case when st.DATE_END <= @PeriodEnd then st.DATE_END else @PeriodEnd end)
					ELSE 
						(CASE WHEN S.DATE_END > (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
							THEN (case when coalesce(U.DIS_DATE,@PeriodEnd) <= @PeriodEnd then coalesce(U.DIS_DATE,@PeriodEnd) else @PeriodEnd end)
							ELSE S.DATE_END
						END)
				END,	
		ISNULL(T.[type],0),
		ISNULL(im.NUM_STAKE,0)--, ST.*
	FROM 
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK	
		INNER JOIN dbo.sa_item_move im ON im.EMPL_LINK = e.link
		inner join dbo.staff_head sh on sh.link = STAFF_LINK
		inner join dbo.staff st on st.link_up = sh.link
		LEFT JOIN dbo.ITEM_DIS_FACE U on E.link = U.empl_link AND U.ACTIVE=1	
		left join #ADD_TYPE T on 
				ISNULL(st.TERR_USL_TRUD,0) = ISNULL(T.TERR_USL_TRUD,0) 
				AND ISNULL(st.TERR_RK,0) = ISNULL(T.TERR_RK,0) 
				AND ISNULL(st.OSOB_USL_TRUD,0) = ISNULL(T.OSOB_USL_TRUD,0) 
				AND ISNULL(st.COD_POS_SPISOK,0) = ISNULL(T.COD_POS_SPISOK,0) 
				AND ISNULL(st.COD_POS_SPISOK2,0) = ISNULL(T.COD_POS_SPISOK2,0) 
				AND ISNULL(st.USL_DOSROCH_PENS,0) = ISNULL(T.USL_DOSROCH_PENS,0) 
				AND ISNULL(st.STAVKA_PED_MED,0) = ISNULL(T.STAVKA_PED_MED,0) 
				AND ISNULL(st.[COD_SPO_USL_TRUD],0) = ISNULL(T.[COD_SPO_USL_TRUD],0)
	where 
		S.LINK_UP = @link
		AND
		IM.NUM_STAKE >= 1 
		AND
		IM.[STATUS] <> 2 --Совместителям доп. тариф не считаем
		AND
		im.DATE_BEGIN <= @PeriodEnd and im.DATE_END3 >= @PeriodBegin
		and 
		st.DATE_BEGIN <= @PeriodEnd and st.DATE_END >= @PeriodBegin
		AND
		T.[TYPE] IS NOT NULL AND T.VID = 'ADD_TYPE'
		AND
		COALESCE(U.DIS_DATE,'20990101') >= @PeriodBegin
	order by
		E.PERS_LINK

	---**************************************

	DECLARE @TMP_TYPE INT
	SET @TMP_TYPE = (SELECT TOP 1 TYPE FROM #ADD_TYPE WHERE VID = 'TMP_TYPE')

	/*Перерыв - отпуска без кодов (для корр. льготных периодов)*/
	INSERT INTO 
		#PERIODY (link_face, LINK_KATEG, date1, date2, [type])
	Select DISTINCT 
		E.pers_link, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			THEN (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when ISNULL(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then ISNULL(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			THEN (case when ISNULL(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then ISNULL(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		ISNULL( (SELECT TOP 1 TYPE FROM #ADD_TYPE AT WHERE AT.VID = LEFT('P_' + LTRIM(RTRIM(VV.CODE)),20) AND AT.IS_DOP = VV.IS_DOP ), @TMP_TYPE)
	FROM 
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK	
		inner join dbo.item_vacation iv on E.link = iv.EMPL_LINK 
		inner join dbo.orders o on iv.order_link=o.link
		-- Только отпуск, помеченный как "Не включать в льготный стаж", --Не административный (Для него свой код)
		INNER JOIN dbo.VACATION_VID VV ON VV.LINK = IV.type_link AND ISNULL(VV.NOT_LGOT_EXPIR,0) = 1 AND NO_SAL <> 1
		left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and ISNULL(ivb.active,0) = 1
	--	LEFT JOIN #PERIODY P ON P.link_face = P.LINK AND P.LINK_KATEG = S.LINK_KATEG AND P.[TYPE] = @TMP_TYPE
	where
		S.LINK_UP = @link
		AND 	
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		ISNULL(ISNULL(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin
		and -- Не по уходу за ребенком (Для него свой код)
		IV.type_link not in (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7)
		--AND
		--P.link_face IS NOT NULL AND 

	/*Перерыв - командировки без кодов (для корр. льготных периодов)*/	
	INSERT INTO 
		#PERIODY (link_face, LINK_KATEG, date1, date2, [type])
	SELECT DISTINCT
		E.pers_link, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when T.date_begin >= @PeriodBegin then T.date_begin else @PeriodBegin end)
			THEN (case when T.date_begin >= @PeriodBegin then T.date_begin else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when ISNULL(ITL.NEW_DATE_END,T.date_end) <= @PeriodEnd then ISNULL(ITL.NEW_DATE_END,T.date_end) else @PeriodEnd end)
			THEN (case when ISNULL(ITL.NEW_DATE_END,T.date_end) <= @PeriodEnd then ISNULL(ITL.NEW_DATE_END,T.date_end) else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		@TMP_TYPE
	FROM 
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK	
		inner join dbo.item_travel T on E.link = T.EMPL_LINK
		left join dbo.ITEM_TRAVEL_LONG ITL on ITL.TRAVEL_LINK = T.LINK and ISNULL(ITL.ACTIVE,0) = 1	
	WHERE
		S.LINK_UP = @link
		AND 	
		E.DEP_LINK = @DEP_LINK
		AND 
		T.ACTIVE = 1 
		AND 
		T.DATE_BEGIN <= @PeriodEnd
		AND 
		ISNULL(ISNULL(ITL.NEW_DATE_END,T.date_end),'20990101') >= @PeriodBegin
		
	/*Перерыв - Больничный по Беременности и родам ДЕКРЕТ*/
	SET @TMP_TYPE = (SELECT TOP 1 TYPE FROM #ADD_TYPE WHERE VID = 'PERIOD1')

	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
	SELECT 
		E.PERS_LINK, LINK_KATEG, 
		CASE WHEN S.DATE_BEG < (case when D.date1 >= @PeriodBegin then D.date1 else @PeriodBegin end)
			THEN (case when D.date1 >= @PeriodBegin then D.date1 else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when D.date2 <= @PeriodEnd then D.date2 else @PeriodEnd end)
			THEN (case when D.date2 <= @PeriodEnd then D.date2 else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		@TMP_TYPE
	FROM 
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK
		inner join dbo.SDOC_DIS D on E.LINK = D.LINK_EMPL
		INNER JOIN dbo.NETRUD N ON N.LINK = [TYPE] AND N.DEKRET = 1
	WHERE 
		S.LINK_UP = @link
		AND	
		E.DEP_LINK = @DEP_LINK
		and
		D.date1 <= @PeriodEnd
		and
		coalesce(D.date2,'20990101') >= @PeriodBegin

	/*Перерыв - Больничный ВРНЕТРУД*/
	SET @TMP_TYPE = (SELECT TOP 1 TYPE FROM #ADD_TYPE WHERE VID = 'PERIOD3')

	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
	SELECT 
		E.PERS_LINK, LINK_KATEG, 
		CASE WHEN S.DATE_BEG < (case when D.date1 >= @PeriodBegin then D.date1 else @PeriodBegin end)
			THEN (case when D.date1 >= @PeriodBegin then D.date1 else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when D.date2 <= @PeriodEnd then D.date2 else @PeriodEnd end)
			THEN (case when D.date2 <= @PeriodEnd then D.date2 else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		@TMP_TYPE
	FROM 
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK
		inner join dbo.SDOC_DIS D on E.LINK = D.LINK_EMPL
	WHERE
		S.LINK_UP = @link
		AND	 
		E.DEP_LINK = @DEP_LINK
		and
		D.date1 <= @PeriodEnd
		and
		coalesce(D.date2,'20990101') >= @PeriodBegin
		and
		[TYPE] not in (select LINK from dbo.NETRUD where DEKRET = 1)

	/*Перерыв - Уход за ребенком до 1,5 и до 3 лет*/
	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
	SELECT 
		E.pers_link, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			THEN (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			THEN (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		(SELECT TOP 1 TYPE FROM #ADD_TYPE AT WHERE AT.VID = 'PERIOD2' AND AT.IS_DOP = LTRIM(RTRIM(ISNULL(V.IS_DOP,'ДЕТИ'))))
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK 
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID V ON V.LINK = IV.TYPE_LINK
		INNER JOIN (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7 AND ISNULL(VV.NOT_LGOT_EXPIR,0) = 0) VV ON VV.LINK = IV.TYPE_LINK
		LEFT JOIN DBO.ITEM_VACATION_BREAK IVB ON IVB.VAC_LINK = IV.LINK AND COALESCE(IVB.ACTIVE,0) = 1
	WHERE 
		S.LINK_UP = @link
		AND		
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin

	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
	SELECT 
		E.pers_link, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			THEN (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			THEN (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		(SELECT TOP 1 TYPE FROM #ADD_TYPE AT WHERE AT.VID = 'PERIOD2LS' AND AT.IS_DOP = LTRIM(RTRIM(ISNULL(V.IS_DOP,'ДЕТИ'))))
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK 
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID V ON V.LINK = IV.TYPE_LINK
		INNER JOIN (SELECT VV.LINK FROM dbo.VACATION_VID VV INNER join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK WHERE WORK_D = 7 AND ISNULL(VV.NOT_LGOT_EXPIR,0) = 1) VV ON VV.LINK = IV.TYPE_LINK
		LEFT JOIN DBO.ITEM_VACATION_BREAK IVB ON IVB.VAC_LINK = IV.LINK AND COALESCE(IVB.ACTIVE,0) = 1
	WHERE 
		S.LINK_UP = @link
		AND		
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin

	/*Перерыв - Отпуск без сохранения содержания АДМИНИСТР*/
	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, type)
	Select E.pers_link, LINK_KATEG,
		CASE WHEN S.DATE_BEG < (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			THEN (case when iv.date_begin >= @PeriodBegin then iv.date_begin else @PeriodBegin end)
			ELSE S.DATE_BEG
		END,
		CASE WHEN S.DATE_END > (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			THEN (case when coalesce(ivb.DATE_BREAK,iv.date_end) <= @PeriodEnd then coalesce(ivb.DATE_BREAK,iv.date_end) else @PeriodEnd end)
			ELSE S.DATE_END
		END,
		(SELECT TOP 1 TYPE FROM #ADD_TYPE AT WHERE AT.VID = 'PERIOD4' AND AT.IS_DOP = LTRIM(RTRIM(ISNULL(VV.IS_DOP,'АДМИНИСТР'))))
	FROM
		#PERSON P
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = P.LINK
		INNER JOIN dbo.empl e on S.LINK_PERS = E.PERS_LINK  
		inner join item_vacation iv on E.link = iv.EMPL_LINK inner join orders o on iv.order_link=o.link
		INNER JOIN dbo.VACATION_VID VV ON VV.LINK = IV.type_link AND VV.NO_SAL = 1
		left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and coalesce(ivb.active,0) = 1
	WHERE
		S.LINK_UP = @link
		AND		 	
		E.DEP_LINK = @DEP_LINK
		and
		iv.active = 1 
		and
		iv.date_begin <= @PeriodEnd
		and
		coalesce(coalesce(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin
		
	--------------------------------------------------------------------------
	-- 2. Выстроим последовательность периодов с учетом их пересечений и приоритетов по полю type.
	--- Предполагается, что на первом шаге однотипные периоды уже нормализованы, т.е. следующие подряд и вложенные объединены
	CREATE TABLE #PERIODY3 (link int identity(1,1), link_face int, LINK_KATEG INT, date1 datetime, date2 datetime, [type] INT, orders int, i int, NUM_STAKE NUMERIC(5,2), TYPE_ADD INT)

	--Все промежутки заполняются типом -1  т.е. несуществующими днями
	INSERT INTO #PERIODY (link_face, LINK_KATEG, date1, date2, [type])
	SELECT DISTINCT link_face, LINK_KATEG, @PeriodBegin, @PeriodEnd, [type] = -1  FROM #PERIODY

	CREATE TABLE #DAYS (ID INT IDENTITY(1,1), LINK_FACE INT, LINK_KATEG INT, [DATE] DATETIME, [TYPE] INT, NUM INT, NUM_STAKE NUMERIC(5,2), [TYPE_ADD] INT)

	INSERT INTO #DAYS (LINK_FACE, LINK_KATEG, [DATE], [TYPE], NUM, NUM_STAKE, [TYPE_ADD])
	SELECT P.LINK_FACE, P.LINK_KATEG, [DATE], [TYPE] = MAX([TYPE]), 0, 
		NUM_STAKE = MAX(ISNULL(NUM_STAKE,0)), 
		[TYPE_ADD] = MAX(CASE WHEN [TYPE] <= @MAX_TYPE THEN [TYPE] ELSE 0 END)
	FROM 
		#PERIODY P
		INNER JOIN dbo.days_ex(@PeriodBegin, @PeriodEnd) D ON 1=1
	WHERE
		D.[DATE] BETWEEN P.DATE1 AND P.DATE2
	GROUP BY
		P.LINK_FACE, P.LINK_KATEG, [date]
	ORDER BY	
		P.LINK_FACE, P.LINK_KATEG, [date]

	--Убрать льготы для периодов, в которых не сохраняются льготы
	UPDATE #DAYS SET [TYPE_ADD] = 0 
	WHERE 
		--Тип периода, в котором не сохраняются льготы
		EXISTS (SELECT * FROM #ADD_TYPE AT WHERE VID = 'TMP_TYPE' AND AT.[TYPE] = #DAYS.[TYPE])
		OR --ОТПУСК ПО УХОДУ ЗА РЕБЁНКОМ (ЕСЛИ ВКЛЮЧЕНА НАСТРОЙКА В ВИДЕ ОТПУСКА
		EXISTS (SELECT * FROM #ADD_TYPE AT WHERE AT.VID = 'PERIOD2LS' AND AT.[TYPE] = #DAYS.[TYPE])
		--OR --ДЕКРЕТ (БОЛЬНИЧНЫЙ 140 ДНЕЙ ПО БЕРЕМЕННОСТИ И РОДАМ
		--EXISTS (SELECT * FROM #ADD_TYPE AT WHERE AT.VID = 'PERIOD1' AND AT.[TYPE] = #DAYS.[TYPE])
		

	--Пронумеровать группы
	DECLARE 
		@ID INT, @ID1 INT, @ID2 INT, @LINK_FACE INT, @LINK_KATEG INT, @TYPE INT, @NUM INT,
		@LINK_FACE1 INT, @LINK_KATEG1 INT, @TYPE1 INT

	--Убрать временные периоды, которые заводились для корректировки льготных периодов
	SET @TMP_TYPE = (SELECT TOP 1 TYPE FROM #ADD_TYPE WHERE VID = 'TMP_TYPE')
	UPDATE #DAYS SET [type] = 0 WHERE [type] = @TMP_TYPE

	--	
	SELECT TOP 1 @ID1 = 0, @ID2 = 0, @NUM = 0, @LINK_FACE1 = LINK_FACE, @LINK_KATEG1 =LINK_KATEG, @TYPE1 = [TYPE]
	FROM #DAYS
	order by ID
	--
	DECLARE @Cur1 CURSOR
	SET @Cur1 = CURSOR FORWARD_ONLY
	FOR SELECT ID, LINK_FACE, LINK_KATEG, [TYPE] from #DAYS order by ID
	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @ID, @LINK_FACE, @LINK_KATEG, @TYPE
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN

			IF NOT (@LINK_FACE = @LINK_FACE1 AND @LINK_KATEG = @LINK_KATEG1 AND @TYPE = @TYPE1)
			BEGIN
				
				SELECT @NUM = @NUM + 1, @LINK_FACE1 = @LINK_FACE, @LINK_KATEG1 = @LINK_KATEG, @TYPE1 = @TYPE
				UPDATE #DAYS SET NUM = @NUM WHERE ID BETWEEN @ID1 AND @ID-1
				SELECT @ID1 = @ID 

			END

		END

		FETCH NEXT FROM @Cur1 INTO @ID, @LINK_FACE, @LINK_KATEG, @TYPE
	END

	CLOSE @Cur1
	DEALLOCATE @Cur1
	--
	UPDATE #DAYS SET NUM = @NUM+1 WHERE ID >= @ID1

	--

	INSERT INTO #PERIODY3 (link_face, LINK_KATEG, date1, date2, [type], orders, i, NUM_STAKE, TYPE_ADD)
	SELECT LINK_FACE, LINK_KATEG, DATE_BEG =  MIN([DATE]), DATE_END = MAX([DATE]), [TYPE], 0, 0, NUM_STAKE = MAX(ISNULL(NUM_STAKE,0)), TYPE_ADD
	FROM #DAYS	
	GROUP BY LINK_FACE, LINK_KATEG, NUM, [TYPE], TYPE_ADD
	ORDER BY LINK_FACE, LINK_KATEG, DATE_BEG, DATE_END

	--Удаляем временные промежутки
	DELETE FROM #PERIODY3 WHERE [TYPE] = -1

	/*пронумеруем периоды*/
	DECLARE @uslovie INT
	set @uslovie = 1
	while @uslovie > 0
	begin
		update #PERIODY3 set orders = @uslovie 
		from #PERIODY3 as tt
		where 	coalesce(orders,0) = 0
			and date1 = (select min(t.date1) from #PERIODY3 t where coalesce(orders,0) = 0 and t.link_face = tt.link_face AND T.LINK_KATEG = TT.LINK_KATEG)

		if @@rowcount > 0
			set @uslovie = @uslovie + 1
		else
			set @uslovie = 0
	end

	--СТАХ ПО ТРУДОВОМУ ДОГОВРУ
	insert into dbo.SZV4_STAZH (link_up, orders, date1, date2, ter_usl, ter_koef, osob_usl, osob_k1, osob_k2, osob_k3, is_osnov, is_dop, is_dop_m, is_dop_d, ud_osnov, ud_dop_m, ud_dop_d, ud_dop_k, osob_spo)
	Select S.link, P.orders, P.date1, P.date2, 
		ter_usl = ISNULL(spr1.CODE,spr1A.CODE),
		ter_koef = ISNULL(T.TERR_RK,TA.TERR_RK),
		osob_usl = ISNULL(spr2.CODE,spr2A.CODE),
		osob_k1 = ISNULL(spr6.CODE,spr6A.CODE),
		osob_k2 = ISNULL(spr7.CODE,spr7A.CODE),
		osob_k3 = NULL,
		is_osnov = NULL, 
		is_dop = LTRIM(RTRIM(ISNULL(T.IS_DOP,TA.IS_DOP))),
		is_dop_m = NULL, 
		is_dop_d = NULL, 
		ud_osnov = ISNULL(spr5.CODE,spr5A.CODE), 
		ud_dop_m = NULL, 
		ud_dop_d = NULL, 
		ud_dop_k = ISNULL(T.STAVKA_PED_MED,TA.STAVKA_PED_MED) * P.NUM_STAKE,
		osob_spo = ISNULL(spr9.CODE,spr9A.CODE)
	from
		#PERSON B 
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
		inner join #PERIODY3 P on S.link_pers = P.link_face AND S.LINK_KATEG = P.LINK_KATEG
		
		LEFT JOIN #ADD_TYPE T ON P.[TYPE] = T.[TYPE]
		LEFT JOIN dbo.szv4_spr spr1 on spr1.spr_code = 'TERR_USL' and spr1.LINK = T.TERR_USL_TRUD
		LEFT JOIN dbo.szv4_spr spr2 on spr2.spr_code = 'OSOB_USL_TRUDA' and spr2.LINK = T.OSOB_USL_TRUD
		--left join dbo.szv4_spr spr3 on spr3.spr_code = 'ISCHISL_STAZH_OSNOV' and spr3.code = T.is_osnov
		--left join dbo.szv4_spr spr4 on spr4.spr_code = 'ISCHISL_STAZH_DOP_SV' and spr4.code = T.is_dop
		left join dbo.szv4_spr spr5 on spr5.spr_code = 'DOSR_NAZN_PEN_OSNOV' and spr5.LINK = T.USL_DOSROCH_PENS
		left join dbo.szv4_spr spr6 on spr6.SPR_CODE LIKE 'SPISOK%' and spr6.LINK = T.COD_POS_SPISOK
		left join dbo.szv4_spr spr7 on spr7.SPR_CODE LIKE 'SPISOK%' and spr7.LINK = T.COD_POS_SPISOK2
		--left join dbo.szv4_spr spr8 on spr8.spr_code = 'LGOT_PROFES' and spr8.code = T.osob_k3
		left join dbo.szv4_spr spr9 on spr9.SPR_CODE LIKE 'SPO_USL_TRUDA' and spr9.LINK = T.[COD_SPO_USL_TRUD]

		LEFT JOIN #ADD_TYPE TA ON P.[TYPE_ADD] = TA.[TYPE] AND P.[TYPE_ADD] <> P.[TYPE]
		LEFT JOIN dbo.szv4_spr spr1A on spr1A.spr_code = 'TERR_USL' and spr1A.LINK = TA.TERR_USL_TRUD
		LEFT JOIN dbo.szv4_spr spr2A on spr2A.spr_code = 'OSOB_USL_TRUDA' and spr2A.LINK = TA.OSOB_USL_TRUD
		--left join dbo.szv4_spr spr3 on spr3.spr_code = 'ISCHISL_STAZH_OSNOV' and spr3.code = T.is_osnov
		--left join dbo.szv4_spr spr4 on spr4.spr_code = 'ISCHISL_STAZH_DOP_SV' and spr4.code = T.is_dop
		left join dbo.szv4_spr spr5A on spr5A.spr_code = 'DOSR_NAZN_PEN_OSNOV' and spr5A.LINK = TA.USL_DOSROCH_PENS
		left join dbo.szv4_spr spr6A on spr6A.SPR_CODE LIKE 'SPISOK%' and spr6A.LINK = TA.COD_POS_SPISOK
		left join dbo.szv4_spr spr7A on spr7A.SPR_CODE LIKE 'SPISOK%' and spr7A.LINK = TA.COD_POS_SPISOK2
		--left join dbo.szv4_spr spr8 on spr8.spr_code = 'LGOT_PROFES' and spr8.code = T.osob_k3	
		left join dbo.szv4_spr spr9A on spr9A.SPR_CODE LIKE 'SPO_USL_TRUDA' and spr9A.LINK = TA.[COD_SPO_USL_TRUD]
	where
		S.link_up = @link
		AND
		S.FORMA = 1
	order by
		S.link, P.orders

	--СТАХ ПО ГПХ
	CREATE TABLE #STAGE_DOG (
		LINK_PERS INT, 
		KATEG TINYINT,
		BERIOD_BEG DATETIME,
		BERIOD_END DATETIME
		)

	INSERT INTO #STAGE_DOG (LINK_PERS, KATEG, BERIOD_BEG, BERIOD_END)
	SELECT LINK_FACE, LINK_KATEG, MIN(date1), MAX(date2) 
	FROM #DGH A
	GROUP BY LINK_FACE, LINK_KATEG

	insert into dbo.SZV4_STAZH (link_up, orders, date1, date2)
	Select S.link, 1, P.BERIOD_BEG, P.BERIOD_END
	from
		#PERSON B 
		INNER JOIN dbo.SZV4_SVEDENIA S ON S.LINK_PERS = B.LINK
		INNER JOIN #STAGE_DOG P on S.link_pers = P.LINK_PERS AND S.LINK_KATEG = P.KATEG
	where
		S.link_up = @link
		AND
		S.FORMA = 2
	order by
		S.link
		
end
--------------------------------------------------------------------------
/* не должно быть физлиц, по которым в данном периоде нет сумм и сведений о стаже 
C 14 ГОДА распределять уплату не нужно
*/	
DELETE FROM dbo.SZV4_SVEDENIA
WHERE 
LINK_UP = @link
AND
EXISTS (		
	Select  1
	from dbo.sa_szv4_svedenia S inner join  dbo.szv4_pachka p on p.link = s.link
	WHERE 
		S.LINK1 = dbo.SZV4_SVEDENIA.LINK
		AND s.sum_doh = 0 AND s.INSUR = 0 AND s.GAIN = 0 AND s.DOP = 0 and s.sum_uplata_dolga_str = 0 and s.sum_uplata_dolga_nak = 0
		and p.vid_kor != 3
		AND NOT EXISTS (SELECT * FROM dbo.SZV4_STAZH ST WHERE ST.LINK_UP = S.LINK1)
)

--------------------------------------------------------------------------
exec dbo.SZV4_NUMERATOR @link



GO


GRANT EXECUTE ON dbo.[SA_SZV4_PACHKA_CALC_Buffer3] TO PUBLIC

GO



GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BB_DOLG_KNIGA]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_DOLG_KNIGA]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
c Кейсистемс (Keysystems), 2005
*/

create  procedure dbo.BB_DOLG_KNIGA
	@dDateB 	datetime,
	@dDateE 	datetime

as
declare @iOwnDep	int,
		@dDateRest  datetime
	
declare @tRest table(DOC int,
		      		SUMMA numeric(28,2),
					[TYPE]	tinyint)

declare @tOborot table(	DOC int,
						[DATE] datetime,
						SUM_PER numeric(28,2),
						SUM_UPL numeric(28,2),
						PROC_N numeric(28,2),
						PROC_P numeric(28,2))

declare @tDoc table(LINK_AP1 int,
					LINK_G int,
					INFO varchar(1000),
		      		KDEP_NAME varchar(1000),
		      		SUMMA numeric(28,2),
					[TYPE_NAME]	varchar(1000),
					DATE_BEG datetime,
					DATE_END datetime,
					[PROC] numeric(10,4),
					[TYPE]	tinyint)
		
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'
exec dbo.BufferClear 'CREDIT_ACC_11'

insert into BUFFER (link, id)
select link, 'CREDIT_ACC' from s_accounts where code like '%301.1[1,2,3]'

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'

insert into BUFFER (link, id)
select link, 'CREDIT_ACC_11' from s_accounts where code = '11'

--insert into @tDoc 
--select * from (
--	select  O.LINK,
--			O.DOC_LINK,
--			O.INFO, 
--			C.KDEP_NAME,
--			C.SUMMA,
--			C.[TYPE_NAME],
--			--C.DATE_BEG,
--			C.DATE,
--			C.DATE_END,
--			[PROC] = dbo.BB_CREDIT_PROC(C.LINK, @dDateE,'PROC',0),
--			[TYPE] = case when exists(select * from dbo.G_PROV_AP GAP inner join dbo.S_ACCOUNTS SA on SA.LINK = GAP.ACCOUNT and SA.CODE = '1.301.11' where GAP.AP1 = O.LINK) then 1
--							when exists(select * from dbo.G_PROV_AP GAP inner join dbo.S_ACCOUNTS SA on SA.LINK = GAP.ACCOUNT and SA.CODE = '1.301.12' where GAP.AP1 = O.LINK) then 2
--							when exists(select * from dbo.G_PROV_AP GAP inner join dbo.S_ACCOUNTS SA on SA.LINK = GAP.ACCOUNT and SA.CODE = '1.301.13' where GAP.AP1 = O.LINK) then 3
--							when exists(select * from dbo.G_PROV_AP GAP inner join dbo.S_ACCOUNTS SA on SA.LINK = GAP.ACCOUNT and SA.CODE = '11' where GAP.AP1 = O.LINK) then 4
--					 else 0 end
--	from dbo.BD_OSNOV O
--	inner join dbo.BB_P_CREDIT C on C.LINK = O.DOC_LINK
--	where C.DEP_LINK = @iOwnDep and C.DATE_BEG <= @dDateE and C.DATE_END >= @dDateB) A
--where [TYPE] <> 0


insert into @tOborot
select isnull(S.KT_AP1, S.DT_AP1), S.DATE_PROV, sum(S.SUMMA), 0, 0, 0
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
where S.SUMMA <> 0
group by isnull(S.KT_AP1, S.DT_AP1), S.DATE_PROV, S.KT_ACCOUNT

insert into @tOborot
select isnull(S.DT_AP1, S.KT_AP1), S.DATE_PROV, 0, sum(S.SUMMA), 0, 0
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
where S.SUMMA <> 0
group by isnull(S.DT_AP1, S.KT_AP1), S.DATE_PROV, DT_ACCOUNT

insert into @tOborot
select isnull(S.KT_AP1, S.DT_AP1), S.DATE_PROV, 0, 0, sum(S.SUMMA), 0
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
where S.SUMMA <> 0
group by isnull(S.KT_AP1, S.DT_AP1), S.DATE_PROV, S.KT_ACCOUNT

insert into @tOborot
select isnull(S.DT_AP1, S.KT_AP1), S.DATE_PROV, 0, 0, 0, sum(S.SUMMA)
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
where S.SUMMA <> 0
group by isnull(S.DT_AP1, S.KT_AP1), S.DATE_PROV, DT_ACCOUNT


insert into @tOborot
select GAP.AP1, G.DATE_PROV, CASE GAP.DB_KR when 0 THEN sum(G2.SUMMA) ELSE 0 END, CASE GAP.DB_KR when 1 THEN sum(G2.SUMMA) ELSE 0 END, 0, 0
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)
INNER JOIN S_ACCOUNTS SA ON (GAP.ACCOUNT = SA.LINK)
where G.DATE_PROV BETWEEN @dDateB AND @dDateE
		AND G.LINK = G1.LINK_UP
		and G2.SUMMA <> 0
		AND sa.CODE = '11'
group by GAP.AP1, G.DATE_PROV, GAP.DB_KR

insert into @tRest
select R.AP1, sum(R.K_SUMMA - R.D_SUMMA), case KBK.TYPE when 1 then 1 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
group by R.AP1, KBK.TYPE, ACCOUNT

set @dDateE = @dDateE + 1
insert into @tRest
select R.AP1, sum(R.K_SUMMA - R.D_SUMMA), 2 + case KBK.TYPE when 1 then 1 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
group by R.AP1, KBK.TYPE, ACCOUNT

insert into @tRest
select R.AP1, sum(R.K_SUMMA - R.D_SUMMA), case KBK.TYPE when 1 then 1 else 0 end
from dbo.aRestTableByDateAccounts(@dDateB,'CREDIT_ACC_11') R
inner join dbo.KL_KBK KBK on R.KBK = KBK.LINK and KBK.TYPE <> 2
group by R.AP1, KBK.TYPE, ACCOUNT

set @dDateE = @dDateE + 1
insert into @tRest
select R.AP1, sum(R.K_SUMMA - R.D_SUMMA), 2 + case KBK.TYPE when 1 then 1 else 0 end 
from dbo.aRestTableByDateAccounts(@dDateE,'CREDIT_ACC_11') R
inner join dbo.KL_KBK KBK on R.KBK = KBK.LINK and KBK.TYPE <> 2
group by R.AP1, KBK.TYPE, ACCOUNT

insert into @tDoc 
select * from (
	select  O.LINK,
			O.DOC_LINK,
			O.INFO, 
			C.KDEP_NAME,
			C.SUMMA,
			C.[TYPE_NAME],
			--C.DATE_BEG,
			C.DATE,
			C.DATE_END,
			[PROC] = dbo.BB_CREDIT_PROC(C.LINK, @dDateE,'PROC',0),
			[TYPE] = case when exists(select * from dbo.G_PROV_AP GAP inner join dbo.S_ACCOUNTS SA on SA.LINK = GAP.ACCOUNT and SA.CODE = '1.301.11' where GAP.AP1 = O.LINK) then 1
							when exists(select * from dbo.G_PROV_AP GAP inner join dbo.S_ACCOUNTS SA on SA.LINK = GAP.ACCOUNT and SA.CODE = '1.301.12' where GAP.AP1 = O.LINK) then 2
							when exists(select * from dbo.G_PROV_AP GAP inner join dbo.S_ACCOUNTS SA on SA.LINK = GAP.ACCOUNT and SA.CODE = '1.301.13' where GAP.AP1 = O.LINK) then 3
							when exists(select * from dbo.G_PROV_AP GAP inner join dbo.S_ACCOUNTS SA on SA.LINK = GAP.ACCOUNT and SA.CODE = '11' where GAP.AP1 = O.LINK) then 4
					 else 0 end
	from dbo.BD_OSNOV O
	left join dbo.BB_P_CREDIT C on C.LINK = O.DOC_LINK
	where C.LINK is not null and C.DEP_LINK = @iOwnDep and C.DATE_BEG <= @dDateE and C.DATE_END >= @dDateB
			or exists(select * from @tOborot where DOC = O.LINK) and exists(select * from dbo.G_PROV_AP GAP inner join dbo.S_ACCOUNTS SA on SA.LINK = GAP.ACCOUNT and SA.CODE = '11' where GAP.AP1 = O.LINK)
			) A
where [TYPE] <> 0


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 'SGU_D'
exec dbo.BufferClear 'SGU_K'
exec dbo.BufferClear 'SGU_K_KL_N'
exec dbo.BufferClear 'CREDIT_ACC_11'

select	DOC = D.LINK_G, 
		D.INFO, 
		D.KDEP_NAME,
		D.SUMMA,
		D.[TYPE_NAME],
		D.DATE_BEG,
		D.DATE_END,
		OB.[DATE],
		D.[PROC],
		REST_B = isnull(RB.SUMMA,0),
		REST_E = isnull(RE.SUMMA,0),
		REST_BP = isnull(RPB.SUMMA,0),
		REST_EP = isnull(RPE.SUMMA,0),
		SUM_PER = isnull(OB.SUM_PER,0), 
		SUM_UPL = isnull(OB.SUM_UPL,0),
		PROC_N = isnull(OB.PROC_N,0),
		PROC_P = isnull(OB.PROC_P,0),
		OPER_NAME = case when isnull(OB.PROC_N,0) <> 0 or isnull(OB.PROC_N,0) <> 0 then 'Начисление процентов' else '' end
		
from @tDoc D
left join (select DOC, [DATE], 
			SUM_PER = sum(isnull(SUM_PER,0)), SUM_UPL = sum(isnull(SUM_UPL,0)), 
			PROC_N = sum(isnull(PROC_N,0)), PROC_P = sum(isnull(PROC_P,0))
			from @tOborot  group by DOC, [DATE]) OB on OB.DOC = D.LINK_AP1
left join @tRest RB on RB.DOC = D.LINK_AP1 and RB.[TYPE] = 0
left join @tRest RE on RE.DOC = D.LINK_AP1 and RE.[TYPE] = 2
left join @tRest RPB on RPB.DOC = D.LINK_AP1 and RPB.[TYPE] = 1
left join @tRest RPE on RPE.DOC = D.LINK_AP1 and RPE.[TYPE] = 3
where D.[TYPE] = 1
union
select	0,	'', '', 0, '', NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, ''
where not exists(select * from @tDoc where [TYPE] = 1)
order by D.LINK_G, OB.[DATE] 



select	0, [MONTH] = 'на начало года',
		REST = sum(isnull(RB.SUMMA,0)),
		REST_P = sum(isnull(RPB.SUMMA,0)),
		SUM_PER = 0, 
		SUM_UPL = 0,
		PROC_N = 0,
		PROC_P = 0
from @tDoc D
left join @tRest RB on RB.DOC = D.LINK_AP1 and RB.[TYPE] = 0
left join @tRest RPB on RPB.DOC = D.LINK_AP1 and RPB.[TYPE] = 1
where D.[TYPE] = 1
union
select	M.NUM, M.MON, 0, 0,
		sum(isnull(OB.SUM_PER,0)), 
		sum(isnull(OB.SUM_UPL,0)),
		sum(isnull(OB.PROC_N,0)),
		sum(isnull(OB.PROC_P,0))
from dbo.Months M
left join @tOborot OB on month(OB.DATE) = M.NUM
left join @tDoc D on OB.DOC = D.LINK_AP1 and D.[TYPE] = 1
where D.[TYPE] = 1 or OB.DATE is null
group by M.NUM, M.MON
union
select	13, [MONTH] = 'на конец года',
		REST = sum(isnull(RE.SUMMA,0)),
		REST_P = sum(isnull(RPE.SUMMA,0)),
		SUM_PER = 0, 
		SUM_UPL = 0,
		PROC_N = 0,
		PROC_P = 0
from @tDoc D
left join @tRest RE on RE.DOC = D.LINK_AP1 and RE.[TYPE] = 2
left join @tRest RPE on RPE.DOC = D.LINK_AP1 and RPE.[TYPE] = 3
where D.[TYPE] = 1
order by 1

select	DOC = D.LINK_G, 
		D.INFO, 
		D.KDEP_NAME,
		D.SUMMA,
		D.[TYPE_NAME],
		D.DATE_BEG,
		D.DATE_END,
		OB.[DATE],
		D.[PROC],
		REST_B = isnull(RB.SUMMA,0),
		REST_E = isnull(RE.SUMMA,0),
		REST_BP = isnull(RPB.SUMMA,0),
		REST_EP = isnull(RPE.SUMMA,0),
		SUM_PER = isnull(OB.SUM_PER,0), 
		SUM_UPL = isnull(OB.SUM_UPL,0),
		PROC_N = isnull(OB.PROC_N,0),
		PROC_P = isnull(OB.PROC_P,0),
		OPER_NAME = case when isnull(OB.PROC_N,0) <> 0 or isnull(OB.PROC_N,0) <> 0 then 'Начисление процентов' else '' end
		
from @tDoc D
left join (select DOC, [DATE], 
			SUM_PER = sum(isnull(SUM_PER,0)), SUM_UPL = sum(isnull(SUM_UPL,0)), 
			PROC_N = sum(isnull(PROC_N,0)), PROC_P = sum(isnull(PROC_P,0))
			from @tOborot  group by DOC, [DATE]) OB on OB.DOC = D.LINK_AP1
left join @tRest RB on RB.DOC = D.LINK_AP1 and RB.[TYPE] = 0
left join @tRest RE on RE.DOC = D.LINK_AP1 and RE.[TYPE] = 2
left join @tRest RPB on RPB.DOC = D.LINK_AP1 and RPB.[TYPE] = 1
left join @tRest RPE on RPE.DOC = D.LINK_AP1 and RPE.[TYPE] = 3
where D.[TYPE] = 3
union
select	0,	'', '', 0, '', NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, ''
where not exists(select * from @tDoc where [TYPE] = 3)
order by D.LINK_G, OB.[DATE] 



select	0, [MONTH] = 'на начало года',
		REST = sum(isnull(RB.SUMMA,0)),
		REST_P = sum(isnull(RPB.SUMMA,0)),
		SUM_PER = 0, 
		SUM_UPL = 0,
		PROC_N = 0,
		PROC_P = 0
from @tDoc D
left join @tRest RB on RB.DOC = D.LINK_AP1 and RB.[TYPE] = 0
left join @tRest RPB on RPB.DOC = D.LINK_AP1 and RPB.[TYPE] = 1
where D.[TYPE] = 3
union
select	M.NUM, M.MON, 0, 0,
		sum(isnull(OB.SUM_PER,0)), 
		sum(isnull(OB.SUM_UPL,0)),
		sum(isnull(OB.PROC_N,0)),
		sum(isnull(OB.PROC_P,0))
from dbo.Months M
left join @tOborot OB on month(OB.DATE) = M.NUM
left join @tDoc D on OB.DOC = D.LINK_AP1 -- and D.[TYPE] = 2
where D.[TYPE] = 3 or OB.DATE is null
group by M.NUM, M.MON
union
select	13, [MONTH] = 'на конец года',
		REST = sum(isnull(RE.SUMMA,0)),
		REST_P = sum(isnull(RPE.SUMMA,0)),
		SUM_PER = 0, 
		SUM_UPL = 0,
		PROC_N = 0,
		PROC_P = 0
from @tDoc D
left join @tRest RE on RE.DOC = D.LINK_AP1 and RE.[TYPE] = 2
left join @tRest RPE on RPE.DOC = D.LINK_AP1 and RPE.[TYPE] = 3
where D.[TYPE] = 3
order by 1

select	DOC = D.LINK_G, 
		D.INFO, 
		D.KDEP_NAME,
		D.SUMMA,
		D.[TYPE_NAME],
		D.DATE_BEG,
		D.DATE_END,
		OB.[DATE],
		D.[PROC],
		REST_B = isnull(RB.SUMMA,0),
		REST_E = isnull(RE.SUMMA,0),
		REST_BP = isnull(RPB.SUMMA,0),
		REST_EP = isnull(RPE.SUMMA,0),
		SUM_PER = isnull(OB.SUM_PER,0), 
		SUM_UPL = isnull(OB.SUM_UPL,0),
		PROC_N = isnull(OB.PROC_N,0),
		PROC_P = isnull(OB.PROC_P,0),
		OPER_NAME = case when isnull(OB.PROC_N,0) <> 0 or isnull(OB.PROC_N,0) <> 0 then 'Начисление процентов' else '' end
		
from @tDoc D
left join (select DOC, [DATE], 
			SUM_PER = sum(isnull(SUM_PER,0)), SUM_UPL = sum(isnull(SUM_UPL,0)), 
			PROC_N = sum(isnull(PROC_N,0)), PROC_P = sum(isnull(PROC_P,0))
			from @tOborot  group by DOC, [DATE]) OB on OB.DOC = D.LINK_AP1
left join @tRest RB on RB.DOC = D.LINK_AP1 and RB.[TYPE] = 0
left join @tRest RE on RE.DOC = D.LINK_AP1 and RE.[TYPE] = 2
left join @tRest RPB on RPB.DOC = D.LINK_AP1 and RPB.[TYPE] = 1
left join @tRest RPE on RPE.DOC = D.LINK_AP1 and RPE.[TYPE] = 3
where D.[TYPE] = 2
union
select	0,	'', '', 0, '', NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, ''
where not exists(select * from @tDoc where [TYPE] = 2)
order by D.LINK_G, OB.[DATE] 



select	0, [MONTH] = 'на начало года',
		REST = sum(isnull(RB.SUMMA,0)),
		REST_P = sum(isnull(RPB.SUMMA,0)),
		SUM_PER = 0, 
		SUM_UPL = 0,
		PROC_N = 0,
		PROC_P = 0
from @tDoc D
left join @tRest RB on RB.DOC = D.LINK_AP1 and RB.[TYPE] = 0
left join @tRest RPB on RPB.DOC = D.LINK_AP1 and RPB.[TYPE] = 1
where D.[TYPE] = 2
union
select	M.NUM, M.MON, 0, 0,
		sum(isnull(OB.SUM_PER,0)), 
		sum(isnull(OB.SUM_UPL,0)),
		sum(isnull(OB.PROC_N,0)),
		sum(isnull(OB.PROC_P,0))
from dbo.Months M
left join @tOborot OB on month(OB.DATE) = M.NUM
left join @tDoc D on OB.DOC = D.LINK_AP1 -- and D.[TYPE] = 2
where D.[TYPE] = 2 or OB.DATE is null
group by M.NUM, M.MON
union
select	13, [MONTH] = 'на конец года',
		REST = sum(isnull(RE.SUMMA,0)),
		REST_P = sum(isnull(RPE.SUMMA,0)),
		SUM_PER = 0, 
		SUM_UPL = 0,
		PROC_N = 0,
		PROC_P = 0
from @tDoc D
left join @tRest RE on RE.DOC = D.LINK_AP1 and RE.[TYPE] = 2
left join @tRest RPE on RPE.DOC = D.LINK_AP1 and RPE.[TYPE] = 3
where D.[TYPE] = 2
order by 1


select	DOC = D.LINK_G, 
		D.INFO, 
		D.KDEP_NAME,
		D.SUMMA,
		D.[TYPE_NAME],
		D.DATE_BEG,
		D.DATE_END,
		OB.[DATE],
		D.[PROC],
		REST_B = isnull(RB.SUMMA,0),
		REST_E = isnull(RE.SUMMA,0),
		REST_BP = isnull(RPB.SUMMA,0),
		REST_EP = isnull(RPE.SUMMA,0),
		SUM_PER = isnull(OB.SUM_PER,0), 
		SUM_UPL = isnull(OB.SUM_UPL,0),
		PROC_N = isnull(OB.PROC_N,0),
		PROC_P = isnull(OB.PROC_P,0),
		OPER_NAME = case when isnull(OB.PROC_N,0) <> 0 or isnull(OB.PROC_N,0) <> 0 then 'Начисление процентов' else '' end
		
from @tDoc D
left join (select DOC, [DATE], 
			SUM_PER = sum(isnull(SUM_PER,0)), SUM_UPL = sum(isnull(SUM_UPL,0)), 
			PROC_N = sum(isnull(PROC_N,0)), PROC_P = sum(isnull(PROC_P,0))
			from @tOborot  group by DOC, [DATE]) OB on OB.DOC = D.LINK_AP1
left join @tRest RB on RB.DOC = D.LINK_AP1 and RB.[TYPE] = 0
left join @tRest RE on RE.DOC = D.LINK_AP1 and RE.[TYPE] = 2
left join @tRest RPB on RPB.DOC = D.LINK_AP1 and RPB.[TYPE] = 1
left join @tRest RPE on RPE.DOC = D.LINK_AP1 and RPE.[TYPE] = 3
where D.[TYPE] = 4
union
select	0,	'', '', 0, '', NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, ''
where not exists(select * from @tDoc where [TYPE] = 4)
order by D.LINK_G, OB.[DATE] 



select	0, [MONTH] = 'на начало года',
		REST = sum(isnull(RB.SUMMA,0)),
		REST_P = sum(isnull(RPB.SUMMA,0)),
		SUM_PER = 0, 
		SUM_UPL = 0,
		PROC_N = 0,
		PROC_P = 0
from @tDoc D
left join @tRest RB on RB.DOC = D.LINK_AP1 and RB.[TYPE] = 0
left join @tRest RPB on RPB.DOC = D.LINK_AP1 and RPB.[TYPE] = 1
where D.[TYPE] = 4
union
select	M.NUM, M.MON, 0, 0,
		sum(isnull(OB.SUM_PER,0)), 
		sum(isnull(OB.SUM_UPL,0)),
		sum(isnull(OB.PROC_N,0)),
		sum(isnull(OB.PROC_P,0))
from dbo.Months M
left join @tOborot OB on month(OB.DATE) = M.NUM
left join @tDoc D on OB.DOC = D.LINK_AP1 -- and D.[TYPE] = 2
where D.[TYPE] = 4 or OB.DATE is null
group by M.NUM, M.MON
union
select	13, [MONTH] = 'на конец года',
		REST = sum(isnull(RE.SUMMA,0)),
		REST_P = sum(isnull(RPE.SUMMA,0)),
		SUM_PER = 0, 
		SUM_UPL = 0,
		PROC_N = 0,
		PROC_P = 0
from @tDoc D
left join @tRest RE on RE.DOC = D.LINK_AP1 and RE.[TYPE] = 2
left join @tRest RPE on RPE.DOC = D.LINK_AP1 and RPE.[TYPE] = 3
where D.[TYPE] = 4
order by 1

select	REST_E = sum(isnull(RE.SUMMA,0)),
		REST_EP = sum(isnull(RPE.SUMMA,0)),
		SUM_PER = sum(isnull(OB.SUM_PER,0)), 
		SUM_UPL = sum(isnull(OB.SUM_UPL,0)),
		PROC_N = sum(isnull(OB.PROC_N,0)),
		PROC_P = sum(isnull(OB.PROC_P,0))
		
from @tDoc D 
left join @tOborot OB  on OB.DOC = D.LINK_AP1 -- and D.[TYPE] = 2
left join @tRest RE on RE.DOC = D.LINK_AP1 and RE.[TYPE] = 2
left join @tRest RPE on RPE.DOC = D.LINK_AP1 and RPE.[TYPE] = 3
where D.[TYPE] <> 0


return 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
grant execute on dbo.BB_DOLG_KNIGA to public
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_SZV_K_STAZH_DELETE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SZV_K_STAZH_DELETE]

GO



---------------------------------

CREATE PROCEDURE dbo.SA_SZV_K_STAZH_DELETE
	@varKSintLINK	int
AS
DECLARE @varKStrancount	int,
		@varKSObjectLink	int,
		@varKSEventText	varchar(254)

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

	DECLARE @link_up int
	select @link_up = link_up from dbo.SZV_K_STAZH where link = @varKSintLINK
	
	
	Select  @varKSEventText = 'Основная запись о стаже по физлицу ' + RTRIM(LTRIM(s.FIO)) + ', в организации' + RTRIM(LTRIM(sv.NAME_DEP)) 
	from dbo.SA_SZV_K_SVEDENIA  s 
	INNER join dbo.sa_szv_k_sved_work_dep sv ON s.link1 = sv.link 
		WHERE sv.link1 = @LINK_UP

	Select  @varKSEventText = @varKSEventText + ' с ' + convert(varchar(10), date1, 104) + ' по ' + convert(varchar(10), coalesce(date2,'20990101'), 104) from dbo.SZV_K_STAZH 
		WITH (UPDLOCK) WHERE link = @varKSintLINK

	IF @@RowCount = 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 2
	END

	DELETE FROM dbo.SZV_K_STAZH WHERE LINK = @varKSintLINK
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END


	/*Правильная сортировка*/
	declare @uslovie int
	set @uslovie = 1
	
	update SZV_K_STAZH set orders = 0 where link_up = @link_up
	
	while @uslovie > 0
	begin
		update SZV_K_STAZH set orders = @uslovie 
		from SZV_K_STAZH as tt
		where 	
			link_up = @link_up
			and coalesce(orders,0) = 0
			and date1 = (select min(t.date1) from SZV_K_STAZH t where coalesce(orders,0) = 0 and link_up = @link_up)
	
		if @@rowcount > 0
			set @uslovie = @uslovie + 1
		else
			set @uslovie = 0
	end

IF @@TRANCOUNT > @varKStrancount
	BEGIN
		SELECT @varKSObjectLink = LINK FROM S_OBJECTS WHERE CODE = 'SA_SZV_K_STAZH_OSN'
		EXECUTE WF_GENERATEEVENT 'Удаление из справочника', @varKSEventText, @varKSObjectLink, 'SA_SZV_K_STAZH_OSN', @varKSintLINK

		COMMIT TRAN
	END
RETURN 0


GO


GRANT EXECUTE ON dbo.[SA_SZV_K_STAZH_DELETE] TO PUBLIC

GO




GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[KIR_EXEC_SALARY_ESN_REPORT1]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KIR_EXEC_SALARY_ESN_REPORT1]

GO
CREATE PROCEDURE [dbo].[KIR_EXEC_SALARY_ESN_REPORT1]

	@DATE1 DATETIME,			/* Начало периода */
	@DATE2 DATETIME,			/* Конец периода */
	@CHECK1 INT	= 1,			/* Мужчины до 1952 г. р., женщины до 1956 */
	@CHECK2 INT	= 1,			/* Мужчины до 1952 г. р., женщины до 1956 */
	@CHECK3 INT	= 1,			/* 1967 г.р. и моложе */
	@ORDERBY INT,				/* Сортировать по */

	@DETAL_SUB TINYINT = 1,		/* Детализировать по подразделениям */
	@DETAL_FIO TINYINT = 1,		/* Детализировать по сотрудникам */
	@DETAL_SOURCE TINYINT = 1,	/* Детализировать по источникам */
	
	@DGH TINYINT = 0,			/* Включать договорников */
	@SHOW_Data TINYINT = 0 ,	/* Вывод данных : 1) по страховым взносам  , 2) по доп тарифам  */
	@cVAL1 CHAR(1)='', @nOTBORLINK1 INT = 0, /* Отбор сотрудников */
	@cVAL2 CHAR(1)='', @nOTBORLINK2 INT = 0, /* Отбор подразделений */
	@cVAL3 CHAR(1)='', @nOTBORLINK3 INT = 0 /* Отбор источников */

AS 
BEGIN

	DECLARE @LINK_DEP INT
	EXEC DBO.XD_WHATS_ZB @LINK_DEP OUTPUT
	
	DECLARE @YEAR_BEG DATETIME
	SET @YEAR_BEG = dbo.DateBeginOfyEAR(@DATE2)	

	CREATE TABLE #EMPLS(LINK_EMPL INT)
	IF LEN(@cVAL1) <> 0 
		INSERT INTO #EMPLS
		SELECT RECORD AS LINK_EMPL FROM DBO.OBJECT_VAR_EMPL WHERE LINK_UP = @nOTBORLINK1
	ELSE
		INSERT INTO #EMPLS
		SELECT LINK AS LINK_EMPL 
 		FROM DBO.EMPL WHERE DEP_LINK = @LINK_DEP

	CREATE TABLE #SUBDIV(LINK_SUB INT)
	IF LEN(@cVAL2) <> 0 
		INSERT INTO #SUBDIV
		SELECT RECORD FROM DBO.OBJECT_VAR_SUBDIV_HEAD WHERE LINK_UP = @nOTBORLINK2

	--
	DECLARE @Y INT, @MIN_M INT, @MAX_M INT
	SELECT @Y = YEAR(@DATE2), @MAX_M = MONTH(@DATE2), @MIN_M = CASE WHEN YEAR(@DATE1) = YEAR(@DATE2) THEN MONTH(@DATE1) ELSE 1 END

	DECLARE @WAY TABLE (WAY_CALC TINYINT) 
	INSERT INTO @WAY(WAY_CALC)
	SELECT T4.way_calc
	FROM 
		dbo.DICTIONARY_MROT_TABLE4 t4
	WHERE
		t4.link_minrot = (SELECT TOP 1 link FROM dbo.DICTIONARY_MROT ss WHERE ss.period <= @DATE1 ORDER BY ss.period DESC)

	--
	CREATE TABLE #T1 (LINK_VKR INT, MONTH_BASE NUMERIC(18,2), SUMMA_BASE NUMERIC(18,2), DED_M NUMERIC(18,2), INV_M NUMERIC(18,2), SUMMA NUMERIC(18,2), WAY_CALC TINYINT, REF_PHYS_PERS INT, DGH TINYINT, SPO INT)
	
	INSERT INTO #T1 (LINK_VKR, MONTH_BASE, SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, DGH, SPO)
	SELECT 
		LINK_VKR = (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END),
		MONTH_BASE, SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, 0 ,SPO = SPECO  
	FROM DBO.SA_ESN_VIEW(@Y, @MAX_M, @LINK_DEP, 0) E
	WHERE 
		(@cVAL3 = '' OR @cVAL3 <> '' AND EXISTS (SELECT RECORD FROM DBO.OBJECT_VAR_SAL_SFIN V WHERE LINK_UP = @nOTBORLINK3 AND V.RECORD = E.LINK_VKR))
	--	
	DECLARE @CUR1 CURSOR
	SET @CUR1 = CURSOR FORWARD_ONLY

	FOR SELECT Y, MIN(M) AS MIN_M, MAX(M) AS MAX_M FROM DBO.MONTHS_EX(@YEAR_BEG, @DATE2) WHERE Y < @Y GROUP BY Y ORDER BY Y DESC 
	
	OPEN @CUR1
	FETCH NEXT FROM @CUR1 INTO @Y, @MIN_M, @MAX_M
	WHILE (@@FETCH_STATUS <> -1)
	BEGIN
		IF (@@FETCH_STATUS <> -2)
		BEGIN

			INSERT INTO #T1 (LINK_VKR, MONTH_BASE, SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, DGH, SPO )
			SELECT 
				LINK_VKR = (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END),
				MONTH_BASE, SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, 0 , SPO = SPECO
			FROM DBO.SA_ESN_VIEW(@Y, @MAX_M, @LINK_DEP, 0) E 
			WHERE MONTH_BASE >= @MIN_M
					AND (@cVAL3 = '' OR @cVAL3 <> '' AND EXISTS (SELECT RECORD FROM DBO.OBJECT_VAR_SAL_SFIN V WHERE LINK_UP = @nOTBORLINK3 AND V.RECORD = E.LINK_VKR))
		END
	
		FETCH NEXT FROM @CUR1 INTO @Y, @MIN_M, @MAX_M
	END
	
	CLOSE @CUR1
	DEALLOCATE @CUR1

	DECLARE @LINK_OBJ__DOCUMENTS_DGH INT
	SELECT @LINK_OBJ__DOCUMENTS_DGH = LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOCUMENTS_DGH' 

	---Суммы по договорникам
	IF @DGH = 1
		INSERT INTO #T1 (LINK_VKR, MONTH_BASE, SUMMA_BASE, DED_M, INV_M, SUMMA, WAY_CALC, REF_PHYS_PERS, DGH)
		SELECT
			LINK_VKR = (CASE WHEN @DETAL_SOURCE = 1 THEN GT.LINK_VKR ELSE 0 END), 
			MONTH(G.[DATE]) AS MONTH_BASE, 
			GT.SUMMA_BASE, 
			DED_M = 0, 
			INV_M = 0, 
			GT.SUMMA, P.WAY_CALC, GT.PERS_LINK, 1
		FROM 
			dbo.SDOC G
			INNER JOIN dbo.SDOC_DGH_TABLE GT ON G.LINK = GT.LINK_UP
			INNER JOIN dbo.PAYS P ON P.LINK = GT.LINK_PAY
			INNER JOIN dbo.SAL_SFIN F ON F.LINK = GT.LINK_VKR
		WHERE
			G.[OBJECT] = @LINK_OBJ__DOCUMENTS_DGH
			AND GT.[OBJECT] = 3 AND P.WAY_CALC <> 5
			AND FLAG_JC = 1
			AND P.[OBJECT] = 3
			AND YEAR(G.[DATE]) = @Y
			AND MONTH(G.[DATE]) BETWEEN MONTH(@YEAR_BEG) AND @MAX_M
			AND LINK_DEP = @LINK_DEP
			AND (@cVAL3 = '' OR @cVAL3 <> '' AND EXISTS (SELECT RECORD FROM DBO.OBJECT_VAR_SAL_SFIN V WHERE LINK_UP = @nOTBORLINK3 AND V.RECORD = GT.LINK_VKR))
	--справочник баз для расчёта отчислений
	CREATE TABLE #BASE_PAYS (WAY_CALC TINYINT, LINK_PAYS INT)
	INSERT INTO #BASE_PAYS (P.WAY_CALC, LINK_PAYS)
	SELECT DISTINCT P.WAY_CALC, R.LINK_PAYS
	FROM 
		dbo.PAYS P INNER JOIN dbo.TAX_REF R ON R.link_tax = P.LINK 
	WHERE
		P.[OBJECT] = 3
		AND EXISTS ( SELECT * FROM @WAY W WHERE W.WAY_CALC = P.WAY_CALC )

	--фактическая база для договорников
	CREATE TABLE #DGH_FAKT_BASE (PERS_LINK INT, WAY_CALC TINYINT, LINK_PAY INT, Y INT, M TINYINT, LINK_VKR INT, SUMMA NUMERIC(18,2))
	INSERT INTO #DGH_FAKT_BASE (PERS_LINK, LINK_PAY, WAY_CALC, Y, M, LINK_VKR, SUMMA)
	SELECT 
		GT.PERS_LINK, GT1.LINK_PAY, GT.WAY_CALC, Y = YEAR(G.[DATE]), M = MONTH(G.[DATE]), 
		(CASE WHEN @DETAL_SOURCE = 1 THEN GT.LINK_VKR ELSE 0 END), 
		SUMMA_BASE = sum(GT.SUMMA_BASE)
	FROM 
		dbo.DOCUMENTS_DGH G 
		INNER JOIN dbo.DOCUMENTS_DGH_T1 GT1 ON G.LINK = GT1.LINK
		INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
	WHERE 
		FLAG_JC = 1
		AND YEAR(G.[DATE]) = @Y and MONTH(G.[DATE]) BETWEEN MONTH(@YEAR_BEG) AND @MAX_M 		
		AND (@cVAL3 = '' OR @cVAL3 <> '' AND EXISTS (SELECT RECORD FROM DBO.OBJECT_VAR_SAL_SFIN V WHERE LINK_UP = @nOTBORLINK3 AND V.RECORD = GT.LINK_VKR ))
		AND LINK_DEP = @LINK_DEP
	GROUP BY G.LINK, 
		GT.PERS_LINK, GT1.LINK_PAY, GT.WAY_CALC, YEAR(G.[DATE]), MONTH(G.[DATE]), GT.LINK_VKR

	--Начисленные суммы по лицам за период
	CREATE TABLE #CALC_OPER (PERS_LINK INT, LINK_PAYS INT, Y INT, M TINYINT, LINK_VKR INT, DGH TINYINT, SUMMA_ALL NUMERIC(18,2), SPO INT)
	INSERT INTO #CALC_OPER (PERS_LINK, LINK_PAYS, Y, M, LINK_VKR, DGH, SUMMA_ALL , SPO)
	--Сотрудники
	SELECT 
		E.PERS_LINK,
		cj.LINK_PAYS, Year(period_begin), Month(period_begin), 
		LINK_VKR = (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END),
		DGH = 0,
		SUMMA_ALL = SUM(CJ.SUMMA), 
		SPO = SPECO
	FROM 
		dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
		INNER JOIN DBO.EMPL E ON E.LINK = CJ.LINK_EMPL
	WHERE 	
		Year(period_begin) = @Y and Month(period_begin) BETWEEN @MIN_M AND @MAX_M 
		AND CJ.LINK_DEP = @LINK_DEP
		AND P.[OBJECT] = 1
		AND (@cVAL3 = '' OR @cVAL3 <> '' AND EXISTS (SELECT RECORD FROM DBO.OBJECT_VAR_SAL_SFIN V WHERE LINK_UP = @nOTBORLINK3 AND V.RECORD = CJ.LINK_VKR))
		AND (LEN(@cVAL1) = 0 OR EXISTS (SELECT * FROM #EMPLS WHERE LINK_EMPL = E.LINK))
	GROUP BY
		E.PERS_LINK, cj.LINK_PAYS, period_begin, CJ.SPECO, (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END)


	
	INSERT INTO #CALC_OPER (PERS_LINK, LINK_PAYS, Y, M, LINK_VKR, DGH, SUMMA_ALL, SPO)
	--Договорники
	SELECT 
		CJ.PERS_LINK,
		cj.LINK_PAYS, Year(period_begin), Month(period_begin),
		LINK_VKR = (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END),
		DGH = 1,
		SUMMA_ALL = SUM(CJ.SUMMA),
		SPO = SPECO
	FROM 
		dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
	WHERE
		@DGH = 1
		AND CJ.PERS_LINK IS NOT NULL
		AND Year(period_begin) = @Y and Month(period_begin) BETWEEN @MIN_M AND @MAX_M 
		AND CJ.LINK_DEP = @LINK_DEP
		AND P.[OBJECT] = 1
		AND (@cVAL3 = '' OR @cVAL3 <> '' AND EXISTS (SELECT RECORD FROM DBO.OBJECT_VAR_SAL_SFIN V WHERE LINK_UP = @nOTBORLINK3 AND V.RECORD = CJ.LINK_VKR))
	GROUP BY
		CJ.PERS_LINK, cj.LINK_PAYS, period_begin, CJ.SPECO, (CASE WHEN @DETAL_SOURCE = 1 THEN LINK_VKR ELSE 0 END)

	-----------
	CREATE TABLE #CALC_OPER_W(PERS_LINK INT, LINK_PAYS INT, Y INT, M INT, LINK_VKR INT, DGH TINYINT, SUMMA NUMERIC(18,2), WAY_CALC TINYINT, WAY_NAME VARCHAR(50) , SPO int)
	INSERT INTO #CALC_OPER_W (PERS_LINK, LINK_PAYS, Y, M, LINK_VKR, DGH, SUMMA, WAY_CALC, WAY_NAME , SPO)
	SELECT PERS_LINK, LINK_PAYS, Y, M, LINK_VKR, DGH, SUMMA_ALL, WC.CODE, WAY_NAME = (CASE WHEN ISNULL(SPO,0) >0 
																THEN WC.NAME  + ' - ' + (SELECT CODE FROM  SA_SZV4_SPR  s4 WHERE  s4.link =  CO.SPO  AND s4.spr_code = 'SPO_USL_TRUDA') 
														     ELSE  WC.NAME  END), CO.SPO
	FROM #CALC_OPER CO INNER JOIN dbo.WAY_CALC WC ON 1=1
	WHERE WC.[TYPE] = 2 
		AND EXISTS ( SELECT * FROM @WAY W WHERE W.WAY_CALC = WC.CODE )

	-----------
	DELETE FROM #CALC_OPER_W
	WHERE 
		DGH = 0 AND EXISTS
			(SELECT * FROM #BASE_PAYS BP WHERE #CALC_OPER_W.LINK_PAYS = BP.LINK_PAYS AND #CALC_OPER_W.WAY_CALC = BP.WAY_CALC)

	-----------
	DELETE FROM #CALC_OPER_W
	WHERE 
		DGH = 1 AND EXISTS
			(SELECT * FROM #DGH_FAKT_BASE D 
				WHERE
					D.PERS_LINK = #CALC_OPER_W.PERS_LINK
					AND D.WAY_CALC = #CALC_OPER_W.WAY_CALC
					AND D.LINK_PAY = #CALC_OPER_W.LINK_PAYS
					AND D.Y = #CALC_OPER_W.Y
					AND D.M = #CALC_OPER_W.M
					AND D.LINK_VKR = #CALC_OPER_W.LINK_VKR
			)

	----------------------------------------------------------------------------------------
	CREATE TABLE #FACT_SUMMA (LINK_PERS INT, LINK_SFIN INT, SUMMA NUMERIC(18,2), DGH TINYINT, SPO INT)
	INSERT INTO #FACT_SUMMA (LINK_PERS, LINK_SFIN, SUMMA, DGH , SPO)
	SELECT PERS_LINK, LINK_VKR, SUMMA_ALL = SUM(SUMMA_ALL), DGH, SPO 
	FROM 
		#CALC_OPER
	WHERE
		M BETWEEN MONTH(@DATE1) AND MONTH(@DATE2)	 
	GROUP BY 
		PERS_LINK, DGH, LINK_VKR, SPO

	--------------------------------------------------------------
	CREATE TABLE #PERS (LINK_PERS INT, LINK_SFIN INT, DGH TINYINT, SPO INT)

	INSERT INTO #PERS (LINK_PERS, LINK_SFIN, DGH , SPO)
	SELECT DISTINCT LINK_PERS, LINK_SFIN, DGH , SPO
	FROM
	(
		SELECT LINK_PERS = REF_PHYS_PERS, LINK_SFIN = LINK_VKR, DGH , SPO FROM #T1 WHERE MONTH_BASE BETWEEN MONTH(@DATE1) AND MONTH(@DATE2)
		UNION 
		SELECT LINK_PERS, LINK_SFIN, DGH, SPO FROM #FACT_SUMMA -- по месяцам ограничено уже (выше)
	) T	
	--------------------------------------------------------------

	CREATE TABLE #PERS_INFO (
		LINK_PERS INT,REF_EMPL INT,
		TAB_NUMER VARCHAR(10),NAME_EMPL VARCHAR(254),
		LINK_SFIN INT, YEAR_B DATETIME, POL TINYINT, TYPE1 TINYINT, LINK_FACE INT, 
		NAME_SUB VARCHAR(254), CODE_SUB VARCHAR(5), DGH TINYINT, SPO INT)

	INSERT INTO #PERS_INFO (LINK_PERS, REF_EMPL, TAB_NUMER, NAME_EMPL, LINK_SFIN, YEAR_B, POL, TYPE1, LINK_FACE, NAME_SUB, CODE_SUB, DGH, SPO)
	SELECT  
		P.LINK_PERS,
		REF_EMPL = K1.LINK, 
		TAB_NUMER = CASE WHEN DGH = 0 THEN COALESCE(K1.TAB,'') ELSE '' END, 
		NAME_EMPL = RTRIM(K.FM) + ' ' + SUBSTRING(RTRIM(K.IM),1,1) + '.' + SUBSTRING(RTRIM(K.OT),1,1) + '.', 
		LINK_SFIN,
		[YEAR_B] = K.BIRTHDATE,
		[POL] = K.SEX,
		[TYPE1] = (CASE WHEN K.SEX = 1 AND YEAR(K.BIRTHDATE)<= 1952 THEN 1
					    WHEN K.SEX = 2 AND YEAR(K.BIRTHDATE)<= 1956 THEN 1
					    WHEN K.SEX = 1 AND (YEAR(K.BIRTHDATE) BETWEEN 1953 AND 1966) THEN 2
					    WHEN K.SEX = 2 AND (YEAR(K.BIRTHDATE) BETWEEN 1957 AND 1966) THEN 2
						WHEN YEAR(K.BIRTHDATE) >= 1967 THEN 3
					    ELSE 0
					END) ,
		[LINK_FACE] = K.LINK,
		NAME_SUB = CASE WHEN DGH = 0 THEN COALESCE(K1.SUBDIV_NAME,'По договору ГПХ') ELSE 'По договору ГПХ' END,
		CODE_SUB = CASE WHEN DGH = 0 THEN COALESCE(K1.SUBDIV_CODE,'ДГХ') ELSE 'ДГХ' END,
		DGH,
		P.SPO
	FROM 
		#PERS P
		INNER JOIN DBO.PERSON K ON  P.LINK_PERS = K.LINK
		LEFT JOIN DBO.SD_EMPL_FN(DEFAULT,@DATE2,DEFAULT,@LINK_DEP) K1 ON 
				P.LINK_PERS = K1.PERS_LINK
			AND
				K1.[STATUS_EMPL] IN (1,3) 
			AND 
				K1.DATE_BEGIN = 
					(SELECT MAX(K2.DATE_BEGIN) FROM DBO.SD_EMPL_FN(DEFAULT,@DATE2,DEFAULT,@LINK_DEP) K2 
					WHERE K2.[STATUS_EMPL] IN (1,3) AND K1.PERS_LINK = K2.PERS_LINK AND K2.DATE_BEGIN IS NOT NULL)
	WHERE
		P.DGH = 1
		OR
		(
			(LEN(@cVAL1) = 0 OR EXISTS (SELECT * FROM #EMPLS WHERE LINK_EMPL = K1.LINK))
			AND 
			(LEN(@cVAL2) = 0 OR EXISTS (SELECT * FROM #SUBDIV WHERE LINK_SUB = K1.SUBDIV_HEAD))	
		)

	--
	DECLARE @LIMIT NUMERIC(18,2)

	SELECT DISTINCT P.WAY_CALC, LIMIT = MIN(S.PREDEL), SPECO = null
	INTO #PREDEL
	FROM 
		dbo.STAVKI S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3
	WHERE 
		[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI S1 INNER JOIN DBO.PAYS P1 ON S1.LINK_PAYS = P1.LINK AND P1.[OBJECT] = 3 AND P1.WAY_CALC = P.WAY_CALC AND [DATE] < @DATE2 ORDER BY [DATE] DESC) 
		AND
		S.PERCENT1 > 0
		AND EXISTS ( SELECT * FROM @WAY W WHERE W.WAY_CALC = P.WAY_CALC )
	GROUP BY P.WAY_CALC	

	INSERT INTO #PREDEL
	SELECT DISTINCT P.WAY_CALC, LIMIT = MIN(S.PREDEL) , SPECO = (CASE WHEN S.SPECO = 0 then null else s.SPECO end)
	FROM 
		dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.OBJECT = 3
	WHERE 
		[DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S1 INNER JOIN DBO.PAYS P1 ON S1.LINK_PAYS = P1.LINK AND P1.[OBJECT] = 3 AND P1.WAY_CALC = P.WAY_CALC AND [DATE] < @DATE2 ORDER BY [DATE] DESC) 
		AND
		(S.PERCENT1 > 0 OR S.PERCENT2 > 0 OR S.PERCENT3 > 0)
		AND EXISTS ( SELECT * FROM @WAY W WHERE W.WAY_CALC = P.WAY_CALC )		
	GROUP BY P.WAY_CALC	, S.SPECO	
	

	
	UPDATE #PREDEL
	SET LIMIT = 0
	WHERE LIMIT IS NULL

	SELECT MON = 1, REF_PHYS_PERS, DGH, T.WAY_CALC , T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END INTO #SPR_ESN1 FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 1 AND @MAX_M >= 1 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 2, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 2 AND @MAX_M >= 2 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 3, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 3 AND @MAX_M >= 3 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO 
	INSERT INTO #SPR_ESN1 SELECT MON = 4, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 4 AND @MAX_M >= 4 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 5, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 5 AND @MAX_M >= 5 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 6, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 6 AND @MAX_M >= 6 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 7, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 7 AND @MAX_M >= 6 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 8, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 8 AND @MAX_M >= 7 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 9, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 9 AND @MAX_M >= 8 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 10, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 10 AND @MAX_M >= 10 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 11, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 11 AND @MAX_M >= 11 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO
	INSERT INTO #SPR_ESN1 SELECT MON = 12, REF_PHYS_PERS, DGH, T.WAY_CALC, T.SPO, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) > LIMIT THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - LIMIT ELSE 0 END FROM #T1 T INNER JOIN #PREDEL P ON T.WAY_CALC = P.WAY_CALC and ISNULL(T.SPO,0) = ISNULL(P.SPECO,0) WHERE MONTH_BASE <= 12 AND @MAX_M >= 12 GROUP BY REF_PHYS_PERS, DGH, LIMIT, T.WAY_CALC, T.SPO


	SELECT T.REF_PHYS_PERS, T.DGH, T.WAY_CALC, T.SPO, T.MON, SUMMA = SUM(SUMMA)
	INTO #SPR_ESN2
	FROM
	(
	SELECT DISTINCT T.REF_PHYS_PERS, T.DGH, T.WAY_CALC,T.SPO,  T1.MON, SUMMA = ISNULL(T1.SUMMA,0.00) - ISNULL(T2.SUMMA,0.00), 
		--Чтобы не потерять одинаковые суммы за разные месяцы
		 S1 = ISNULL(T1.SUMMA,0.00), S2 = ISNULL(T2.SUMMA,0.00), M1 = T1.MON, M2 = T2.MON
	FROM 
		#SPR_ESN1 T INNER JOIN dbo.months_ex(@YEAR_BEG, @DATE2) M ON 1=1
		LEFT JOIN #SPR_ESN1 T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.DGH = T.DGH AND T1.WAY_CALC = T.WAY_CALC AND isnull(T1.SPO,0) = isnull(T.SPO,0) AND T1.MON = M.M
		LEFT JOIN #SPR_ESN1 T2 ON T2.REF_PHYS_PERS = T.REF_PHYS_PERS AND T2.DGH = T.DGH AND T2.WAY_CALC = T.WAY_CALC AND isnull(T2.SPO,0) = isnull(T.SPO,0) AND T2.MON = M.M - 1
	WHERE
		(ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)) <> 0--> 0
		AND M.Y = YEAR(@DATE2) AND M.M BETWEEN MONTH(@YEAR_BEG) AND MONTH(@DATE2)
	)t
	WHERE EXISTS ( SELECT * FROM @WAY W WHERE W.WAY_CALC = T.WAY_CALC )
	GROUP BY T.REF_PHYS_PERS, T.DGH, T.WAY_CALC, T.SPO, T.MON

---
	CREATE TABLE #T2 (REF_PHYS_PERS INT, DGH INT, MONTH_BASE TINYINT, WAY_CALC INT, SUMMA_BASE NUMERIC(18,2) , SPO INT)
	
	INSERT INTO #T2(REF_PHYS_PERS, DGH, MONTH_BASE, WAY_CALC, SUMMA_BASE , SPO)
	SELECT REF_PHYS_PERS, DGH, MONTH_BASE, WAY_CALC, SUMMA_BASE = SUM(SUMMA_BASE) , SPO  
	FROM #T1
	WHERE MONTH_BASE BETWEEN MONTH(@DATE1) AND MONTH(@DATE2)
	GROUP BY REF_PHYS_PERS, DGH, MONTH_BASE, WAY_CALC, SPO 


	--- Суммы с разбивкой по источникам финансирования
	SELECT LINK_FACE1, DGH, LINK_SFIN1, WAY_NAME = (CASE WHEN ISNULL(SPO,0) >0 
																THEN WAY_NAME + ' - ' + (SELECT CODE FROM  SA_SZV4_SPR  s4 WHERE  s4.link = TT.SPO  AND s4.spr_code = 'SPO_USL_TRUDA') 
														     ELSE  ISNULL(WAY_NAME,'') END),
		WAY_CALC, SPO, SS = SUM(SS), PAY = SUM(PAY), DED = SUM(DED), INV = SUM(INV), TAX = SUM(TAX),
		LIM = CONVERT(NUMERIC(18,2),
							CASE WHEN LINK_SFIN1 = 0 THEN SUM(SUM_LIM)
								ELSE SUM(SUM_LIM) * CASE WHEN SUM(BASE_ALL) > 0 AND SUM(BASE_FIN) > 0 THEN SUM(BASE_FIN) / SUM(BASE_ALL) ELSE 0 END 
							END
					)
	INTO #ESN 	
	FROM
		(
		SELECT  	
			LINK_FACE1 = T2.REF_PHYS_PERS,
			T2.DGH,
			LINK_SFIN1 = T3.LINK_VKR,
			WAY_NAME  = W.NAME,  
			T2.WAY_CALC,
			T2.MONTH_BASE,
			SS = SUM(CASE WHEN T2.WAY_CALC = 2 THEN T2.SUMMA_BASE ELSE 0 END),
	 		[PAY] = SUM(T3.SUMMA_BASE),
	 		[DED] = SUM(T3.DED_M),
	 		[INV] = SUM(T3.INV_M),
	 		SUM_LIM = CASE WHEN T2.DGH = 0 THEN ISNULL(MAX(L.SUMMA),0) 
	 					ELSE SUM( CASE WHEN T2.DGH > 0 AND ISNULL(L.SUMMA,0) > 0 THEN  T3.SUMMA_BASE ELSE  0 END )
	 					END,
	 		BASE_ALL = ISNULL(MAX(T2.SUMMA_BASE),0),
	 		BASE_FIN = ISNULL(SUM(T3.SUMMA_BASE),0),
	 		[TAX] = SUM(T3.SUMMA),	
	 		T2.SPO 	
		FROM 
			#T2 T2 -- доход сгруппирован по физ лицу, виду, договору и месяцу
			INNER JOIN dbo.WAY_CALC W ON W.CODE = T2.WAY_CALC AND W.[TYPE] = 2
			INNER JOIN #T1 T3 ON T2.REF_PHYS_PERS = T3.REF_PHYS_PERS AND T2.DGH = T3.DGH AND T2.MONTH_BASE = T3.MONTH_BASE AND T2.WAY_CALC = T3.WAY_CALC AND ISNULL(T2.SPO,0) = ISNULL(T3.SPO,0)
			LEFT JOIN #SPR_ESN2 L ON L.REF_PHYS_PERS = T2.REF_PHYS_PERS AND T2.DGH = L.DGH AND L.WAY_CALC = T2.WAY_CALC AND ISNULL(L.SPO,0) = ISNULL(T2.SPO,0) AND L.MON = T2.MONTH_BASE
		GROUP BY 
			T2.REF_PHYS_PERS, T2.DGH, T3.LINK_VKR, W.NAME, T2.WAY_CALC , T2.SPO, T2.MONTH_BASE
		) TT
	GROUP BY
		LINK_FACE1, DGH, LINK_SFIN1, WAY_NAME, WAY_CALC, SPO		



IF @SHOW_Data = '1' 
		DELETE FROM #ESN WHERE WAY_CALC IN (10, 11)
IF  @SHOW_Data = '2' 
		DELETE FROM #ESN WHERE WAY_CALC NOT IN (10, 11)
--<<<<<**********************
	--- переворачиваем поля в таблице 

	DECLARE @TABLE_1 VARCHAR(5000),
			@TABLE_2 varchar(5000)
	
	EXEC X_GET_TABLE_NAME @TABLE_1 OUTPUT
	EXEC X_GET_TABLE_NAME @TABLE_2 OUTPUT
	DECLARE @CNT1 INT
	SELECT @CNT1 = COUNT(DISTINCT WAY_NAME ) FROM #ESN 

	EXEC M_CROSS_TABLE
		'LINK_SFIN1, LINK_FACE1, DGH',  
		'WAY_NAME', 'VARCHAR(50)', 
		'SUMMA,PAY,DED,INV,LIM,TAX' , 'NUMERIC(20,2)#NUMERIC(20,2)#NUMERIC(20,2)#NUMERIC(20,2)#NUMERIC(20,2)#NUMERIC(20,2)',  'SUM(ss) AS ss, SUM(PAY) AS PAY, SUM(DED) AS DED, SUM(INV) AS INV, SUM(LIM) AS LIM, SUM(TAX) AS TAX ',
		'#ESN', @TABLE_1
	
	DECLARE @I1 INT, @SQLS1 VARCHAR(8000), @FIELD1 VARCHAR(4000)
	SET @I1=1
	WHILE @I1 <= @CNT1 BEGIN

		SET @FIELD1= 'WAY_NAME_'  +  RTRIM(LTRIM(STR(@I1)))
		SET @SQLS1= ' UPDATE '+@TABLE_1 + '  SET '+@FIELD1+ ' = (SELECT TOP 1 '+@FIELD1+' FROM ' +@TABLE_1 + ' WHERE '+ @FIELD1+ '  IS NOT NULL ) ' 
		
		EXEC (@SQLS1)
		
		SET @FIELD1= 'SUMMA_'  +  RTRIM(LTRIM(STR(@I1)))
		SET @SQLS1= ' UPDATE '+@TABLE_1 + '  SET '+@FIELD1+ ' = 0  WHERE ' + @FIELD1+ '  IS  NULL ' 
		
		EXEC (@SQLS1)

		SET @FIELD1= 'PAY_'  +  RTRIM(LTRIM(STR(@I1)))
		SET @SQLS1= ' UPDATE '+@TABLE_1 + '  SET '+@FIELD1+ ' = 0  WHERE ' + @FIELD1+ '  IS  NULL ' 

		EXEC (@SQLS1)

		SET @FIELD1= 'DED_'  +  RTRIM(LTRIM(STR(@I1)))
		SET @SQLS1= ' UPDATE '+@TABLE_1 + '  SET '+@FIELD1+ ' = 0  WHERE ' + @FIELD1+ '  IS  NULL ' 

		EXEC (@SQLS1)

		SET @FIELD1= 'INV_'  +  RTRIM(LTRIM(STR(@I1)))
		SET @SQLS1= ' UPDATE '+@TABLE_1 + '  SET '+@FIELD1+ ' = 0  WHERE ' + @FIELD1+ '  IS  NULL ' 

		EXEC (@SQLS1)
		
		SET @FIELD1= 'LIM_'  +  RTRIM(LTRIM(STR(@I1)))
		SET @SQLS1= ' UPDATE '+@TABLE_1 + '  SET '+@FIELD1+ ' = 0  WHERE ' + @FIELD1+ '  IS  NULL ' 

		EXEC (@SQLS1)				

		SET @FIELD1= 'TAX_'  +  RTRIM(LTRIM(STR(@I1)))
		SET @SQLS1= ' UPDATE '+@TABLE_1 + '  SET '+@FIELD1+ ' = 0  WHERE ' + @FIELD1+ '  IS  NULL ' 

		EXEC (@SQLS1)
						
		SET @I1=@I1+1
	END	



	-- приведение к нормальному виду и выборка данных из перевернутой  

	DECLARE @SQL NVARCHAR(4000), @ParmDefinition NVARCHAR(500)

	SET @SQL = N'SELECT LINK_SFIN = P.LINK_SFIN,'
	--
	IF @DETAL_SUB = 1
		SET @SQL = @SQL + ' NAME_SUB, CODE_SUB,'
	ELSE
		SET @SQL = @SQL + ' NAME_SUB = '' '', CODE_SUB = '' '','	
	--	
	IF @DETAL_FIO = 1
		/*<code begin> Шорков И.А. 10.10.2011 добавление в первую страницу поля Возрастная группа до 1967 ->1 , с 1967 -> 2  */
		SET @SQL = @SQL	+ ' [LINK_FACE] = P.LINK_PERS, [DGH1] = P.DGH, [TNum] = rtrim(ltrim(P.TAB_NUMER)), [LINK_EMPL] = P.REF_EMPL, [TN] = P.TAB_NUMER, [FIO]= P.NAME_EMPL, [SEX] = P.POL, [BIRTH] = P.YEAR_B,
						    [AGE_TYPE] = (CASE	WHEN P.TYPE1 = 1 THEN 1
												WHEN P.TYPE1 = 2 THEN 1
												WHEN P.TYPE1 = 3 THEN 2
										    ELSE 0
										  END),'
		/*<code end> Шорков И.А.  */							  
	ELSE
		SET @SQL = @SQL	+ ' [LINK_FACE] = 0, [LINK_EMPL] = 0, [TNUM] = 0, [TN] = '''', [FIO]= '''', [SEX] = 0, [BIRTH] = '''',[AGE_TYPE] = '''','

	IF @DETAL_SOURCE = 1
		SET @SQL = @SQL + ' [NAME_VKR] = F.CODE,'
	ELSE
		SET @SQL = @SQL + ' [NAME_VKR] = '' '','
		
	IF @CNT1 = 0 BEGIN
		SET @SQL =  @SQL + ' WAY_NAME_0 = '' '', SUMMA_0 = 0, PAY_0 =0, DED_0 =0, INV_0 = 0, LIM_0 =0, TAX_0 = 0,'
	END		
	--
	
		
	--
	SET @SQL = @SQL
			+ '
			O.*,
			SUMMA = (select sum(isnull(summa,0))			
			from  #FACT_SUMMA where P.LINK_PERS = LINK_PERS AND P.DGH = DGH AND LINK_SFIN = P.LINK_SFIN)
		into '+ @TABLE_2 +'	
		FROM
			#PERS_INFO P
			LEFT JOIN dbo.SAL_SFIN F ON F.LINK = P.LINK_SFIN
			LEFT JOIN ' + @TABLE_1 + ' O ON  O.LINK_FACE1 = P.LINK_PERS AND o.LINK_SFIN1 = P.LINK_SFIN  and o.dgh = p.dgh
			/*LEFT JOIN #ESN E ON O.LINK_FACE = E.LINK_FACE  AND O.LINK_SFIN = E.LINK_SFIN AND P.DGH = E.DGH*/
			--LEFT JOIN #FACT_SUMMA FS ON P.LINK_PERS = FS.LINK_PERS AND P.DGH = FS.DGH AND FS.LINK_SFIN = P.LINK_SFIN
		WHERE
			(@pCHECK1 = 1 AND TYPE1 = 1) OR (@pCHECK2 = 1 AND TYPE1 = 2) OR (@pCHECK3 = 1 AND  TYPE1 = 3)				
		GROUP BY
			'

	SET @SQL = @SQL + ' P.LINK_SFIN, F.CODE, o.LINK_SFIN1'
	
	SET @I1=1
	WHILE @I1 <= @CNT1 BEGIN
		
		SET @FIELD1 = 'o.WAY_NAME_' + RTRIM(LTRIM(STR(@I1)))
		SET @SQL = @SQL + ',' + @FIELD1	
		
		SET @FIELD1 = 'o.SUMMA_' + RTRIM(LTRIM(STR(@I1)))
		SET @SQL = @SQL + ',' + @FIELD1	

		SET @FIELD1 = 'o.PAY_' + RTRIM(LTRIM(STR(@I1)))
		SET @SQL = @SQL + ',' + @FIELD1	
		
		SET @FIELD1 = 'o.DED_' + RTRIM(LTRIM(STR(@I1)))
		SET @SQL = @SQL+ ',' + @FIELD1	
		
		SET @FIELD1 = 'o.INV_' + RTRIM(LTRIM(STR(@I1)))
		SET @SQL = @SQL + ',' + @FIELD1	
		
		SET @FIELD1 = 'o.LIM_' + RTRIM(LTRIM(STR(@I1)))
		SET @SQL = @SQL + ',' + @FIELD1	
		
		SET @FIELD1 = 'o.TAX_' + RTRIM(LTRIM(STR(@I1)))
		SET @SQL = @SQL + ',' + @FIELD1	
	
		
	SET @I1=@I1+1
	END	
	

	IF @DETAL_SUB = 1
		SET @SQL = @SQL + ' ,NAME_SUB, CODE_SUB'

	SET @SQL = @SQL + ' ,P.LINK_PERS, p.DGH   , O.LINK_FACE1 , o.DGH '
	
	IF @DETAL_FIO = 1
		/*<code begin>  Шорков И.А. 10.10.2011 добавление в первую страницу поля Возрастная группа , добавление в группировку  */
		SET @SQL = @SQL	+ ' , P.REF_EMPL ,  P.TAB_NUMER, P.NAME_EMPL, P.POL, P.YEAR_B, P.TYPE1/*, O.LINK_FACE1*/  '
		/* <coide end> Шорков И.А.*/

	SET @SQL = @SQL
			+ '
		ORDER BY 
			' 
	+ CASE @ORDERBY 
		WHEN 1 THEN 'SUMMA'
		WHEN 2 then ' TNum '
		WHEN 3 then 'FIO'
		ELSE 'NAME_SUB'
	END
	+ CASE WHEN @DETAL_SOURCE = 1 THEN ',F.CODE' ELSE '' END	

	PRINT   (@SQL)

	SET @ParmDefinition	= N'@pCHECK1 TINYINT, @pCHECK2 TINYINT, @pCHECK3 TINYINT'

	EXECUTE sp_executesql @SQL, @ParmDefinition, @pCHECK1 = @CHECK1, @pCHECK2 = @CHECK2, @pCHECK3 = @CHECK3


	SET @I1=1
	WHILE @I1 <= @CNT1 BEGIN
	
		SET @FIELD1= 'WAY_NAME_'  +  RTRIM(LTRIM(STR(@I1)))
		
		SET @SQLS1= ' UPDATE '+@TABLE_2 + '  SET '+@FIELD1+ ' = (SELECT TOP 1 '+@FIELD1+' FROM ' +@TABLE_2 + ' WHERE '+ @FIELD1+ '  IS NOT NULL ) ' 
		EXEC (@SQLS1)	
	SET @I1=@I1+1
	END		
	
	exec (' SELECT * FROM  ' + @TABLE_2 )

	DROP TABLE #T1
	DROP TABLE #PERS_INFO
	DROP TABLE #ESN
	DROP TABLE #FACT_SUMMA
	
	DECLARE @TABLE VARCHAR(100)
	EXEC X_GET_TABLE_NAME @TABLE OUTPUT
	DECLARE @CNT INT
	SELECT @CNT = COUNT(DISTINCT WAY_NAME) FROM #CALC_OPER_W

	
	EXEC M_CROSS_TABLE
		'PERS_LINK, LINK_PAYS, LINK_VKR, Y, M', 
		'WAY_NAME', 'VARCHAR(50)', 
		'SUMMA', 'NUMERIC(20,2)', 'SUM(SUMMA) AS SUMMA',
		'#CALC_OPER_W', @TABLE

	DECLARE @I INT, @SQLS VARCHAR(4000), @FIELD VARCHAR(100)
	SET @I=1
	WHILE @I <= @CNT BEGIN

		SET @FIELD= 'WAY_NAME_'  +  RTRIM(LTRIM(STR(@I)))
		SET @SQLS= ' UPDATE '+@TABLE + '  SET '+@FIELD+ ' = (SELECT TOP 1 '+@FIELD+' FROM ' +@TABLE + ' WHERE '+ @FIELD+ '  IS NOT NULL ) ' 

		EXEC (@SQLS)

		SET @FIELD= 'SUMMA_'  +  RTRIM(LTRIM(STR(@I)))
		SET @SQLS= ' UPDATE '+@TABLE + '  SET '+@FIELD+ ' = 0  WHERE ' + @FIELD+ '  IS  NULL ' 

		EXEC (@SQLS)

		SET @I=@I+1
	END			

	/* <coide begin> Шорков И.А. 10.10.2011 добавление во вторую страницу поля Возрастная группа до 1967 ->1 , с 1967 -> 2  */
	EXEC('
	IF EXISTS (SELECT * FROM ' + @TABLE + ')
		SELECT 
			NAME_EMPL = RTRIM(P.FM) + '' '' + SUBSTRING(RTRIM(P.IM),1,1) + ''.'' + SUBSTRING(RTRIM(P.OT),1,1) + ''.'',
			AGE_TYPE =  (CASE WHEN P.SEX = 1 AND YEAR(P.BIRTHDATE)<= 1952 THEN 1
					    WHEN P.SEX = 2 AND YEAR(P.BIRTHDATE)<= 1956 THEN 1
					    WHEN P.SEX = 1 AND (YEAR(P.BIRTHDATE) BETWEEN 1953 AND 1966) THEN 1
					    WHEN P.SEX = 2 AND (YEAR(P.BIRTHDATE) BETWEEN 1957 AND 1966) THEN 1
						WHEN YEAR(P.BIRTHDATE) >= 1967 THEN 2
					    ELSE 0
					END) ,
			BIRTH = P.BIRTHDATE,		
			PN.CODE, PN.NAME, SFIN_CODE = ISNULL(F.CODE,''ВСЕ''),
			O.*
		FROM
			dbo.PERSON P 
			INNER JOIN ' + @TABLE + ' O ON P.LINK = O.PERS_LINK
			INNER JOIN dbo.PAYS PN ON PN.LINK = O.LINK_PAYS
			LEFT JOIN dbo.SAL_SFIN F ON F.LINK = O.LINK_VKR
		ORDER BY 
			NAME_EMPL, Y, M, PN.CODE		
	ELSE		
		SELECT NAME_EMPL= '''', AGE_TYPE = '''', BIRTH = '''', CODE = '''', NAME = '''', SFIN_CODE = '''', PERS_LINK = 0, LINK_PAYS = 0, LINK_VKR = 0, Y = 0, M = 0, WAY_NAME_1  = '''', SUMMA_1 = 0	
	')	
	/* <coide end> Шорков И.А.*/
END






GO


GRANT EXECUTE ON dbo.[KIR_EXEC_SALARY_ESN_REPORT1] TO PUBLIC

GO



GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SD_REP_F417]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_REP_F417]

GO

CREATE  PROCEDURE [dbo].SD_REP_F417
	@varKScYear VARCHAR(254),
	@varKSnLinkEmpl INT,
	@nCheck1 int = 0 ,/* Объединять начисления */
	@nMode int = 0/* 0-По сотрудникам, 1-По ГПХ */
AS 
BEGIN

	DECLARE @varKSnYear INT
	SELECT @varKSnYear = CAST(@varKScYear AS INT)
	DECLARE @varKSnLinkPers INT
	
	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output	

	DECLARE @varKSstart_date DATETIME, 
			@varKSEND_DATE DATETIME

	SELECT @varKSstart_date = dbo.ConvertDMY2Date(1,1,@varKSnYear)
	SELECT @varKSEND_DATE  = dbo.DateEndOfYear(@varKSstart_date)

	DECLARE 
		@varKSCODE_FKR_D VARCHAR(10), @varKSNAME_FKR_D VARCHAR(254),
		@varKSCODE_FKR_T VARCHAR(10), @varKSNAME_FKR_T VARCHAR(254),
		@varKSCODE_FKR_E VARCHAR(10), @varKSNAME_FKR_E VARCHAR(254),
		@varKSDate datetime
		
	IF @nMode = 0 
	BEGIN
		SELECT @varKSnLinkPers = PERS_LINK FROM dbo.EMPL WHERE LINK = @varKSnLinkEmpl

		SELECT TOP 1
			@varKSCODE_FKR_D = CODE_FKR_D, @varKSNAME_FKR_D = NAME_FKR_D,
			@varKSCODE_FKR_T = CODE_FKR_T, @varKSNAME_FKR_T = NAME_FKR_T,
			@varKSCODE_FKR_E = CODE_FKR_E, @varKSNAME_FKR_E = NAME_FKR_E,
			@varKSDate = dpe.date_begin
		FROM 
			dbo.BI_DICTION_VKR VKR 
			INNER JOIN dbo.SAL_SFIN F ON F.KBK = VKR.LINK		
			INNER JOIN dbo.DICTIONARY_PAYS_EMPL_FN(@varKSEND_DATE,@varKSnLinkEmpl,0,DEFAULT,@DEP_LINK,1) DPE ON DPE.LINK_KBK = F.LINK
		WHERE 
			DPE.DATE_BEGIN <= @varKSEND_DATE  
		ORDER BY 
			DPE.DATE_BEGIN DESC


		CREATE TABLE #PART1(SUBDIV VARCHAR(254),FIO VARCHAR(254),TAB_NUM VARCHAR(15),
							BIRTH DATETIME, KATEG VARCHAR(254), OBR VARCHAR(254), 
							ZV_STEP VARCHAR(254), EXPIR VARCHAR(40), 
							OSN_OKL NUMERIC(20,2), CHILDREN INT, IZHD INT, INV VARCHAR(20), PENS_DATE datetime)

		INSERT INTO #PART1
		SELECT TOP 1
			[SUBDIV]  = EP.SUBDIV_NAME,
			[FIO] 	  = RTRIM(P.FM) + ' ' + RTRIM(P.IM) + ' ' + RTRIM(P.OT),
			[tab_num] = EP.TAB,
			[BIRTH]   = P.BIRTHDATE,
			[KATEG]   = '',
			[OBR] 	  = (SELECT NAME FROM EDUCTYPE WHERE LINK =  PE.EDUC_LINK),
			[ZV_STEP] = RTRIM(ISNULL((SELECT NAME FROM dbo.ACAD_STATUS WHERE LINK = P.ACAD_STATUS_LINK),'')) + ' ' 
						+ RTRIM(ISNULL((SELECT NAME FROM dbo.ACAD_DEGREE WHERE LINK = P.ACAD_DEGREE_LINK),'')),
			[EXPIR]   = '',
			[OSN_OKL] = (SELECT OKLAD FROM dbo.SALARY_OKLAD(@varKSEND_DATE,@varKSnLinkEmpl, DEFAULT, @DEP_LINK)),
			[CHILDREN] = (SELECT COUNT(*) FROM dbo.KU_PERS_FAMILY F WHERE 
										F.PERS_LINK = EP.PERS_LINK AND YEAR(F.[BIRTHDATE]) <= @varKSnYear
										AND FAMILY_NAME IN ('Сын','Дочь')),
			[IZHD] = (SELECT COUNT(*) FROM dbo.PERS_FAMILY F WHERE 
										F.PERS_LINK = EP.PERS_LINK  AND IZHD = 1 AND @varKSnYear BETWEEN YEAR(F.[IZHD_BEG]) AND ISNULL(YEAR(F.[IZHD_END]),@varKSnYear)),
			[INV] = (SELECT TOP 1 LTRIM(RTRIM(PV.GROUP_NAME)) FROM dbo.KU_PERS_INVALID PV
					 WHERE PV.PERS_LINK = P.LINK AND @varKSEND_DATE BETWEEN DATE_BEGIN AND ISNULL(DATE_END,@varKSEND_DATE)),
			[PENS_DATE] = (SELECT TOP 1 K.DATE_PENS FROM dbo.KJ_PERS_PENSION K WHERE K.PERS_LINK = P.LINK)
		FROM 
			dbo.SD_EMPL_FN(@varKSnLinkEmpl, @varKSEND_DATE, DEFAULT, @DEP_LINK) EP  
			INNER JOIN dbo.PERSON P ON (EP.PERS_LINK = P.LINK)
			LEFT OUTER JOIN dbo.KU_PERS_EDUCATION PE ON (P.LINK = PE.PERS_LINK
					 and (SATISFY = (case when exists (select * from  KU_PERS_EDUCATION where pers_link = P.LINK and SATISFY = 1)
				then  1
				else 0
				end)
				and pe.educ_code = (case when SATISFY = 0 
				then 	 (select max(educ_code) from  KU_PERS_EDUCATION where pers_link = P.LINK)
				else (select max(educ_code) from  KU_PERS_EDUCATION where pers_link = P.LINK and SATISFY = 1)
				end		)))
	
					

		--Вычисление категории
		DECLARE @varKSKATEG VARCHAR(4000), @varKSTMP_STR VARCHAR(254)
		SET @varKSKATEG = ''
		DECLARE #KAT_CURSOR CURSOR LOCAL FAST_FORWARD FOR

		SELECT TOP 1 ISNULL(QUALIFY, '') 
		FROM dbo.KU_PERS_EDUCATION PE
		WHERE PERS_LINK = @varKSnLinkPers AND YEAR(DATE_END) <= @varKSnYear
		ORDER BY SATISFY DESC
		
		OPEN #KAT_CURSOR
		FETCH #KAT_CURSOR INTO @varKSTMP_STR
		WHILE @@FETCH_STATUS = 0 BEGIN
			SET @varKSKATEG = @varKSKATEG + ' ' + RTRIM(@varKSTMP_STR)
			FETCH #KAT_CURSOR INTO @varKSTMP_STR
		END
		CLOSE #KAT_CURSOR
		DEALLOCATE #KAT_CURSOR

		UPDATE #PART1 SET KATEG = LTRIM(RTRIM(@varKSKATEG))

		--	
		declare @varKSdays int, @varKSmonths int, @varKSyears int, @varKScDate varchar(10)
		SELECT @varKSyears = years, @varKSmonths = months, @varKSdays = days from dbo.ku_EmplExpirTable(@varKSnLinkEmpl,@varKSEND_DATE, DEFAULT) ET WHERE ET.EXPIR_CODE = 'GEN'  

		UPDATE #PART1 SET EXPIR = 
			RTRIM(LTRIM(CAST (@varKSyears AS VARCHAR(4) ))) + ' лет '
			+ RTRIM(LTRIM(CAST (@varKSmonths AS VARCHAR(2) ))) + ' месяцев '
			+ RTRIM(LTRIM(CAST (@varKSdays AS VARCHAR(2) ))) + ' дней '

		CREATE TABLE #DPE (LINK_EMPL INT, LINK_PAYS INT, ORDER_DATE DATETIME, DATE_BEGIN DATETIME, DATE_END DATETIME, VALUE NUMERIC(18,4))

		INSERT INTO #DPE (LINK_EMPL, LINK_PAYS, ORDER_DATE, DATE_BEGIN, DATE_END, VALUE)
		SELECT LINK_EMPL, LINK_PAYS, ORDER_DATE, DATE_BEGIN, DATE_END, VALUE 
		FROM dbo.DICTIONARY_PAYS_EMPL_FN(DEFAULT,@varKSnLinkEmpl,0,DEFAULT,DEFAULT,DEFAULT)

		CREATE TABLE #PAYS_EMPL(
			LINK_PAY INT, cp varchar(10), NP VARCHAR(254), 
			date_begin datetime, date_end datetime,
			s numeric(20,2), parent_id int
		)


		-- На начало года по стортуднику
		INSERT INTO #PAYS_EMPL
		SELECT 
			ISNULL(P1.LINK,P.LINK), ISNULL(P1.CODE,P.CODE), ISNULL(P1.NAME,P.NAME), ISNULL(DPE.ORDER_DATE,DPE.DATE_BEGIN), NULL, VALUE, 0
		FROM 
			#DPE DPE
			INNER JOIN dbo.PAYS P ON P.LINK = DPE.LINK_PAYS
			LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1 
		WHERE 
			LINK_EMPL = @varKSnLinkEmpl
			AND @varKSstart_date - 1 BETWEEN DPE.DATE_BEGIN AND ISNULL(DATE_END, '30000101')
			AND VALUE > 0
		
		-- Изменения в выбранном году
		INSERT INTO #PAYS_EMPL
		SELECT 
			ISNULL(P1.LINK,P.LINK), ISNULL(P1.CODE,P.CODE), ISNULL(P1.NAME,P.NAME), 
			ISNULL(DPE.ORDER_DATE,DPE.DATE_BEGIN), 
			DATE_END, VALUE, 0
		FROM 
			#DPE DPE
			INNER JOIN dbo.PAYS P ON P.LINK = DPE.LINK_PAYS
			LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1
		WHERE 
			LINK_EMPL = @varKSnLinkEmpl
			AND YEAR(ISNULL(DPE.ORDER_DATE,DPE.DATE_BEGIN)) = @varKSnYear
			AND ISNULL(DATE_END, '30000101') >= @varKSstart_date
			AND VALUE > 0
			AND NOT EXISTS (SELECT * FROM #PAYS_EMPL PE WHERE PE.LINK_PAY = ISNULL(P1.LINK,P.LINK) AND PE.date_begin = ISNULL(DPE.ORDER_DATE,DPE.DATE_BEGIN))

		-- Прочие действующие сейчас начисления
		INSERT INTO #PAYS_EMPL
		SELECT 
			ISNULL(P1.LINK,P.LINK), ISNULL(P1.CODE,P.CODE), ISNULL(P1.NAME,P.NAME), NULL, NULL, VALUE, 0
		FROM 
			#DPE DPE
			INNER JOIN dbo.PAYS P ON P.LINK = DPE.LINK_PAYS
			LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1
		WHERE 
			LINK_EMPL = @varKSnLinkEmpl
			AND DATE_BEGIN = (Select max(DATE_BEGIN) from dbo.DICTIONARY_PAYS_EMPL_FN(@varKSEND_DATE,@varKSnLinkEmpl,0,DEFAULT,@DEP_LINK,1) DPE1 where DPE1.LINK_EMPL = DPE.LINK_EMPL and DPE1.LINK_PAYS = DPE.LINK_PAYS and DPE1.DATE_BEGIN <= @varKSEND_DATE AND ISNULL(DPE1.DATE_END, '30000101') >= @varKSstart_date) 
			AND ISNULL(DATE_END, '30000101') >= @varKSstart_date
			AND VALUE > 0
			AND NOT EXISTS (SELECT * FROM #PAYS_EMPL PE WHERE PE.LINK_PAY = ISNULL(P1.LINK,P.LINK))

		UPDATE #PAYS_EMPL
		SET DATE_BEGIN = NULL
		WHERE DATE_BEGIN < @varKSstart_date

		UPDATE R
		SET CP = CP + '*', NP = NP + '*'
		FROM
			#PAYS_EMPL R
			INNER JOIN dbo.PAYS P on P.LINK_MPAY = R.LINK_PAY

		CREATE TABLE #TMP2 ( ID INT IDENTITY, ORDER_DATE datetime, ORDER_NUM VARCHAR(30), 
			SUBDIV VARCHAR(254), POST VARCHAR(254), CONDITION VARCHAR(40), 
			KATEG VARCHAR(254), AVANSE NUMERIC(20, 2), REAL_REC BIT
		)
		
		--INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG,
		--	REAL_REC)
		--SELECT TOP 1 DATE, NUMBER, SUBDIVISION_PD, POST_PD, '', '', 1
		--FROM DICTIONARY_PURP_DISP_FACES 
		--WHERE EMPL_LINK = @varKSnLinkEmpl AND YEAR(DATE_PD) < @varKSnYear
		--ORDER BY DATE_PD DESC

		CREATE TABLE #STAFF_INFO(LINK_UP INT, SUBDIV_NAME VARCHAR(254), POST_NAME VARCHAR(254), DATE_BEGIN DATETIME, DATE_END DATETIME)
		INSERT INTO #STAFF_INFO(LINK_UP, SUBDIV_NAME, POST_NAME, DATE_BEGIN, DATE_END)
		SELECT 
			S.LINK_UP, 
			(SELECT TOP 1 [name] FROM subdiv WHERE link_up = s.subdiv_link and (s.date_begin between date_begin and date_end or s.date_begin < date_begin and s.date_end > date_end or s.date_end between date_begin and date_end)),
			DP.NAME,
			S.DATE_BEGIN, 
			S.DATE_END
		FROM 
			DBO.STAFF_HEAD SH
			INNER JOIN dbo.staff s ON s.link_up=sh.link
			LEFT OUTER JOIN dbo.POST DP ON DP.LINK = s.post_link
			
		--Приказы о приёме и переводе
		---------------------------
		-- Прием
		INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG, REAL_REC)
		SELECT 
			o.[DATE], o.NUMBER, 'ПРИНЯТ(А) ' + CONVERT(VARCHAR(10),im.DATE_BEGIN,104), S.POST_NAME, '', '', 1 /*#3584 Шорков И.А. добавление даты приема*/
		FROM 
			ITEM_MOVE im 
			INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE = 1
			LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
			
		WHERE 
			im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) <= @varKSnYear	 /* #3584 Шорков И.А. приказ о приеме работника может быть не только за выбранный год */
		ORDER BY 
			IM.DATE_BEGIN DESC
		---
		INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG,REAL_REC)
		SELECT NULL, NULL, NULL, NULL, '', '', 1
		WHERE EXISTS (
			SELECT * FROM #DPE DPE WHERE LINK_EMPL = @varKSnLinkEmpl
					AND @varKSstart_date-1 BETWEEN DPE.DATE_BEGIN AND ISNULL(DATE_END, '30000101')
					AND VALUE > 0	
			)		

		---		

		--Перевод
		INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG, REAL_REC)
		SELECT 
			o.[DATE], o.NUMBER, 
			case when ORD.obj_code = 'MOVES' then 'ПЕРЕВЕДЕН(А) ' + CONVERT(VARCHAR(10),im.DATE_BEGIN,104)
				 else ORD.type_txt + ' ' + CONVERT(VARCHAR(10),im.DATE_BEGIN,104) end	, 
			S.POST_NAME, '', '', 1 /*#3584 Шорков И.А. добавление даты приема*/
		FROM 
			ITEM_MOVE im 
			INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE not in(2,1)
			inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
			LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
			
		WHERE 
			im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear	 /* #3584 Шорков И.А. приказ о приеме работника может быть не только за выбранный год */
		
		union 
	 		SELECT DISTINCT DATE_BEGIN, null, '','','','',1
			FROM #PAYS_EMPL
			WHERE 
			DATE_BEGIN NOT IN (SELECT ISNULL(O.[DATE],'18000101') FROM ITEM_MOVE im 
								INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE not in(2,1)
								inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
								LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
									WHERE 
								im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear)
			AND ( DATE_BEGIN >= ISNULL((SELECT MIN(O.[DATE]) FROM ITEM_MOVE im 
								INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE not in(2,1)
								inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
								LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
									WHERE 
								im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear), '18000101')
			OR ISNULL(DATE_END,'18000101') < ISNULL((SELECT MIN(O.[DATE]) FROM ITEM_MOVE im 
								INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE not in(2,1)
								inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
								LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
									WHERE 
								im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear), '18000101')		
			)								



		/*ORDER BY 
			DATE_BEGIN ASC*/

		-----------------------------
			
		-- Приказы об увольнении
		DECLARE @DICTIONARY_PUV INT
		SET @DICTIONARY_PUV = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS WHERE CODE = 'DICTIONARY_PUV')

		INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG, REAL_REC)
		SELECT 
			o.[DATE], o.NUMBER, 'УВОЛЕН(А) ' + CONVERT(VARCHAR(10),DIS_DATE,104), LEFT(D.NAME,254), '', '', 1
		FROM 
			dbo.ITEM_DIS_FACE DF
			INNER JOIN dbo.ORDERS O ON DF.ORDER_LINK=o.LINK and DF.active=1
			INNER JOIN dbo.DICTION D ON D.LINK = DF.REASON
		WHERE 
			DF.EMPL_LINK = @varKSnLinkEmpl AND YEAR(DF.DIS_DATE) = @varKSnYear	
		ORDER BY 
			DF.DIS_DATE DESC		
			
		DECLARE @varKSDATE_MIN DATETIME, @varKSADVANCE NUMERIC(20, 2)

		SELECT @varKSADVANCE = OKL.OKLAD * ISNULL(AVANCE, 0) / 100.0 
		FROM EMPL E,dbo.salary_oklad(@varKSEND_DATE, @varKSnLinkEmpl, DEFAULT, @DEP_LINK) OKL  
		WHERE OKL.LINK_EMPL = @varKSnLinkEmpl AND E.LINK = OKL.LINK_EMPL 

		SET @varKSDATE_MIN = ISNULL((SELECT MIN(ORDER_DATE) FROM #TMP2), '18000101')


		/*INSERT INTO #TMP2(ORDER_DATE, REAL_REC)
		SELECT DISTINCT DATE_BEGIN, 1
		FROM #PAYS_EMPL
		WHERE 
			DATE_BEGIN NOT IN (SELECT ISNULL(ORDER_DATE,'18000101') FROM #TMP2)
			AND DATE_BEGIN >= @varKSDATE_MIN
		*/
		
		
		DECLARE #TMP_CUR CURSOR LOCAL FAST_FORWARD FOR 
			SELECT ID, ORDER_DATE
			FROM #TMP2
			ORDER BY ORDER_DATE DESC
		DECLARE @varKSID INT, @varKSORDER_DATE DATETIME
		
		OPEN #TMP_CUR
		FETCH #TMP_CUR INTO @varKSID, @varKSORDER_DATE
		WHILE @@FETCH_STATUS = 0 BEGIN
			
			UPDATE #PAYS_EMPL
			SET PARENT_ID = @varKSID 
			WHERE 
				PARENT_ID = 0 
				AND DATE_BEGIN >= @varKSORDER_DATE
			FETCH #TMP_CUR INTO @varKSID, @varKSORDER_DATE
		END
		CLOSE #TMP_CUR
		DEALLOCATE #TMP_CUR
		
		UPDATE #PAYS_EMPL
		SET PARENT_ID = @varKSID 
		WHERE 
			PARENT_ID = 0 


		UPDATE #TMP2 SET AVANSE = @varKSADVANCE WHERE ORDER_DATE = @varKSDATE_MIN
		DECLARE @varKSPAYS_EMPL VARCHAR(100), @varKSTMP2 VARCHAR(120)
		EXEC X_GET_TABLE_NAME @varKSPAYS_EMPL OUTPUT
		SET @varKSTMP2 = @varKSPAYS_EMPL + '_1'

		EXEC M_CROSS_TABLE 
			'PARENT_ID',
			'CP, NP',
			'VARCHAR(10)#VARCHAR(254)',
			'S',
			'NUMERIC(20,2)',
			'SUM(S) AS S',
			'#PAYS_EMPL',
			@varKSPAYS_EMPL


		INSERT INTO #TMP2(REAL_REC) VALUES(0)
		INSERT INTO #TMP2(REAL_REC) VALUES(0)
		INSERT INTO #TMP2(REAL_REC) VALUES(0)
		INSERT INTO #TMP2(REAL_REC) VALUES(0)
		INSERT INTO #TMP2(REAL_REC) VALUES(0)
		INSERT INTO #TMP2(REAL_REC) VALUES(0)

		CREATE TABLE #TMP_3 ( ID INT IDENTITY,
			ORD_DATE DATETIME,	ORD_NUM VARCHAR(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, 'отработано дней', '',
			M1 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 1 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M2 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 2 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M3 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 3 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M4 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 4 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M5 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 5 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M6 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 6 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M7 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 7 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M8 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 8 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M9 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 9 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M10 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 10 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M11 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 11 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M12 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 12 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END )
		FROM	
			(
			SELECT DISTINCT LINK_EMPL, J.PERIOD_BEGIN, J.PERIOD_END
			from 
				dbo.WAY_CALC W
				INNER JOIN dbo.PAYS P ON P.WAY_CALC = W.CODE
				INNER JOIN dbo.CALCULATE_JURNAL J ON P.LINK = J.LINK_PAYS
			where 
				W.[TYPE] = 1 AND W.[OKLAD] = 1
				AND P.[OBJECT] = 1
				AND J.LINK_EMPL = @varKSnLinkEmpl and YEAR(J.PERIOD_BEGIN) = @varKSnYear
			) T	


		insert into #PART2 
		select 2, 'всего начислено', '',
			sum(case when month_begin = 1 then summa else 0 end),
			sum(case when month_begin = 2 then summa else 0 end),
			sum(case when month_begin = 3 then summa else 0 end),
			sum(case when month_begin = 4 then summa else 0 end),
			sum(case when month_begin = 5 then summa else 0 end),
			sum(case when month_begin = 6 then summa else 0 end),
			sum(case when month_begin = 7 then summa else 0 end),
			sum(case when month_begin = 8 then summa else 0 end),
			sum(case when month_begin = 9 then summa else 0 end),
			sum(case when month_begin = 10 then summa else 0 end),
			sum(case when month_begin = 11 then summa else 0 end),
			sum(case when month_begin = 12 then summa else 0 end)
		from s_j_c where link_empl = @varKSnLinkEmpl and year_begin = @varKSnYear
			and typ_oper = 1


		
		insert into #PART2 
		select 4, 'всего удержано', '',
			sum(case when month_begin = 1 then summa else 0 end),
			sum(case when month_begin = 2 then summa else 0 end),
			sum(case when month_begin = 3 then summa else 0 end),
			sum(case when month_begin = 4 then summa else 0 end),
			sum(case when month_begin = 5 then summa else 0 end),
			sum(case when month_begin = 6 then summa else 0 end),
			sum(case when month_begin = 7 then summa else 0 end),
			sum(case when month_begin = 8 then summa else 0 end),
			sum(case when month_begin = 9 then summa else 0 end),
			sum(case when month_begin = 10 then summa else 0 end),
			sum(case when month_begin = 11 then summa else 0 end),
			sum(case when month_begin = 12 then summa else 0 end)
		from s_j_c where link_empl = @varKSnLinkEmpl and year_begin = @varKSnYear
			and typ_oper = 2 
			and link_doc not in (
				select link from documents_ded_pr 
				where year_base = @varKSnYear

					and flag_jc = 1
					and TYP_PAYMENT = 1
			)



	-----Начисленные суммы
		CREATE TABLE #SJ (typ_oper TINYINT , month_begin TINYINT, LINK_PAYS INT, NAME_PAYS VARCHAR(254), CODE_PAYS  varchar(10), SUMMA NUMERIC(18,2))
		INSERT INTO #SJ (typ_oper, month_begin, LINK_PAYS, NAME_PAYS, CODE_PAYS, SUMMA)
		SELECT P.[OBJECT], MONTH(J.PERIOD_BEGIN), ISNULL(P1.LINK,P.LINK), ISNULL(P1.NAME,P.NAME), ISNULL(P1.CODE,P.CODE), SUMMA
		from 
			dbo.CALCULATE_JURNAL J
			INNER JOIN dbo.PAYS P ON P.LINK = J.LINK_PAYS
			LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1
		where 
			link_empl = @varKSnLinkEmpl 
			and YEAR(J.PERIOD_BEGIN) = @varKSnYear
			and P.[OBJECT] in(1, 2)
			and link_doc not in (
				select link from documents_ded_pr 
				where year_base = @varKSnYear
					and flag_jc = 1
					and TYP_PAYMENT = 1
			)
		--
		UPDATE R
		SET NAME_PAYS = NAME_PAYS + '*', CODE_PAYS = CODE_PAYS + '*'
		FROM
			#SJ R
			INNER JOIN dbo.PAYS P on P.LINK_MPAY = R.LINK_PAYS
		--	
		insert into #PART2 
		select 
			case when typ_oper = 1 then 3 else 5 end, 
			name_pays, code_pays,
			sum(case when month_begin = 1 then summa else 0 end),
			sum(case when month_begin = 2 then summa else 0 end),
			sum(case when month_begin = 3 then summa else 0 end),
			sum(case when month_begin = 4 then summa else 0 end),
			sum(case when month_begin = 5 then summa else 0 end),
			sum(case when month_begin = 6 then summa else 0 end),
			sum(case when month_begin = 7 then summa else 0 end),
			sum(case when month_begin = 8 then summa else 0 end),
			sum(case when month_begin = 9 then summa else 0 end),
			sum(case when month_begin = 10 then summa else 0 end),
			sum(case when month_begin = 11 then summa else 0 end),
			sum(case when month_begin = 12 then summa else 0 end)
		from #SJ
		group by 
			case when typ_oper = 1 then 3 else 5 end, 
			name_pays, code_pays


		insert into #PART2 
		select 6, 'сумма к выдаче', '',
			sum(case when month_base = 1 then d1.summa else 0.00 end),
			sum(case when month_base = 2 then d1.summa else 0.00 end),
			sum(case when month_base = 3 then d1.summa else 0.00 end),
			sum(case when month_base = 4 then d1.summa else 0.00 end),
			sum(case when month_base = 5 then d1.summa else 0.00 end),
			sum(case when month_base = 6 then d1.summa else 0.00 end),
			sum(case when month_base = 7 then d1.summa else 0.00 end),
			sum(case when month_base = 8 then d1.summa else 0.00 end),
			sum(case when month_base = 9 then d1.summa else 0.00 end),
			sum(case when month_base = 10 then d1.summa else 0.00 end),
			sum(case when month_base = 11 then d1.summa else 0.00 end),
			sum(case when month_base = 12 then d1.summa else 0.00 end)
		from documents_ded_pr d inner join DOCUMENTS_DED_PR_TABLE d1
			on (d.link = d1.link and d1.REF_Empl = @varKSnLinkEmpl 
				and year_base = @varKSnYear
				and flag_jc = 1
				and TYP_PAYMENT = 1)




		SELECT *,
			@varKSCODE_FKR_D AS CODE_FKR_D, @varKSNAME_FKR_D AS NAME_FKR_D,
			@varKSCODE_FKR_T AS CODE_FKR_T, @varKSNAME_FKR_T AS NAME_FKR_T,
			@varKSCODE_FKR_E AS CODE_FKR_E, @varKSNAME_FKR_E AS NAME_FKR_E
		FROM #PART1

		EXEC ('
			SELECT * 
			INTO ' + @varKSTMP2 + ' 
			FROM #TMP2 T2 LEFT OUTER JOIN ' + @varKSPAYS_EMPL + ' PE
			ON T2.ID = PE.PARENT_ID
		')	
	 
		DECLARE @varKSCNT_PAYS INT, @varKSFIELD_NAME VARCHAR(254), @varKSSQL_STR VARCHAR(8000), @varKSI INT
		SELECT @varKSCNT_PAYS = COUNT(DISTINCT CP) FROM #PAYS_EMPL
		SET @varKSI=1
		WHILE @varKSI <= @varKSCNT_PAYS BEGIN
			SET @varKSFIELD_NAME = 'CP_' + RTRIM(LTRIM(STR(@varKSI))) 
			SET @varKSSQL_STR= ' UPDATE ' + @varKSTMP2 + '  SET '+@varKSFIELD_NAME+ ' = (SELECT TOP 1 '+@varKSFIELD_NAME + ' FROM ' + @varKSPAYS_EMPL + ' WHERE '+
				@varKSFIELD_NAME+ '  IS NOT NULL ) ' 
			EXEC (@varKSSQL_STR)
			SET @varKSFIELD_NAME= 'NP_'  +  RTRIM(LTRIM(STR(@varKSI)))  + '_'  +  RTRIM(LTRIM(STR(@varKSI))) 
			SET @varKSSQL_STR= ' UPDATE ' + @varKSTMP2 + '  SET '+@varKSFIELD_NAME+ ' = (SELECT TOP 1 '+@varKSFIELD_NAME + ' FROM ' + @varKSPAYS_EMPL + ' WHERE '+
				@varKSFIELD_NAME+ '  IS NOT NULL ) ' 
			EXEC (@varKSSQL_STR)
			SET @varKSFIELD_NAME= 'S_'  +  RTRIM(LTRIM(STR(@varKSI)))  + '_'  +  RTRIM(LTRIM(STR(@varKSI))) 
			SET @varKSSQL_STR= ' UPDATE '+@varKSTMP2 + '  SET '+@varKSFIELD_NAME+ ' = 0  WHERE ' +
				@varKSFIELD_NAME+ '  IS  NULL ' 

			SET @varKSI=@varKSI+1
		END

		IF @varKSCNT_PAYS >= 1 AND @varKSCNT_PAYS < 9  BEGIN
			SET @varKSDELTA = 9 - @varKSCNT_PAYS
			SET @varKSI = 1
			WHILE @varKSI <= @varKSDELTA BEGIN
				SET @varKSSQL_STR= 'ALTER TABLE '  + @varKSTMP2 + 
				'  ADD CP_' + LTRIM(STR(@varKSCNT_PAYS + @varKSI)) + '  VARCHAR(10), 
				NP_' + LTRIM(STR(@varKSCNT_PAYS + @varKSI)) + '_' + LTRIM(STR(@varKSCNT_PAYS + @varKSI)) + ' VARCHAR(254), 
				S_' + LTRIM(STR(@varKSCNT_PAYS + @varKSI)) + '_' + LTRIM(STR(@varKSCNT_PAYS + @varKSI)) + '  NUMERIC(20,2) '
				EXEC (@varKSSQL_STR)
				SET @varKSI=@varKSI+1
			END
		END

		IF @varKSCNT_PAYS = 0 BEGIN
			SET @varKSSQL_STR= 
				'ALTER TABLE '  + @varKSTMP2 + 
				'  ADD CP_0  VARCHAR(10), 
				NP_0_0 VARCHAR(254), 
				S_0_0  NUMERIC(20,2) '
				EXEC (@varKSSQL_STR)
		END


		EXEC( 'SELECT *, ITOGOZP = NULL 
		FROM ' + @varKSTMP2 + ' ORDER  by ID, REAL_REC DESC, ORDER_DATE ASC')
	/*
		EXEC( 'SELECT *, ITOGOZP = (SELECT SUM(S) FROM #PAYS_EMPL WHERE ORDER_DATE BETWEEN DATE_BEGIN AND COALESCE(DATE_END,''29990101'')) 
		FROM ' + @varKSTMP2 + ' ORDER BY REAL_REC DESC, ORDER_DATE ASC')
	*/
		SELECT * 
		FROM #TMP_3 INNER JOIN #TMP_DED ON #TMP_3.ID = #TMP_DED.ID
		ORDER BY #TMP_3.REAL_REC DESC, ORD_DATE

		select * from #part2
		order by mode, code


		EXEC ('DROP TABLE ' + @varKSPAYS_EMPL )
		EXEC ('DROP TABLE ' + @varKSTMP2 )
	END 
	ELSE BEGIN
	----------------------------------------------------------------------------
	------ПО ДОГОВОРНИКАМ			---------------------------------------------
	----------------------------------------------------------------------------

		SET @varKSnLinkPers = @varKSnLinkEmpl
			
		select @varKSCODE_FKR_D = CODE_FKR_D, @varKSNAME_FKR_D = NAME_FKR_D,
			@varKSCODE_FKR_T = CODE_FKR_T, @varKSNAME_FKR_T = NAME_FKR_T,
			@varKSCODE_FKR_E = CODE_FKR_E, @varKSNAME_FKR_E = NAME_FKR_E,
			@varKSDate = G.period
		from 	
			DOCUMENTS_DGH G INNER JOIN DOCUMENTS_DGH_T1 GT ON G.LINK = GT.LINK 
			inner join PERSON P on GT.PERS_LINK = P.link
			inner join dbo.SAL_SFIN F on F.LINK = GT.LINK_VKR
			inner join BI_DICTION_VKR VKR ON F.KBK = VKR.LINK
		WHERE 
			FLAG_jc = 1
			and G.PERIOD <= @varKSEND_DATE
			AND G.PERIOD >= @varKSstart_date
			AND g.link_dep = @DEP_LINK
			AND (P.link = @varKSnLinkPers OR @varKSnLinkPers = 0)	
		ORDER BY 
			G.PERIOD DESC


		CREATE TABLE #PART1_P(SUBDIV VARCHAR(254),FIO VARCHAR(254),TAB_NUM VARCHAR(15),
							BIRTH DATETIME, KATEG VARCHAR(254), OBR VARCHAR(254), 
							ZV_STEP VARCHAR(254), EXPIR VARCHAR(40), 
							OSN_OKL NUMERIC(20,2), CHILDREN INT, IZHD INT, INV VARCHAR(20), PENS_DATE datetime)

		INSERT INTO #PART1_p
		SELECT TOP 1
			[SUBDIV]  = '',
			[FIO] 	  = RTRIM(P.FM) + ' ' + RTRIM(P.IM) + ' ' + RTRIM(P.OT),
			[tab_num] = '',
			[BIRTH]   = P.BIRTHDATE,
			[KATEG]   = '',
			[OBR] 	  = (SELECT NAME FROM EDUCTYPE WHERE LINK =  PE.EDUC_LINK),
			[ZV_STEP] = RTRIM(ISNULL((SELECT NAME FROM dbo.ACAD_STATUS WHERE LINK = P.ACAD_STATUS_LINK),'')) + ' ' 
						+ RTRIM(ISNULL((SELECT NAME FROM dbo.ACAD_DEGREE WHERE LINK = P.ACAD_DEGREE_LINK),'')),
			[EXPIR]   = '',
			[OSN_OKL] = null,
			[CHILDREN] = (SELECT COUNT(*) FROM dbo.KU_PERS_FAMILY F WHERE 
										F.PERS_LINK = s.PERS_LINK AND YEAR(F.[BIRTHDATE]) <= @varKSnYear
										AND FAMILY_NAME IN ('Сын','Дочь')),
			[IZHD] = (SELECT COUNT(*) FROM dbo.PERS_FAMILY F WHERE 
										F.PERS_LINK = s.PERS_LINK  AND IZHD = 1 AND @varKSnYear BETWEEN YEAR(F.[IZHD_BEG]) AND ISNULL(YEAR(F.[IZHD_END]),@varKSnYear)),
			[INV] = (SELECT TOP 1 LTRIM(RTRIM(PV.GROUP_NAME)) FROM dbo.KU_PERS_INVALID PV
					 WHERE PV.PERS_LINK = P.LINK AND @varKSEND_DATE BETWEEN DATE_BEGIN AND ISNULL(DATE_END,@varKSEND_DATE)),
			[PENS_DATE] = (SELECT TOP 1 K.DATE_PENS FROM dbo.KJ_PERS_PENSION K WHERE K.PERS_LINK = P.LINK)
		FROM 
	 		salary_reestr_dgh s  
	 		inner join PERSON P on s.PERS_LINK = P.link
			LEFT OUTER JOIN dbo.KU_PERS_EDUCATION PE ON (P.LINK = PE.PERS_LINK
					 and (SATISFY = (case when exists (select * from  KU_PERS_EDUCATION where pers_link = P.LINK and SATISFY = 1)
				then  1
				else 0
				end)
				and pe.educ_code = (case when SATISFY = 0 
				then 	 (select max(educ_code) from  KU_PERS_EDUCATION where pers_link = P.LINK)
				else (select max(educ_code) from  KU_PERS_EDUCATION where pers_link = P.LINK and SATISFY = 1)
				end		)))
		where 	(P.link = @varKSnLinkPers OR @varKSnLinkPers = 0)	
				AND s.DATE1 <= @varKSEND_DATE
				AND s.DATE1 >= @varKSstart_date	
				AND s.DEP_LINK = @DEP_LINK
		ORDER BY 
				s.DATE1 DESC		
					

		--Вычисление категории
		DECLARE @varKSKATEG_P VARCHAR(4000), @varKSTMP_STR_P VARCHAR(254)
		SET @varKSKATEG_P = ''
		DECLARE #KAT_CURSOR CURSOR LOCAL FAST_FORWARD FOR

		SELECT TOP 1 ISNULL(QUALIFY, '') 
		FROM dbo.KU_PERS_EDUCATION PE
		WHERE PERS_LINK = @varKSnLinkPers AND YEAR(DATE_END) <= @varKSnYear
		ORDER BY SATISFY DESC
		
		OPEN #KAT_CURSOR
		FETCH #KAT_CURSOR INTO @varKSTMP_STR
		WHILE @@FETCH_STATUS = 0 BEGIN
			SET @varKSKATEG_P = @varKSKATEG_P + ' ' + RTRIM(@varKSTMP_STR_P)
			FETCH #KAT_CURSOR INTO @varKSTMP_STR
		END
		CLOSE #KAT_CURSOR
		DEALLOCATE #KAT_CURSOR

		UPDATE #PART1_P SET KATEG = LTRIM(RTRIM(@varKSKATEG_P))

		--	
		declare @varKSdays_P int, @varKSmonths_P int, @varKSyears_P int, @varKScDate_P varchar(10)
		SELECT @varKSyears_P = years, @varKSmonths_P = months, @varKSdays_P = days from dbo.ku_EmplExpirTable(@varKSnLinkEmpl,@varKSEND_DATE, DEFAULT) ET WHERE ET.EXPIR_CODE = 'GEN'  

		UPDATE #PART1_P SET EXPIR = ''
		/*	RTRIM(LTRIM(CAST (@varKSyears_P AS VARCHAR(4) ))) + ' лет '
			+ RTRIM(LTRIM(CAST (@varKSmonths_P AS VARCHAR(2) ))) + ' месяцев '
			+ RTRIM(LTRIM(CAST (@varKSdays_P AS VARCHAR(2) ))) + ' дней '
		*/	
		CREATE TABLE #DPP (PERS_LINK INT, LINK_PAYS INT, ORDER_DATE DATETIME, ORD_LINK int ,  DATE_BEGIN DATETIME, DATE_END DATETIME, VALUE NUMERIC(18,4))

		INSERT INTO #DPP (PERS_LINK, LINK_PAYS, ORDER_DATE,ORD_LINK, DATE_BEGIN, DATE_END, VALUE)
		SELECT GT.PERS_LINK, GT.LINK_PAY, S.[DATE], S.link, G.PERIOD, dbo.DateEndOfMonth(G.PERIOD), GT.SUMMA 
		FROM DOCUMENTS_DGH G INNER JOIN DOCUMENTS_DGH_T1 GT ON G.LINK = GT.LINK 
							 left  join salary_reestr_dgh s on GT.LINK_DOG =  s.link
		WHERE 
			gt.pers_Link = @varKSnLinkPers
			and G.FLAG_JC = 1
			AND G.LINK_DEP = @DEP_LINK
		
		CREATE TABLE #PAYS_PERS(
			LINK_PAY INT, ord_link int ,cp varchar(10), NP VARCHAR(254), 
			date_begin datetime, date_end datetime,
			s numeric(20,2), parent_id int
		)

		-- На начало года по договорнику
		/*INSERT INTO #PAYS_PERS
		SELECT 
			ISNULL(P1.LINK,P.LINK), ISNULL(P1.CODE,P.CODE), ISNULL(P1.NAME,P.NAME), ISNULL(DPP.ORDER_DATE,DPP.DATE_BEGIN), NULL, VALUE, 0
		FROM 
			#DPP DPP
			INNER JOIN dbo.PAYS P ON P.LINK = DPP.LINK_PAYS
			LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1 
		WHERE 
			PERS_LINK = @varKSnLinkPers
			AND @varKSstart_date - 1 BETWEEN DPP.DATE_BEGIN AND ISNULL(DATE_END, '30000101')
			AND VALUE > 0
		*/

		-- Изменения в выбранном году
		INSERT INTO #PAYS_PERS
		SELECT 
			ISNULL(P1.LINK,P.LINK), ord_link ,ISNULL(P1.CODE,P.CODE), ISNULL(P1.NAME,P.NAME), 
			ISNULL(DPP.ORDER_DATE,DPP.DATE_BEGIN), 
			DATE_END, VALUE, 0
		FROM 
			#DPP DPP
			INNER JOIN dbo.PAYS P ON P.LINK = DPP.LINK_PAYS
			LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1
		WHERE 
			PERS_LINK = @varKSnLinkPers
			AND YEAR(ISNULL(DPP.ORDER_DATE,DPP.DATE_BEGIN)) = @varKSnYear
			AND ISNULL(DATE_END, '30000101') >= @varKSstart_date
			AND VALUE > 0
			AND NOT EXISTS (SELECT * FROM #PAYS_PERS PP WHERE PP.LINK_PAY = ISNULL(P1.LINK,P.LINK) AND PP.date_begin = ISNULL(DPP.ORDER_DATE,DPP.DATE_BEGIN))

		-- Прочие действующие сейчас начисления
		INSERT INTO #PAYS_PERS
		SELECT 
			ISNULL(P1.LINK,P.LINK),ord_link, ISNULL(P1.CODE,P.CODE), ISNULL(P1.NAME,P.NAME), NULL, NULL, VALUE, 0
		FROM 
			#DPP DPP
			INNER JOIN dbo.PAYS P ON P.LINK = DPP.LINK_PAYS
			LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1
		WHERE 
			PERS_LINK = @varKSnLinkPers
			AND DATE_BEGIN = (Select max(g1.period) from DOCUMENTS_DGH G1 INNER JOIN DOCUMENTS_DGH_T1 GT1 ON G1.LINK = GT1.LINK  where GT1.PERS_LINK = DPP.PERS_LINK and Gt1.LINK_PAY = DPP.LINK_PAYS and G1.PERIOD <= @varKSEND_DATE AND ISNULL(dbo.DateEndOfMonth(g1.PERIOD), '30000101') >= @varKSstart_date) 
			AND ISNULL(DATE_END, '30000101') >= @varKSstart_date
			AND VALUE > 0
			AND NOT EXISTS (SELECT * FROM #PAYS_PERS PP WHERE PP.LINK_PAY = ISNULL(P1.LINK,P.LINK))

		UPDATE #PAYS_PERS
		SET DATE_BEGIN = NULL
		WHERE DATE_BEGIN < @varKSstart_date
		
		UPDATE R
		SET CP = CP + '*', NP = NP + '*'
		FROM
			#PAYS_PERS R
			INNER JOIN dbo.PAYS P on P.LINK_MPAY = R.LINK_PAY

		CREATE TABLE #TMP2_P ( ID INT IDENTITY, ORDER_DATE datetime, ORDER_NUM VARCHAR(30),
			SUBDIV VARCHAR(254), POST VARCHAR(254), CONDITION VARCHAR(40), 
			KATEG VARCHAR(254), AVANSE NUMERIC(20, 2), REAL_REC BIT, link_dgh int
		)
		
		--INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG,
		--	REAL_REC)
		--SELECT TOP 1 DATE, NUMBER, SUBDIVISION_PD, POST_PD, '', '', 1
		--FROM DICTIONARY_PURP_DISP_FACES 
		--WHERE EMPL_LINK = @varKSnLinkEmpl AND YEAR(DATE_PD) < @varKSnYear
		--ORDER BY DATE_PD DESC

		CREATE TABLE #STAFF_INFO_P(LINK_UP INT, DEP_NAME VARCHAR(254), POST_NAME VARCHAR(254), DATE_BEGIN DATETIME, DATE_END DATETIME)
		INSERT INTO #STAFF_INFO_P(LINK_UP, DEP_NAME, POST_NAME, DATE_BEGIN, DATE_END)
		SELECT 
			S.LINK, 
			(SELECT TOP 1 [name] FROM dictionary_department_hist WHERE link_UP = s.dep_link and (s.date1 between date_begin and date_end or s.date1< date_begin and s.date2 > date_end or s.date2 between date_begin and date_end)),
			'Наемный рабочий',
			S.DATE1, 
			S.DATE2
		FROM 
			DBO.salary_reestr_dgh S
			
		--Приказы о приёме и переводе
		---------------------------
		-- Прием
		INSERT INTO #TMP2_P (ORDER_DATE, ORDER_NUM ,  SUBDIV, POST, CONDITION, KATEG, REAL_REC, link_dgh)
		SELECT 
			sr.[DATE], sr.NUMBER, case when sr.date2 is not null then 'ПРИНЯТ(А) c' + CONVERT(VARCHAR(10),sr.DATE1,104) + ' по ' + CONVERT(VARCHAR(10),sr.DATE2,104) 
																else 'ПРИНЯТ(А) ' + CONVERT(VARCHAR(10),sr.DATE1,104) end 	
			, '', '', '', 1 , Sr.link /*#3584 Шорков И.А. добавление даты приема*/
		FROM 
			#STAFF_INFO_P S 
			inner join DBO.salary_reestr_dgh Sr ON S.link_up=sr.link and sr.date1 between s.date_begin and s.date_end
		WHERE 
			sr.PERS_LINK = @varKSnLinkPers AND (YEAR(sr.DATE1) <= @varKSnYear and YEAR(sr.DATE2) >= @varKSnYear) 	 /* #3584 Шорков И.А. приказ о приеме работника может быть не только за выбранный год */
		ORDER BY 
			sr.DATE1 
		---
		INSERT INTO #TMP2_P (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG,REAL_REC, link_dgh)
		SELECT NULL, NULL, NULL, NULL, '', '', 1 , null
		WHERE EXISTS (
			SELECT * FROM #DPP DPP WHERE PERS_LINK = @varKSnLinkPers
					AND @varKSstart_date-1 BETWEEN DPP.DATE_BEGIN AND ISNULL(DATE_END, '30000101')
					AND VALUE > 0	
			)		
	
		---		
		/*--Перевод
		INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG, REAL_REC)
		SELECT 
			o.[DATE], o.NUMBER, 
			case when ORD.obj_code = 'MOVES' then 'ПЕРЕВЕДЕН(А) ' + CONVERT(VARCHAR(10),im.DATE_BEGIN,104)
				 else ORD.type_txt + ' ' + CONVERT(VARCHAR(10),im.DATE_BEGIN,104) end	, 
			S.POST_NAME, '', '', 1 /*#3584 Шорков И.А. добавление даты приема*/
		FROM 
			ITEM_MOVE im 
			INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE not in(2,1)
			inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
			LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
			
		WHERE 
			im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear	 /* #3584 Шорков И.А. приказ о приеме работника может быть не только за выбранный год */
		
		union 
	 		SELECT DISTINCT DATE_BEGIN, null, '','','','',1
			FROM #PAYS_EMPL
			WHERE 
			DATE_BEGIN NOT IN (SELECT ISNULL(O.[DATE],'18000101') FROM ITEM_MOVE im 
								INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE not in(2,1)
								inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
								LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
									WHERE 
								im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear)
			AND DATE_BEGIN >= ISNULL((SELECT MIN(O.[DATE]) FROM ITEM_MOVE im 
								INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK /*and im.active=1*/ AND IM.NEW_FACE not in(2,1)
								inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
								LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
									WHERE 
								im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear), '18000101')
								
		/*ORDER BY 
			DATE_BEGIN ASC*/
		-----------------------------
			
		-- Приказы об увольнении
		DECLARE @DICTIONARY_PUV INT
		SET @DICTIONARY_PUV = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS WHERE CODE = 'DICTIONARY_PUV')

		INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG, REAL_REC)
		SELECT 
			o.[DATE], o.NUMBER, 'УВОЛЕН(А) ' + CONVERT(VARCHAR(10),DIS_DATE,104), LEFT(D.NAME,254), '', '', 1
		FROM 
			dbo.ITEM_DIS_FACE DF
			INNER JOIN dbo.ORDERS O ON DF.ORDER_LINK=o.LINK and DF.active=1
			INNER JOIN dbo.DICTION D ON D.LINK = DF.REASON
		WHERE 
			DF.EMPL_LINK = @varKSnLinkEmpl AND YEAR(DF.DIS_DATE) = @varKSnYear	
		ORDER BY 
			DF.DIS_DATE DESC		
		*/	
		DECLARE @varKSDATE_MIN_P DATETIME, 
				@varKSADVANCE_P NUMERIC(20, 2)

		set @varKSADVANCE_P = 0
		
		/*SELECT @varKSADVANCE_P = OKL.OKLAD * ISNULL(AVANCE, 0) / 100.0 
		FROM EMPL E,dbo.salary_oklad(@varKSEND_DATE, @varKSnLinkEmpl, DEFAULT, @DEP_LINK) OKL  
		WHERE OKL.LINK_EMPL = @varKSnLinkEmpl AND E.LINK = OKL.LINK_EMPL 
		*/
		SET @varKSDATE_MIN_P = ISNULL((SELECT MIN(ORDER_DATE) FROM #TMP2_P), '18000101')

		/*INSERT INTO #TMP2_P(ORDER_DATE, REAL_REC)
		SELECT DISTINCT DATE_BEGIN, 1
		FROM #PAYS_PERS
		WHERE 
			DATE_BEGIN NOT IN (SELECT ISNULL(ORDER_DATE,'18000101') FROM #TMP2_P)
			AND DATE_BEGIN >= @varKSDATE_MIN
		*/

		DECLARE #TMP_CUR CURSOR LOCAL FAST_FORWARD FOR 
			SELECT ID, ORDER_DATE, link_DGH
			FROM #TMP2_P
			ORDER BY ORDER_DATE DESC, id DESC
		DECLARE @varKSID_P INT, @varKSORDER_DATE_P DATETIME , @varKSORDL_P INT
		
		OPEN #TMP_CUR
		FETCH #TMP_CUR INTO @varKSID_P, @varKSORDER_DATE_P, @varKSORDL_P
		WHILE @@FETCH_STATUS = 0 BEGIN
		
			UPDATE #PAYS_PERS
			SET PARENT_ID = @varKSID_P
			WHERE 
				PARENT_ID = 0 
				AND DATE_BEGIN >= @varKSORDER_DATE_P and ORD_LINK = @varKSORDL_P
			FETCH #TMP_CUR INTO @varKSID_P, @varKSORDER_DATE_P ,@varKSORDL_P
		END
		CLOSE #TMP_CUR
		DEALLOCATE #TMP_CUR
		
		UPDATE #PAYS_PERS
		SET PARENT_ID = @varKSID_P 
		WHERE 
			PARENT_ID = 0 

		UPDATE #TMP2_P SET AVANSE = @varKSADVANCE_P WHERE ORDER_DATE = @varKSDATE_MIN_P
		DECLARE @varKSPAYS_PERS VARCHAR(100), @varKSTMP2_P VARCHAR(120)
		EXEC X_GET_TABLE_NAME @varKSPAYS_PERS OUTPUT
		SET @varKSTMP2_P = @varKSPAYS_PERS + '_1'

		EXEC M_CROSS_TABLE 
			'PARENT_ID',
			'CP, NP',
			'VARCHAR(10)#VARCHAR(254)',
			'S',
			'NUMERIC(20,2)',
			'SUM(S) AS S',
			'#PAYS_PERS',
			@varKSPAYS_PERS


		INSERT INTO #TMP2_P(REAL_REC) VALUES(0)
		INSERT INTO #TMP2_P(REAL_REC) VALUES(0)
		INSERT INTO #TMP2_P(REAL_REC) VALUES(0)
		INSERT INTO #TMP2_P(REAL_REC) VALUES(0)
		INSERT INTO #TMP2_P(REAL_REC) VALUES(0)
		INSERT INTO #TMP2_P(REAL_REC) VALUES(0)

		-- у договорников нет отпусков
		CREATE TABLE #TMP_3_P ( ID INT IDENTITY,
			ORD_DATE DATETIME,	ORD_NUM VARCHAR(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_P
		(
			ORD_DATE, ORD_NUM, 
			VAC_TYPE,
			PERIOD_B, PERIOD_E,
			VAC_BEG, VAC_END,
			DAYS, REAL_REC
		)
		SELECT 
			null, null,
			'',
			null, null,
			null, null,
			null,
			1
		/*INSERT INTO #TMP_3_P
		(
			ORD_DATE, ORD_NUM, 
			VAC_TYPE,
			PERIOD_B, PERIOD_E,
			VAC_BEG, VAC_END,
			DAYS, REAL_REC
		)
		SELECT 
			DATE, NUMBER,
			TYPE_NAME,
			PERIOD_BEGIN, PERIOD_END,
			DATE_BEGIN, DATE_END,
			dbo.W_DAYS(7, DATE_BEGIN,DATE_END),
			1
		FROM VACATION
		WHERE
			EMPL_LINK = @varKSnLinkEmpl
			AND YEAR([DATE_BEGIN]) = @varKSnYear
		*/	
	
		CREATE TABLE #TMP_DED_P (
			ID INT IDENTITY, 
			DOC_NAME VARCHAR(254), DOC_NUM VARCHAR(50), DOC_DST VARCHAR(254), DOC_ADR VARCHAR(254), 
			link_tax int, NAME_TAX VARCHAR(254), DATE1 DATETIME, DATE2 DATETIME, 
			SUMMA_PROC NUMERIC(20,2), SUMMA NUMERIC(20, 2), REAL_REC BIT )

		INSERT INTO #TMP_DED_P (DOC_NAME, DOC_NUM, DOC_DST, DOC_ADR, link_tax, NAME_TAX, DATE1, DATE2, SUMMA_PROC, SUMMA, REAL_REC)
		SELECT 
			DOC_NAME, 
			DOC_NUM = '№ ' + DOC_NUM + ' от ' + CONVERT(VARCHAR(10),DOC_DATE,104),
			DOC_DST = D.NAME,
			DOC_ADR = 
				LEFT(
					(
					LEFT(ISNULL(dbo.GetAddressByKladr(D.KLADR_LINK), ''), 254) + 
					CASE WHEN LEN(ISNULL(HOUSE, '')) = 0 THEN '' ELSE ', д. ' + LTRIM(RTRIM(HOUSE)) END 
					--+ CASE WHEN LEN(ISNULL(CORP_REAL, '')) = 0 THEN '' ELSE ', корп. ' + LTRIM(RTRIM(CORP_REAL)) END 
					+ CASE WHEN LEN(ISNULL(FLAT, '')) = 0 THEN '' ELSE ', оф. ' + LTRIM(RTRIM(FLAT)) END
					--Расчётный счёт		
					+ ISNULL(
						CASE WHEN DA.CODE IS NOT NULL THEN DA.CODE
							ELSE (SELECT TOP 1 DA1.CODE FROM dbo.DEPARTMENT_ACCOUNTS DA1 WHERE DA1.[TYPE] = 1 AND DA1.LINK_UP = ET.LINK_DEST)
						END, '')
				),254),	
			
			link_tax, NAME_TAX, DATE1, DATE2, SUMMA, SUMMA, 1
		FROM 
			dbo.SD_EMPL_TAX ET
			inner join #TMP2_P  p2 on ET.LINK_DGH = p2.LINK_DGH
			LEFT JOIN dbo.DEPARTMENTS D ON D.LINK = ET.LINK_DEST
			LEFT JOIN dbo.DEPARTMENT_ACCOUNTS DA ON DA.LINK = D.MAIN_LINK
		WHERE 
			ET.LINK_DGH is not null
			and ET.LINK_EMPL is null
			AND (DATE2 IS NULL OR DATE2 >= @varKSstart_date)
			AND (DATE1 <= @varKSEND_DATE)

		DECLARE @varKSTMP_INT_P INT, 
			@varKSCOUNT_2_P INT, @varKSCOUNT_3_P INT, @varKSCOUNT_4_P INT, @varKSCOUNT_MAX_P INT, @varKSDELTA_P INT
		SET @varKSCOUNT_2_P = 0
		SET @varKSCOUNT_MAX_P = @varKSCOUNT_2_P
		SET @varKSCOUNT_3_P = (SELECT COUNT(*) FROM #TMP_DED_P)
		IF @varKSCOUNT_MAX_P < @varKSCOUNT_3_P SET @varKSCOUNT_MAX_P = @varKSCOUNT_3_P
		IF @varKSCOUNT_MAX_P =0 SET @varKSCOUNT_MAX_P = 1
		SET @varKSDELTA_P = @varKSCOUNT_MAX_P - @varKSCOUNT_2_P
		SET @varKSTMP_INT_P = 1
		/*WHILE @varKSTMP_INT_P <= @varKSDELTA_P BEGIN
			INSERT INTO #TMP_3(REAL_REC) VALUES(0)
			SET @varKSTMP_INT_P=@varKSTMP_INT_P+1
		END
		*/

		SET @varKSDELTA_P=@varKSCOUNT_MAX_P-@varKSCOUNT_3_P
		SET @varKSTMP_INT_P=1
		WHILE @varKSTMP_INT_P<=@varKSDELTA_P BEGIN
			INSERT INTO #TMP_DED_P (REAL_REC) VALUES(0)
			SET @varKSTMP_INT_P=@varKSTMP_INT_P+1
		END


		--INSERT INTO #TMP_3(REAL_REC) VALUES(0)
		--INSERT INTO #TMP_3(REAL_REC) VALUES(0)
		--INSERT INTO #TMP_3(REAL_REC) VALUES(0)
		INSERT INTO #TMP_DED_P (REAL_REC) VALUES(0)
		INSERT INTO #TMP_DED_P (REAL_REC) VALUES(0)
		INSERT INTO #TMP_DED_P (REAL_REC) VALUES(0)
		

		CREATE TABLE #PART2_p (mode int, NAME_STR VARCHAR(254), code varchar(10),
			SM01 NUMERIC(20,2), SM02 NUMERIC(20,2), SM03 NUMERIC(20,2), 
			SM04 NUMERIC(20,2), SM05 NUMERIC(20,2), SM06 NUMERIC(20,2), 
			SM07 NUMERIC(20,2), SM08 NUMERIC(20,2), SM09 NUMERIC(20,2), 
			SM10 NUMERIC(20,2), SM11 NUMERIC(20,2), SM12 NUMERIC(20,2)
		)


		
		insert into #PART2_P 
		select 1, 'отработано дней', '',
			max(case when month_begin = 1 then days else 0 end),
			max(case when month_begin = 2 then days else 0 end),
			max(case when month_begin = 3 then days else 0 end),
			max(case when month_begin = 4 then days else 0 end),
			max(case when month_begin = 5 then days else 0 end),
			max(case when month_begin = 6 then days else 0 end),
			max(case when month_begin = 7 then days else 0 end),
			max(case when month_begin = 8 then days else 0 end),
			max(case when month_begin = 9 then days else 0 end),
			max(case when month_begin = 10 then days else 0 end),
			max(case when month_begin = 11 then days else 0 end),
			max(case when month_begin = 12 then days else 0 end)
		from s_j_c 
		where  
			link_empl IS NULL AND  PERS_LINK = @varKSnLinkPers
			and year_begin = @varKSnYear
			and typ_oper = 1 /*and (way_calc = 1 or way_calc = 2)*/

		insert into #PART2_P 
		select 2, 'всего начислено', '',
			sum(case when month_begin = 1 then summa else 0 end),
			sum(case when month_begin = 2 then summa else 0 end),
			sum(case when month_begin = 3 then summa else 0 end),
			sum(case when month_begin = 4 then summa else 0 end),
			sum(case when month_begin = 5 then summa else 0 end),
			sum(case when month_begin = 6 then summa else 0 end),
			sum(case when month_begin = 7 then summa else 0 end),
			sum(case when month_begin = 8 then summa else 0 end),
			sum(case when month_begin = 9 then summa else 0 end),
			sum(case when month_begin = 10 then summa else 0 end),
			sum(case when month_begin = 11 then summa else 0 end),
			sum(case when month_begin = 12 then summa else 0 end)
		from s_j_c where link_empl IS NULL AND  PERS_LINK = @varKSnLinkPers
			and year_begin = @varKSnYear
			and typ_oper = 1


		
		insert into #PART2_P 
		select 4, 'всего удержано', '',
			sum(case when month_begin = 1 then summa else 0 end),
			sum(case when month_begin = 2 then summa else 0 end),
			sum(case when month_begin = 3 then summa else 0 end),
			sum(case when month_begin = 4 then summa else 0 end),
			sum(case when month_begin = 5 then summa else 0 end),
			sum(case when month_begin = 6 then summa else 0 end),
			sum(case when month_begin = 7 then summa else 0 end),
			sum(case when month_begin = 8 then summa else 0 end),
			sum(case when month_begin = 9 then summa else 0 end),
			sum(case when month_begin = 10 then summa else 0 end),
			sum(case when month_begin = 11 then summa else 0 end),
			sum(case when month_begin = 12 then summa else 0 end)
		from s_j_c where link_empl IS NULL AND  PERS_LINK = @varKSnLinkPers
			and year_begin = @varKSnYear
			and typ_oper = 2 
			and link_doc not in (
				select link from DOCUMENTS_DED_PR_DGH 
				where year_base = @varKSnYear

					and flag_jc = 1
					and TYP_PAYMENT = 1
			)



	-----Начисленные суммы
		CREATE TABLE #SJ_P (typ_oper TINYINT , month_begin TINYINT, LINK_PAYS INT, NAME_PAYS VARCHAR(254), CODE_PAYS  varchar(10), SUMMA NUMERIC(18,2))
		INSERT INTO #SJ_P (typ_oper, month_begin, LINK_PAYS, NAME_PAYS, CODE_PAYS, SUMMA)
		SELECT P.[OBJECT], MONTH(J.PERIOD_BEGIN), ISNULL(P1.LINK,P.LINK), ISNULL(P1.NAME,P.NAME), ISNULL(P1.CODE,P.CODE), SUMMA
		from 
			dbo.CALCULATE_JURNAL J
			INNER JOIN dbo.PAYS P ON P.LINK = J.LINK_PAYS
			LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1
		where 
			link_empl IS NULL
			AND  PERS_LINK = @varKSnLinkPers
			and YEAR(J.PERIOD_BEGIN) = @varKSnYear
			and P.[OBJECT] in(1, 2)
			and link_doc not in (
				select link from DOCUMENTS_DED_PR_DGH 
				where year_base = @varKSnYear
					and flag_jc = 1
					and TYP_PAYMENT = 1
			)
		--
		UPDATE R
		SET NAME_PAYS = NAME_PAYS + '*', CODE_PAYS = CODE_PAYS + '*'
		FROM
			#SJ_P R
			INNER JOIN dbo.PAYS P on P.LINK_MPAY = R.LINK_PAYS
		--	
		insert into #PART2_P 
		select 
			case when typ_oper = 1 then 3 else 5 end, 
			name_pays, code_pays,
			sum(case when month_begin = 1 then summa else 0 end),
			sum(case when month_begin = 2 then summa else 0 end),
			sum(case when month_begin = 3 then summa else 0 end),
			sum(case when month_begin = 4 then summa else 0 end),
			sum(case when month_begin = 5 then summa else 0 end),
			sum(case when month_begin = 6 then summa else 0 end),
			sum(case when month_begin = 7 then summa else 0 end),
			sum(case when month_begin = 8 then summa else 0 end),
			sum(case when month_begin = 9 then summa else 0 end),
			sum(case when month_begin = 10 then summa else 0 end),
			sum(case when month_begin = 11 then summa else 0 end),
			sum(case when month_begin = 12 then summa else 0 end)
		from #SJ_P
		group by 
			case when typ_oper = 1 then 3 else 5 end, 
			name_pays, code_pays


		insert into #PART2_P 
		select 6, 'сумма к выдаче', '',
			sum(case when month_base = 1 then d1.summa else 0.00 end),
			sum(case when month_base = 2 then d1.summa else 0.00 end),
			sum(case when month_base = 3 then d1.summa else 0.00 end),
			sum(case when month_base = 4 then d1.summa else 0.00 end),
			sum(case when month_base = 5 then d1.summa else 0.00 end),
			sum(case when month_base = 6 then d1.summa else 0.00 end),
			sum(case when month_base = 7 then d1.summa else 0.00 end),
			sum(case when month_base = 8 then d1.summa else 0.00 end),
			sum(case when month_base = 9 then d1.summa else 0.00 end),
			sum(case when month_base = 10 then d1.summa else 0.00 end),
			sum(case when month_base = 11 then d1.summa else 0.00 end),
			sum(case when month_base = 12 then d1.summa else 0.00 end)
		from DOCUMENTS_DED_PR_DGH d inner join DOCUMENTS_DED_PR_TABLE_DGH d1
			on (d.link = d1.link and d1.PERS_LINK = @varKSnLinkPers 
				and year_base = @varKSnYear
				and flag_jc = 1
				and TYP_PAYMENT = 1)

		SELECT *,
			@varKSCODE_FKR_D AS CODE_FKR_D, @varKSNAME_FKR_D AS NAME_FKR_D,
			@varKSCODE_FKR_T AS CODE_FKR_T, @varKSNAME_FKR_T AS NAME_FKR_T,
			@varKSCODE_FKR_E AS CODE_FKR_E, @varKSNAME_FKR_E AS NAME_FKR_E
		FROM #PART1_P

		EXEC ('
			SELECT * 
			INTO ' + @varKSTMP2_P + ' 
			FROM #TMP2_P T2 LEFT OUTER JOIN ' + @varKSPAYS_PERS + ' PE
			ON T2.ID = PE.PARENT_ID
		')	
	 
		DECLARE @varKSCNT_PAYS_P INT, @varKSFIELD_NAME_P VARCHAR(254), @varKSSQL_STR_P VARCHAR(8000), @varKSI_P INT
		SELECT @varKSCNT_PAYS_P = COUNT(DISTINCT CP) FROM #PAYS_PERS
		SET @varKSI_P=1
		WHILE @varKSI_P <= @varKSCNT_PAYS_P BEGIN
			SET @varKSFIELD_NAME_P = 'CP_' + RTRIM(LTRIM(STR(@varKSI_P))) 
			SET @varKSSQL_STR_P= ' UPDATE ' + @varKSTMP2_P + '  SET '+@varKSFIELD_NAME_P+ ' = (SELECT TOP 1 '+@varKSFIELD_NAME_P + ' FROM ' + @varKSPAYS_PERS + ' WHERE '+
				@varKSFIELD_NAME_P+ '  IS NOT NULL ) ' 
			EXEC (@varKSSQL_STR_P)
			SET @varKSFIELD_NAME_P= 'NP_'  +  RTRIM(LTRIM(STR(@varKSI_P)))  + '_'  +  RTRIM(LTRIM(STR(@varKSI_P))) 
			SET @varKSSQL_STR_P= ' UPDATE ' + @varKSTMP2_P + '  SET '+@varKSFIELD_NAME_P+ ' = (SELECT TOP 1 '+@varKSFIELD_NAME_P + ' FROM ' + @varKSPAYS_PERS + ' WHERE '+
				@varKSFIELD_NAME_P+ '  IS NOT NULL ) ' 
			EXEC (@varKSSQL_STR_P)
			SET @varKSFIELD_NAME_P= 'S_'  +  RTRIM(LTRIM(STR(@varKSI_P)))  + '_'  +  RTRIM(LTRIM(STR(@varKSI_P))) 
			SET @varKSSQL_STR_P= ' UPDATE '+@varKSTMP2_P + '  SET '+@varKSFIELD_NAME_P+ ' = 0  WHERE ' +
				@varKSFIELD_NAME_P+ '  IS  NULL ' 

			SET @varKSI_P=@varKSI_P+1
		END

		IF @varKSCNT_PAYS_P >= 1 AND @varKSCNT_PAYS_P < 9  BEGIN
			SET @varKSDELTA_P = 9 - @varKSCNT_PAYS_P
			SET @varKSI_P = 1
			WHILE @varKSI_P <= @varKSDELTA_P BEGIN
				SET @varKSSQL_STR_P= 'ALTER TABLE '  + @varKSTMP2_P + 
				'  ADD CP_' + LTRIM(STR(@varKSCNT_PAYS_P + @varKSI_P)) + '  VARCHAR(10), 
				NP_' + LTRIM(STR(@varKSCNT_PAYS_P + @varKSI_P)) + '_' + LTRIM(STR(@varKSCNT_PAYS_P + @varKSI_P)) + ' VARCHAR(254), 
				S_' + LTRIM(STR(@varKSCNT_PAYS_P + @varKSI_P)) + '_' + LTRIM(STR(@varKSCNT_PAYS_P + @varKSI_P)) + '  NUMERIC(20,2) '
				EXEC (@varKSSQL_STR_P)
				SET @varKSI_P=@varKSI_P+1
			END
		END

		IF @varKSCNT_PAYS_P = 0 BEGIN
			SET @varKSSQL_STR_P= 
				'ALTER TABLE '  + @varKSTMP2_P + 
				'  ADD CP_0  VARCHAR(10), 
				NP_0_0 VARCHAR(254), 
				S_0_0  NUMERIC(20,2) '
				EXEC (@varKSSQL_STR_P)
		END


		EXEC( 'SELECT *, ITOGOZP = NULL 
		FROM ' + @varKSTMP2_P + ' ORDER  by ID, REAL_REC DESC, ORDER_DATE ASC')
	/*
		EXEC( 'SELECT *, ITOGOZP = (SELECT SUM(S) FROM #PAYS_EMPL WHERE ORDER_DATE BETWEEN DATE_BEGIN AND COALESCE(DATE_END,''29990101'')) 
		FROM ' + @varKSTMP2 + ' ORDER BY REAL_REC DESC, ORDER_DATE ASC')
	*/
		SELECT * 
		FROM #TMP_3_P INNER JOIN #TMP_DED_P ON #TMP_3_P.ID = #TMP_DED_P.ID
		ORDER BY #TMP_3_P.REAL_REC DESC, ORD_DATE

		select * from #part2_P
		order by mode, code


		EXEC ('DROP TABLE ' + @varKSPAYS_PERS )
		EXEC ('DROP TABLE ' + @varKSTMP2_P )
	
	
	END
END










GO


GRANT EXECUTE ON dbo.[SD_REP_F417] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SZV4_PRINT_SPV2]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SZV4_PRINT_SPV2]

GO


CREATE PROCEDURE dbo.SZV4_PRINT_SPV2(@Link int)
AS
-- exec SZV4_PRINT_SPV2 151
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 dbo.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),
	[YEAR_EDT] = ISNULL(p.year_edt,0),
	[PER_EDT] = ISNULL(p.PER_EDT,0),
	[TYPE] = P.vid_kor,
	[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), --Это сумма уплаченных взносов на страхов. часть
	[GAIN] = COALESCE(S.GAIN,0), --Это сумма начисленных взносов на накопит. часть
	[GAIN1] = COALESCE(S.DOP,0), --Это сумма уплаченных взносов на накопит. часть
	INC_T1_M1 = S.INCOME_T1_M1,--Это сумма уплаченных взносов по доп тарифу1 за 1 месяц
	INC_T1_M2 = S.INCOME_T1_M2,--Это сумма уплаченных взносов по доп тарифу1 за 2 месяц
	INC_T1_M3 = S.INCOME_T1_M3,--Это сумма уплаченных взносов по доп тарифу1 за 3 месяц
	INC_T2_M1 = S.INCOME_T2_M1,--Это сумма уплаченных взносов по доп тарифу2 за 1 месяц
	INC_T2_M2 = S.INCOME_T2_M2,--Это сумма уплаченных взносов по доп тарифу2 за 2 месяц
	INC_T2_M3 = S.INCOME_T2_M3,--Это сумма уплаченных взносов по доп тарифу2 за 3 месяц
	[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], DD = DAY([date]), MM = M.MON, YY = YEAR([date])
from
	dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SA_SZV4_SVEDENIA S ON P.link = S.link
	left JOIN dbo.SA_SZV4_STAZH ST ON S.link1 = ST.link
	INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = P.KATEG AND year_begin BETWEEN YBEG AND YEND
	INNER JOIN dbo.MONTHS M ON M.NUM = MONTH([date])
where
	P.link = @Link
	and P.[type] = 2
	and P.proverka = 1
order by
	S.pachka, S.orders, ST.orders


GO


GRANT EXECUTE ON dbo.[SZV4_PRINT_SPV2] TO PUBLIC

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(1000), 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
WHERE
	SO.CODE <> 'DOCUMENTS_500' --б/о  НЕ ТЕСТИМ

INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
SELECT distinct SO.CODE, '', 'Основание', G.LINK,
	'Невозможно переформировать проводки, т.к. документ без даты проведения "' + SO2.NAME + '" №' + LTRIM(RTRIM(GG.NUMBER)) + ' от ' + CONVERT(VARCHAR(10),GG.[DATE],104) 
		+ CHAR(13) + CHAR(10) + ' указан в качестве документа-основания в документе ' + SO.NAME + '" №' + LTRIM(RTRIM(G.NUMBER)) + ' от ' + CONVERT(VARCHAR(10),G.[DATE],104)
		+ CHAR(13) + CHAR(10) + ' Удалите вручную документ: ' +SO.NAME + '" №' + LTRIM(RTRIM(G.NUMBER)) + ' от ' + CONVERT(VARCHAR(10),G.[DATE],104),
	1
from 
	osnov o 
	inner join #PROV p on p.LINK = o.LINK_G_PROV
	inner join G_PROV_AP gap on gap.AP1 = o.LINK
	inner join G_PROV2 g2 on g2.LINK = gap.LINK_UP
	inner join G_PROV1 g1 on g1.LINK = g2.LINK_UP
	inner join G_PROV g on g.LINK = g1.LINK_UP
	inner join G_PROV gg on gg.LINK = o.LINK_G_PROV
	inner join dbo.S_OBJECTS so on so.LINK = g.OBJECT
	inner join dbo.S_OBJECTS so2 on so2.LINK = gg.OBJECT
where
	gg.DATE_PROV is null
	
INSERT INTO #TempControlTable(OBJ_CODE,OBJ_NAME,FIELD_NAME,LINK,COMMENTS,Type)
SELECT distinct SO.CODE, '', 'Основание', G.LINK,
	'Невозможно переформировать проводки, т.к. документ без проводки "' + SO2.NAME + '" №' + LTRIM(RTRIM(GG.NUMBER)) + ' от ' + CONVERT(VARCHAR(10),GG.[DATE],104) 
		+ CHAR(13) + CHAR(10) + ' указан в качестве документа-основания в документе ' + SO.NAME + '" №' + LTRIM(RTRIM(G.NUMBER)) + ' от ' + CONVERT(VARCHAR(10),G.[DATE],104) + ' Сумма=' + CONVERT(VARCHAR(20),g2.SUMMA)
		+ CHAR(13) + CHAR(10) + ' Удалите вручную документ: ' +SO.NAME + '" №' + LTRIM(RTRIM(G.NUMBER)) + ' от ' + CONVERT(VARCHAR(10),G.[DATE],104),
	1
from 
	osnov o 
	inner join #PROV p on p.LINK = o.LINK_G_PROV
	inner join G_PROV_AP gap on gap.AP1 = o.LINK
	inner join G_PROV2 g2 on g2.LINK = gap.LINK_UP
	inner join G_PROV1 g1 on g1.LINK = g2.LINK_UP
	inner join G_PROV g on g.LINK = g1.LINK_UP
	inner join G_PROV gg on gg.LINK = o.LINK_G_PROV
	inner join dbo.S_OBJECTS so on so.LINK = g.OBJECT
	inner join dbo.S_OBJECTS so2 on so2.LINK = gg.OBJECT
where
	NOT EXISTS( SELECT * FROM dbo.G_PROV1 GG1
								INNER JOIN dbo.G_PROV2 GG2 ON GG2.LINK_UP = GG1.LINK 
								INNER JOIN dbo.G_PROV_AP GGAP ON GGAP.LINK_UP = GG2.LINK
				WHERE GG1.LINK_UP = GG.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.[XA_CREATE_PROC_CLR_DOCUMENTS]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[XA_CREATE_PROC_CLR_DOCUMENTS]

GO
CREATE PROCEDURE dbo.XA_CREATE_PROC_CLR_DOCUMENTS
AS

BEGIN

declare
	@FUNC_SCRIPT VARCHAR(8000),
	@err int


SET @FUNC_SCRIPT = 'IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N''dbo.[CLR_DOCUMENTS]'') AND OBJECTPROPERTY(id,N''IsProcedure'') = 1)
DROP PROCEDURE dbo.[CLR_DOCUMENTS]'

EXEC(@FUNC_SCRIPT)

CREATE TABLE #SCRIPT(ORD INT IDENTITY(1,1), TXT VARCHAR(8000), TAB VARCHAR(256))	

INSERT INTO #SCRIPT (TXT)
SELECT 'CREATE  PROCEDURE dbo.[CLR_DOCUMENTS] (@DATE_DOC DATETIME)
--Сгенерировано скриптом XA_CREATE_PROC_CLR_DOCUMENTS
--Процедура удаляет документы задачи Дело-КС старше даты @DATE_DOC по @DATE_DOC включительно
AS
'

INSERT INTO #SCRIPT (TXT) VALUES ('--Линки удаляемых документов')

INSERT INTO #SCRIPT (TXT)
SELECT '
IF OBJECT_ID (''TEMPDB..#LINKS'',''U'') IS NOT NULL 
	DROP TABLE #LINKS

CREATE TABLE #LINKS (LINK INT)

INSERT INTO #LINKS (LINK)
SELECT LINK FROM dbo.DOCUMENTS WHERE DATE_DOC < (@DATE_DOC + 1)
'

INSERT INTO #SCRIPT (TXT) VALUES ('
--Удаление данных документов
')

;WITH 
 tree (fkeyid, F_COL, REF, C, CnstIsDisabled, CnstIsDeleteCascade, COL)
 AS (
	select
		A.fkeyid,
		quotename(E.Name),
		CONVERT( VARCHAR(8000), 'dbo.' + object_name(A.rkeyid) + ' INNER JOIN dbo.' + object_name(A.fkeyid) + ' ON dbo.' + object_name(A.fkeyid) + '.' + quotename(E.Name) + '=dbo.' + object_name(A.rkeyid) + '.' + quotename(C.Name))
		,1
		,OBJECTPROPERTY(A.constid, 'CnstIsDisabled')
		,OBJECTPROPERTY(A.constid, 'CnstIsDeleteCascade')
		,'dbo.' + object_name(A.rkeyid) + '.' + quotename(C.Name)
	from sysreferences A, syscolumns C, syscolumns E
	where A.rkey1=C.colid and A.rkeyid=C.id 
		and A.fkey1=E.colid and A.fkeyid=E.id 
		AND object_name(A.rkeyid) NOT LIKE 'R%' 
		AND Object_Name(A.fkeyid) NOT LIKE 'R%' 
		AND object_name(A.rkeyid) NOT IN ('S_OBJECTS')
		AND object_name(A.rkeyid) <> Object_Name(A.fkeyid)	
		AND object_name(A.rkeyid) = 'DOCUMENTS'
   UNION ALL
	select
		A.fkeyid,
		quotename(E.Name),
		CONVERT( VARCHAR(8000),  T.REF + ' INNER JOIN dbo.' + object_name(A.fkeyid) + ' ON dbo.' + object_name(A.fkeyid) + '.' + quotename(E.Name) + '=dbo.' + object_name(A.rkeyid) + '.' + quotename(C.Name))
		,T.C + 1
		,OBJECTPROPERTY(A.constid, 'CnstIsDisabled')
		,OBJECTPROPERTY(A.constid, 'CnstIsDeleteCascade')
		,T.col
	from 
		sysreferences A 
		INNER JOIN syscolumns C ON A.rkey1=C.colid and A.rkeyid=C.id
		INNER JOIN syscolumns E ON A.fkey1=E.colid and A.fkeyid=E.id
		INNER JOIN tree T ON T.fkeyid = A.rkeyid
	where 
		object_name(A.rkeyid) NOT LIKE 'R%' 
		AND Object_Name(A.fkeyid) NOT LIKE 'R%' 
		AND object_name(A.rkeyid) NOT IN ('S_OBJECTS')
		AND object_name(A.rkeyid) <> Object_Name(A.fkeyid)	
		AND object_name(A.fkeyid) <> 'DOCUMENTS'	
		AND T.C <= 10 --Уровень рекурсии
   ) 

INSERT INTO #SCRIPT (TXT, TAB)
SELECT 
'DELETE dbo.' + object_name(fkeyid) + CHAR(13) + CHAR(10)
+ ' FROM ' + REF +  CHAR(13) + CHAR(10)
+ ' WHERE EXISTS (SELECT * FROM #LINKS L WHERE ' + COL + ' = L.LINK)'  + CHAR(13) + CHAR(10) 
,object_name(fkeyid)

FROM tree
ORDER BY C DESC

INSERT INTO #SCRIPT (TXT)
SELECT ' DELETE FROM dbo.DOCUMENTS WHERE EXISTS (SELECT * FROM #LINKS L WHERE dbo.DOCUMENTS.[LINK] = L.LINK)'  + CHAR(13) + CHAR(10) 

INSERT INTO #SCRIPT (TXT)

SELECT '
IF OBJECT_ID (''TEMPDB..#LINKS'',''U'') IS NOT NULL 
	DROP TABLE #LINKS
'

SELECT TXT FROM #SCRIPT ORDER BY ORD

exec @err = dbo.ssp_execresultset 'SELECT TXT FROM #SCRIPT ORDER BY ORD'


SET @FUNC_SCRIPT = 'GRANT EXECUTE ON dbo.[CLR_DOCUMENTS] TO PUBLIC'

EXEC (@FUNC_SCRIPT)

SET @FUNC_SCRIPT = 'dbo.U_UPDATE_SCRIPT_PROPERTY ''CLR_DOCUMENTS'', ''EXECUTE dbo.XA_CREATE_PROC_CLR_DOCUMENTS'''

EXEC (@FUNC_SCRIPT)

END
GO
	

GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SA_CREATE_PP_BY_VEDOM]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_CREATE_PP_BY_VEDOM]

GO

CREATE PROCEDURE [dbo].[SA_CREATE_PP_BY_VEDOM] 
			@LINK_PP INT OUTPUT,
			@LINK_VEDOM INT,
			@DATE_DOC DATETIME

AS BEGIN

---
Set @LINK_PP = Coalesce((SELECT TOP 1 R.LINK_RKO 
						FROM dbo.sdoc_vedom_rko R
							INNER JOIN dbo.G_PROV G ON R.LINK_RKO = G.LINK
							INNER JOIN dbo.S_OBJECTS O ON O.LINK = G.[OBJECT]
						WHERE 
							O.CODE IN ('DOCUMENTS_RKO', 'DOCUMENTS_PAY', 'BB_ZAYAVKA_KR')
							AND
							LINK_vedom = @LINK_VEDOM),0)

IF @LINK_PP <> 0 BEGIN

	Select R.LINK_RKO, R.COMMENT from dbo.sdoc_vedom_rko R
			INNER JOIN dbo.G_PROV G ON R.LINK_RKO = G.LINK
			INNER JOIN dbo.S_OBJECTS O ON O.LINK = G.[OBJECT]
	where 
		O.CODE IN ('DOCUMENTS_RKO', 'DOCUMENTS_PAY', 'BB_ZAYAVKA_KR') 
		AND
		R.LINK_VEDOM = @LINK_VEDOM
	
	RETURN 0
END

/*Очистить старые сообщения об ошибках*/
delete from SAL_WORNINGS WHERE SID = SUSER_SID() AND TASK ='SALARY'

DECLARE 
	@NUM_PP 	VARCHAR(25),
	@NUM_VEDOM	VARCHAR(20),
	@DATE_VEDOM  	DATETIME,
	@SUMMA_PP	numeric(19,2),
	@DEP_LINK	INT,
	@var_EKR_LINK_adv	INT,
	@REF_EMPL	INT,
	@Osnovanie VARCHAR(254),
	@Add_text VARCHAR(254),
	@link_pay INT,
	@TYP_PAYMENT TINYINT,
	@LINK_CARD INT,
	@pTARGETTEXT     VARCHAR(1000),
	@Cur CURSOR, 
	@CUR_F CURSOR,
	@SUM_PROV NUMERIC(18,2), 
	@ORDER INT, 
	@Account1 INT, 
	@Account2 INT,	
	@HOZ_OPER INT, 
	@P1 FLOAT, 
	@P2 FLOAT, 
	@SGU INT,
	@LINK_KBK INT, 
	@LINK_KAU INT, 
	@LINK_DOP_KL INT, 
	@USER_ACC VARCHAR(4), 
	@CODE_SFIN VARCHAR(20), 
	@Fin_Source CHAR(1),
	@LINK_EKR INT,
	@MONTH_BASE INT,
	@YEAR_BASE INT,
	@ACC_CODE VARCHAR(20),
	@UIN VARCHAR(20)
	

DECLARE @trancount INT, @ERROR as INT

CREATE TABLE #tmp (CODE VARCHAR(254), [TNAME] VARCHAR(254), LINK INT, [ANAME] VARCHAR(254), REF_LINK_B INT, REF_LINK_K INT)

DECLARE @iCreatePP INT
SELECT @iCreatePP = dbo.sa_get_option_by_code('XB_NASTR_ZAYAVKA_KR_OR_PP')

/*Определим шаблон с параметрами*/
DECLARE @SHABLON_LINK INT, @OBJ_SNAME VARCHAR(10)
IF @iCreatePP = 0
	SELECT	@SHABLON_LINK = dbo.sa_get_option_by_code('VEDOM_OPTIONS_OPT9'),
			@OBJ_SNAME = 'ПП'
ELSE
	SELECT	@SHABLON_LINK = dbo.sa_get_option_by_code('VEDOM_OPTIONS_OPT15'),
			@OBJ_SNAME = 'ЗКР'

---
IF NOT EXISTS (SELECT * FROM G_PROV WHERE LINK = @SHABLON_LINK)
BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление зарплаты на карточки ',
	'Не указан шаблон ' + @OBJ_SNAME + ' в настройках ведомости на выплату, или ' + @OBJ_SNAME + ' , указанная в качестве шаблона удалена.',
	'Укажите в настройках шаблон.',
	'SALARY'
	GOTO DO_END
END

---
DECLARE
	@pKIND           CHAR(50),
	@pS_LINK         INT,		
	@pS_ACC_LINK     INT,
	@pD_LINK         INT,		
	@pD_ACC_LINK     INT,
	@pORDER          CHAR(1),
	@pPAYKIND        CHAR(5),
	@pREASON         CHAR(5),
	@pSBANK_LINK     INT,	
	@pDBANK_LINK     INT,
	@pNDSKIND        VARCHAR(100),
	@pNDS            INT,
	@pBK_IN_TGT      tinyint,
	@pPRINT_KPP      tinyint,
	@pNDS_LINK       INT,
	@pDOG_LINK       INT,
	--
	@AVANSE TINYINT,
	@SHORT BIT,
	@BO_NUM char(10),
	@NDS_SUM NUMERIC(18,2)	


IF @iCreatePP = 0
	--Реквизиты ПП
	SELECT  @pKIND = PP.KIND,
		@pD_LINK = PP.D_LINK,
		@pD_ACC_LINK = PP.D_ACC_LINK,
		@pORDER = PP.[ORDER],
		@pPAYKIND = PP.PAYKIND,
		@pREASON = PP.REASON,
		@pSBANK_LINK = PP.SBANK_LINK,		
		@pDBANK_LINK = PP.DBANK_LINK,		
		@pNDSKIND = PP.NDSKIND,	
		@pNDS = PP.NDS,
		@pBK_IN_TGT = PP.BK_IN_TGT,
		@pPRINT_KPP = PP.PRINT_KPP,
		@pNDS_LINK = PP.NDS_LINK,
		@pDOG_LINK = PP.DOG_LINK,
		@pTARGETTEXT = RTRIM(LTRIM(PP.TARGETTEXT)),
		@UIN = ISNULL(ppA.UIN_CODE,'')
	FROM dbo.DOCUMENTS_PAY PP
		LEFT JOIN dbo.DOCUMENTS_PAY_ADD PPA on PP.LINK = PPA.LINK
	WHERE PP.LINK = @SHABLON_LINK
ELSE
	SELECT  
		@AVANSE = ISNULL(AVANSE,0), --Авансовый платеж 
		@pKIND = KIND, --Вид платежа
		@pD_LINK = KOR_LINK, -- Получатель
		@pD_ACC_LINK = KOR_ACC_LINK, --Номер счета получателя 
		@pORDER = [ORDER], --Очередность платежа     
		@pNDS = NDS, --Процент НДС  
		@pNDS_LINK = NDS_LINK, --Шаблон НДС  
--		@SROK 		= SROK, --Срок платежа 
		@SHORT = ISNULL(SHORT,0), -- Сокращенная форма заявки
		@pTARGETTEXT = RTRIM(LTRIM(TARGETTEXT)), --Назначение платежа,
		@BO_NUM = ISNULL(BO_NUM,''),
		@UIN = ISNULL(UIN_CODE,'')
	FROM dbo.BB_ZAYAVKA_KR WHERE LINK = @SHABLON_LINK		

-- данные из ведомости
SELECT 	
	@DATE_VEDOM = CASE WHEN dbo.SA_GET_OPTION_BY_CODE('VEDOM_OPTIONS_OPT11') = 1 THEN dbo.DateEndOfMonth( dbo.ConvertDMY2Date(1, MONTH_BASE, YEAR_BASE)) ELSE [DATE] END,
	@NUM_VEDOM = NUMBER,
	@MONTH_BASE = MONTH_BASE,
	@YEAR_BASE = YEAR_BASE,
	@DEP_LINK=LINK_DEP,
	@REF_EMPL=REF_EMPL,
	@TYP_PAYMENT = TYP_PAYMENT,
	@Add_Text = 'Ведомость №' + RTRIM(LTRIM(COALESCE(NUMBER,''))) + ' от ' + COALESCE(convert(VARCHAR(10),[DATE], 104),''),
	@link_pay = REF_PAY,
	@LINK_CARD = CARD_LINK,
	@pTARGETTEXT = @pTARGETTEXT + case when dbo.sa_get_option_by_code('SALARY_OPTIONS_OPT9') = 1 then CASE WHEN LEN(@pTARGETTEXT) > 0 THEN ', ' else '' end + [NAME_PAY] ELSE '' END 
FROM 
	(
	SELECT [DATE], MONTH_BASE, YEAR_BASE, NUMBER, LINK_DEP, REF_EMPL, TYP_PAYMENT, REF_PAY, CARD_LINK, NAME_PAY FROM dbo.DOCUMENTS_DED_PR V1 WHERE V1.LINK = @LINK_VEDOM
	UNION ALL
	SELECT [DATE], MONTH_BASE, YEAR_BASE, NUMBER, LINK_DEP, REF_EMPL, TYP_PAYMENT, REF_PAY, CARD_LINK, NAME_PAY FROM dbo.DOCUMENTS_DED_PR_DGH V2 WHERE V2.LINK = @LINK_VEDOM
	) V

--
SET @DATE_VEDOM = CASE WHEN COALESCE(@DATE_DOC,@DATE_VEDOM) > @DATE_VEDOM THEN @DATE_DOC ELSE @DATE_VEDOM END	

DECLARE	@DATE_PROV datetime
SET @DATE_PROV = CASE WHEN dbo.sa_get_option_by_code('SALARY_OPTIONS_OPT12') = 1 THEN @DATE_VEDOM ELSE NULL END

--Проверка рабочего периода
IF @DATE_PROV is not null and not exists(Select * from admin_info Where @DATE_PROV BETWEEN BEGINDATE AND ENDDATE)
BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление зарплаты на карточки по документу ' + @Add_Text,
		'Программа формирует дату проводки, равную дате платежки. Но эта дата не попадает в период редактирования!',
		'Отключите в общих настройках по зарплате опцию "В бух. документе автоматически ставить дату" проводки или измените период редактирования.',
		'SALARY'
	GOTO DO_END
END


--Платежка только если указана пластиковая карточка
IF COALESCE(@LINK_CARD,0) = 0
	RETURN 0

IF NOT EXISTS (SELECT * FROM dbo.DEPARTMENT_ACCOUNTS T2 WHERE LINK_UP = @DEP_LINK AND [TYPE] IN (1,2,4) ) BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление зарплаты на карточки ',
	'Не указаны счета в настройках организации.',
	'Требуется указать счета в настройках организации.',
	'SALARY'
	RETURN 0		
END

----
DECLARE @CODE_OBJECT VARCHAR(254)
SET @CODE_OBJECT = (SELECT O.CODE FROM SDOC D INNER JOIN dbo.S_OBJECTS O ON D.OBJECT = O.LINK WHERE D.LINK = @LINK_VEDOM)

DECLARE @LINK_EKR_DEFAULT INT
SELECT @LINK_EKR_DEFAULT = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = CASE WHEN RTRIM(LTRIM(@CODE_OBJECT)) = 'DOCUMENTS_DED_PAYROLL' THEN '211' ELSE '226' END

---
Declare @ACC_304_03 VARCHAR(10)
SET @ACC_304_03 = (SELECT TOP 1 RTRIM(LTRIM(VALUE)) FROM dbo.S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SALARY_OPTIONS_OPT2'))) AND SID IS NULL)

IF RTRIM(LTRIM(COALESCE(@ACC_304_03,''))) IN ('','.') BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление зарплаты на карточки ',
		'Не указан счет для расчетов по удержаниям в общих настройках по зарплате.',
		'Укажите счет для расчетов по удержаниям в общих настройках по зарплате.',
		'SALARY'
	RETURN 0		
END	

---
DECLARE @LINK_ORG int, @LINK_ACC int, @LINK_SFIN INT
DECLARE @KD_CODE_ACC VARCHAR(6), @KD_FULL_CODE_ACC VARCHAR(13), @ACC_NAME VARCHAR(15)

DECLARE @BUH_TYPE TINYINT
SET @BUH_TYPE = ISNULL((SELECT BUH_TYPE FROM DBO.DEPARTMENTS WHERE LINK = @DEP_LINK),0)

DECLARE @WORKMODE157N INT
SET @WORKMODE157N = ISNULL((SELECT dbo.XK_GET_NASTR_INT ('XK_WORKMODE157N')),0)
--Если не выполнен переход, то считаем, что тип организации не определён!
SET @BUH_TYPE = CASE WHEN @WORKMODE157N = 0 THEN 0 ELSE @BUH_TYPE END

--IF @BUH_TYPE = 0 BEGIN
--	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
--	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление зарплаты на карточки ',
--		'Не определён вид государственного учреждения.',
--		'В реквизитах текущей организации установите реквизит "Вид государственного учреждения".',
--		'SALARY'
--	RETURN 0		
--END

IF NOT EXISTS (SELECT * FROM DBO.SAL_NASTR_PROV WHERE TYPE_OPER = 1 AND TYPE_DEP = @BUH_TYPE) BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление зарплаты на карточки ',
		'Не определён счет для выбытия ср-в с лиц. либо расч. счета.',
		'В настройках формирования проводок по зарплате укажите счёта в справочнике "Счета для выбытия ср-в с лиц. либо расч. счета" для данного вида гос. учреждения".',
		'SALARY'
	RETURN 0		
END

SET @CUR_F = CURSOR FORWARD_ONLY
FOR 
	SELECT F.KBK, COALESCE(CAST (F.SOURCE as CHAR(1)),'') ,
		T.LINK_ORG,
		T.LINK_ACC,
		F.LINK
	FROM dbo.CALCULATE_JURNAL CJ
		LEFT JOIN  dbo.SAL_SFIN F ON F.LINK = CJ.LINK_VKR
		LEFT JOIN TAX2_APP T on CJ.LINK_PAYS = T.link_up
	WHERE CJ.LINK_DOC = @LINK_VEDOM
	GROUP BY F.KBK, F.SOURCE, T.LINK_ORG, T.LINK_ACC, F.LINK
	HAVING SUM(CJ.SUMMA) <> 0
	ORDER BY F.KBK
OPEN @CUR_F
FETCH NEXT FROM @CUR_F INTO @LINK_KBK, @Fin_Source, @LINK_ORG, @LINK_ACC, @LINK_SFIN
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN	--Формирование расходников для каждого КБК по отдельности

		SET @trancount = @@TRANCOUNT
		SET IMPLICIT_TRANSACTIONS ON
		BEGIN TRAN 
		COMMIT TRAN

		IF @ERROR <> 0
			RETURN @ERROR


		IF COALESCE(@LINK_ORG,0) = 0 BEGIN 
			ROLLBACK
			SET IMPLICIT_TRANSACTIONS OFF
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформированы проводки на перечисление зарплаты на карточки',
				'В настройках удержания, указанного в ведомости не указан получатель',
				'Укажите получателя в настройках удержания ',
				'SALARY'
			GOTO DO_NEXT
		END

		IF COALESCE(@LINK_ACC,0) = 0 BEGIN 
			ROLLBACK
			SET IMPLICIT_TRANSACTIONS OFF
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформированы проводки на перечисление зарплаты на карточки',
				'В настройках удержания, указанного в ведомости не указан счет получателя',
				'Укажите счет получателя в настройках удержания ',
				'SALARY'
			GOTO DO_NEXT
		END

		--------------------
		SELECT TOP 1 @Osnovanie = (case COALESCE(@TYP_PAYMENT,0) WHEN 1 THEN 'Перечисление з/пл' WHEN 2 THEN 'Перечисление аванса' ELSE 'Перечисление межрасч. выпл.' end) +
			' за ' + coalesce((SELECT TOP 1 MON FROM dbo.months WHERE NUM = @MONTH_BASE),'') + ',' + CONVERT(VARCHAR(4),coalesce(@YEAR_BASE,0)) + 'г.' +
			 ' по КБК ' + RTRIM(LTRIM(COALESCE(KBK.[CODE],''))) + ' ' + ISNULL((SELECT TOP 1 LTRIM(RTRIM(NAME)) FROM DBO.BB_FIN_SOURCE WHERE CODE = @Fin_Source),'')  + ', Вед.№' + RTRIM(LTRIM(COALESCE(@NUM_VEDOM,''))) + ' от ' + COALESCE(convert(VARCHAR(10),@DATE_VEDOM, 104),'')
		FROM dbo.KL_KBK KBK WHERE KBK.LINK = @LINK_KBK
		
		SET @ORDER = 0

		-- определим максимальный номер
		Set @NUM_PP = NULL
		IF @iCreatePP = 0		
			exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'DOCUMENTS_PAY', @NUM_PP output, @DEP_LINK
		ELSE
			exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'BB_ZAYAVKA_KR', @NUM_PP output, @DEP_LINK			

		--		
		SET @KD_CODE_ACC = (SELECT TOP 1 CODE_ACC FROM DBO.SAL_NASTR_PROV WHERE TYPE_OPER = 1 AND TYPE_DEP = @BUH_TYPE AND TYPE_FUNC = @Fin_Source)

		IF REPLACE(LTRIM(RTRIM(ISNULL(@KD_CODE_ACC,''))),'.','') = '' BEGIN
			ROLLBACK
			SET IMPLICIT_TRANSACTIONS OFF		
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформированы ' + @OBJ_SNAME + ' на перечисление зарплаты на карточки ',
				'Не задан счет для выбытия ср-в с лиц. либо расч. счета для вида организации ' 
				+ ISNULL((SELECT TOP 1 BT_NAME FROM DBO.DICTIONARY_BUH_TYPE WHERE BUH_TYPE = @BUH_TYPE),'')
				+ ' для вида деятельности ' + ISNULL((SELECT TOP 1 NAME FROM DBO.BB_FIN_SOURCE WHERE CODE = @Fin_Source),''),
				'В настройках всех режимов задачи выберите раздел "Настройка счетов для проводок по зарплате" и укажите требуемый счёт в настройке "Счет для выбытия ср-в с лиц. либо расч. счета".',
				'SALARY'
			RETURN 0		
		END		

		SET @Account2 = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @KD_CODE_ACC) AND cUser = RTRIM(LTRIM(COALESCE(@USER_ACC,''))))
		SET @KD_FULL_CODE_ACC = @Fin_Source + '.' + @KD_CODE_ACC + CASE WHEN RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> '' THEN '/' + RTRIM(LTRIM(COALESCE(@USER_ACC,''))) ELSE '' END

		IF COALESCE(@Account2,0) = 0 BEGIN 
			ROLLBACK
			SET IMPLICIT_TRANSACTIONS OFF
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформированы проводки на перечисление зарплаты на карточки',
				'В плане счетов не найден счет ' + @KD_FULL_CODE_ACC,
				'Добавьте в план счетов счет ' + @KD_FULL_CODE_ACC,
				'SALARY'
			GOTO DO_NEXT
		END
		
		SET @pS_ACC_LINK = dbo.SA_GET_DEP_ACC(@DEP_LINK, @Account2, @LINK_SFIN, DEFAULT)
		
		IF COALESCE(@pS_ACC_LINK,0) = 0 BEGIN
			ROLLBACK
			SET IMPLICIT_TRANSACTIONS OFF
			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			select 'Не сформированы проводки на перечисление зарплаты на карточки',
				'В настройках реквизитов организации на вкладке "счета" не найден ' + @ACC_NAME + ' счет.',
				'Добавьте ' + @ACC_NAME + ' счет в настройках реквизитов организации на вкладке "счета".',
				'SALARY'
			GOTO DO_NEXT
		END		

		-- Сохраняем ПП 
		SET @LINK_PP = NULL
		SET @pD_ACC_LINK = @LINK_ACC--COALESCE(@LINK_ACC,@pD_ACC_LINK)
		SET @pD_LINK = @LINK_ORG--COALESCE(@LINK_ORG,@pD_LINK)
		
		IF @iCreatePP = 0 
		BEGIN
			EXEC dbo.X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_VEDOM, @DATE_PROV, 0, '',
				@pKIND, @pS_LINK, @pS_ACC_LINK, @pD_LINK, @pD_ACC_LINK,
				@DATE_VEDOM, @pORDER, @pPAYKIND, @pREASON,
				@pTARGETTEXT, @pNDS, @pBK_IN_TGT, @pPRINT_KPP,
				@pNDS_LINK, 'DOCUMENTS_PAY'
		END		 
		ELSE
		BEGIN
			EXEC dbo.X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_VEDOM, @DATE_PROV, 0, '',
				@pKIND, @pS_LINK, @pS_ACC_LINK, @pD_LINK, @pD_ACC_LINK,
				@DATE_VEDOM, @pORDER, NULL, DEFAULT, 
				@pTARGETTEXT, @pNDS, @pBK_IN_TGT, NULL,
				@pNDS_LINK, 'BB_ZAYAVKA_KR'

			SET @NDS_SUM = ISNULL(@SUMMA_PP * ISNULL(@pNDS,0) / 100 ,0)

			EXEC dbo.X_SAVE_DOCUMENTS_PAY2 @LINK_PP, NULL, @BO_NUM, NULL, @AVANSE, @NDS_SUM, @SHORT

		END					

		INSERT INTO dbo.sdoc_vedom_rko (LINK_VEDOM, LINK_RKO, COMMENT) VALUES(@LINK_VEDOM, @LINK_PP, @Osnovanie)

		SET @Cur = CURSOR FORWARD_ONLY
		FOR 
			-- Данные для проводок
			SELECT 	COALESCE(JC.LINK_EKR,@LINK_EKR_DEFAULT), 
				LINK_KAU = F.KAU,
				LINK_DOP_KL = F.DOP_KL,
				USER_ACC = F.USER_ACC,
				CODE_SFIN = F.CODE,
				SUMMA= SUM(JC.SUMMA) 
			FROM	
				dbo.CALCULATE_JURNAL JC INNER JOIN dbo.SAL_SFIN F ON F.LINK = JC.LINK_VKR
			WHERE   
				JC.LINK_DOC = @LINK_VEDOM AND F.KBK = @LINK_KBK AND COALESCE(CAST (F.SOURCE as CHAR(1)),'') = @Fin_Source
			GROUP BY 
				JC.LINK_EKR, JC.LINK_PAYS, F.KBK, F.KAU, F.DOP_KL, F.USER_ACC, F.CODE
			HAVING 
				SUM(JC.SUMMA) <> 0

		OPEN @Cur
		FETCH NEXT FROM @Cur INTO @LINK_EKR, @LINK_KAU, @LINK_DOP_KL, @USER_ACC, @CODE_SFIN, @SUM_PROV
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN
				IF COALESCE(@SUM_PROV,0) >= 0 BEGIN
						
					SET @P1 = NULL

					exec X_UPDATE_G_PROV1 @P1 output, @LINK_PP, NULL, @Osnovanie, 1
			
					Set @ORDER = @ORDER + 1
					--Найдем счет с пользовательским субсчетом

					IF RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> ''
						Set @Account1 = (SELECT TOP 1 link FROM dbo.S_ACCOUNTS WHERE cSource = RTRIM(LTRIM(@Fin_Source)) and cSinth = RTRIM(dbo.SA_GET_WORD_NUM(@ACC_304_03,1,'.')) and cAnalit = RTRIM(dbo.SA_GET_WORD_NUM(@ACC_304_03,2,'.')) AND cUser = RTRIM(LTRIM(COALESCE(@USER_ACC,''))))
					ELSE 
						Set @Account1 = (SELECT TOP 1 link FROM dbo.S_ACCOUNTS WHERE cSource = RTRIM(LTRIM(@Fin_Source)) and cSinth = RTRIM(dbo.SA_GET_WORD_NUM(@ACC_304_03,1,'.')) and cAnalit = RTRIM(dbo.SA_GET_WORD_NUM(@ACC_304_03,2,'.')) )

					--Если не нашли, то ошибка!
					IF COALESCE(@Account1,0) = 0 BEGIN 
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'В плане счетов не найден счет ' + @Fin_Source + '.' + RTRIM(dbo.SA_GET_WORD_NUM(@ACC_304_03,1,'.')) + '.' + RTRIM(dbo.SA_GET_WORD_NUM(@ACC_304_03,2,'.')) + + CASE WHEN RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> '' THEN '/' + RTRIM(LTRIM(COALESCE(@USER_ACC,''))) else '' END,
							'Добавьте в план счетов такой счет.',
							'SALARY'
						GOTO DO_NEXT
					END

					---
					SET @ACC_CODE = (select top 1 A2.CODE from dbo.S_ACCOUNTS A1 inner join dbo.S_ACCOUNTS A2 on A1.link_self = A2.link
						WHERE A2.LINK = @Account1 and A2.cSource <> '')

					IF  RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) <> '' AND RTRIM(LTRIM(COALESCE(@USER_ACC,''))) = '' BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'У источника финансирования ' + RTRIM(LTRIM(@CODE_SFIN)) + ' не указан пользовательский субсчет, однако у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' есть субсчета',
							'Укажите пользовательский субсчет, либо уберите в плане счетов субсчет у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' с помощью слияния',
							'SALARY'
						GOTO DO_NEXT
					END

					---
					SET @ACC_CODE = (select top 1 A2.CODE from dbo.S_ACCOUNTS A1 inner join dbo.S_ACCOUNTS A2 on A1.link_self = A2.link
						WHERE A2.LINK = (SELECT TOP 1 LINK FROM dbo.S_ACCOUNTS where cSource = @Fin_Source AND (cSinth + '.' + cAnalit = @KD_CODE_ACC) ) and A2.cSource <> '')

					IF  RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) <> '' AND RTRIM(LTRIM(COALESCE(@USER_ACC,''))) = '' BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
							'У источника финансирования ' + RTRIM(LTRIM(@CODE_SFIN)) + ' не указан пользовательский субсчет, однако у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' есть субсчета',
							'Укажите пользовательский субсчет, либо уберите в плане счетов субсчет у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' с помощью слияния',
							'SALARY'
						GOTO DO_NEXT
					END
	
					IF COALESCE(@Account1,0) > 0 AND COALESCE(@Account2,0) > 0 BEGIN

						SET @HOZ_OPER = (SELECT TOP 1 LINK FROM dbo.BX_BPROV_VIBOR_ECON_OPER(@Account1,@Account2))
						IF COALESCE(@HOZ_OPER,0) = 0 BEGIN
							ROLLBACK
							SET IMPLICIT_TRANSACTIONS OFF
							INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
								'Не найдено подходящей хоз. операции для проводки ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account1) + '-' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account2),
								'Вероятно в общих настройках по зарплате указан неправильно счет для выбытия бюдж. или внебюдж средств с лицевого либо расчетного счета',
								'SALARY'
							GOTO DO_NEXT
						END	
				
						set @P2 = null
						exec X_UPDATE_G_PROV2 @P2 output, @P1, NULL, @SUM_PROV, 0, 0, @Osnovanie, @HOZ_OPER, @ORDER
						
						UPDATE dbo.G_PROV
						SET SUMMA = SUMMA + @SUM_PROV
						WHERE LINK = @LINK_PP
			
						SET @SGU = (SELECT TOP 1 LINK_SGU FROM S_ACCOUNTS_SGU SGU INNER JOIN KOSGU ON SGU.LINK_SGU = KOSGU.LINK WHERE DB_KR = 0 AND ACCOUNT = @Account1)
						IF EXISTS (SELECT p_KASSA FROM dbo.s_accounts WHERE LINK = @Account1 AND p_KASSA = 1)
							SET @SGU = @LINK_EKR
		
						IF COALESCE(@SGU,0) = 0 BEGIN
							ROLLBACK
							SET IMPLICIT_TRANSACTIONS OFF
							INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
								'У счета ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account1) + ' не задано СГУ',
								'Укажите СГУ в настройках счета в плане счетов',
								'SALARY'
							GOTO DO_NEXT
						END	
						exec X_UPDATE_G_PROV_AP @P2, 0, @Account1, @LINK_KBK, @LINK_EKR, @pD_LINK, NULL, NULL, NULL, NULL, @LINK_KAU, @pD_ACC_LINK, NULL, NULL, NULL, @LINK_DOP_KL, NULL, @SGU
		
						SET @SGU = (SELECT TOP 1 LINK_SGU FROM S_ACCOUNTS_SGU SGU INNER JOIN KOSGU ON SGU.LINK_SGU = KOSGU.LINK WHERE DB_KR = 1 AND ACCOUNT = @Account2)
						IF EXISTS (SELECT p_KASSA FROM dbo.s_accounts WHERE LINK = @Account2 AND p_KASSA = 1)
							SET @SGU = @LINK_EKR
		
						IF COALESCE(@SGU,0) = 0 BEGIN
							ROLLBACK
							SET IMPLICIT_TRANSACTIONS OFF
							INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформировано ' + @OBJ_SNAME + ' ' + @Osnovanie,
								'У счета ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account2) + ' не задано СГУ',
								'Укажите СГУ в настройках счета в плане счетов',
								'SALARY'
							GOTO DO_NEXT
						END	
						exec X_UPDATE_G_PROV_AP @P2, 1, @Account2, @LINK_KBK, @LINK_EKR, @DEP_LINK, NULL, NULL, NULL, NULL, @LINK_KAU, @pS_ACC_LINK, NULL, NULL, NULL, @LINK_DOP_KL, NULL, @SGU
					END
		
				END
			END

			IF @iCreatePP = 1
				EXEC dbo.BB_ZAYAVKA_KR_CREATE_TABLE @LINK_PP
			
			FETCH NEXT FROM @Cur INTO @LINK_EKR, @LINK_KAU, @LINK_DOP_KL, @USER_ACC, @CODE_SFIN, @SUM_PROV
		END
		
		CLOSE @Cur
		DEALLOCATE @Cur

		IF @@TRANCOUNT > @trancount BEGIN
			COMMIT TRAN
			SET IMPLICIT_TRANSACTIONS OFF
		END
		---Если надо, то сформировать БО
		DECLARE @TestBO tinyint
		exec @TestBO = dbo.XD_TEST_FORM_BO @LINK_PP 

		IF @TestBO = 0
		BEGIN
			create table #tProtocol1(txt varchar(1000), NEW_ROW tinyint, nSTATUS tinyint, nTAB tinyint, ord int identity(1,1))

			insert into #tProtocol1 (txt, NEW_ROW, nSTATUS, nTAB) 
			Exec dbo.XD_FORM_BO @LINK_PP

			IF EXISTS (SELECT * FROM #tProtocol1 WHERE nSTATUS >=1 )
				INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
				select 'Обнаружены замечания при формирование БО:', CASE WHEN nSTATUS = 1 THEN 'Предупреждение!' ELSE 'Ошибка!' END + SPACE(1) + LEFT(txt,240), 'Устраните замечания!', 'SALARY'
				FROM #tProtocol1	WHERE nSTATUS >= 1
			
			DROP TABLE #tProtocol1
				
		END				

	END

	DO_NEXT:

	FETCH NEXT FROM @CUR_F INTO @LINK_KBK, @Fin_Source, @LINK_ORG, @LINK_ACC, @LINK_SFIN
END

CLOSE @CUR_F
DEALLOCATE @CUR_F

exec X_SALDO_CommitChanges

DO_END:

Select LINK_RKO, COMMENT from dbo.sdoc_vedom_rko where LINK_VEDOM = @LINK_VEDOM

Return 0
END



GO


GRANT EXECUTE ON dbo.[SA_CREATE_PP_BY_VEDOM] TO PUBLIC

GO

GO

--AFTER CODE 27.10.2014
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXBD140101' 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','Информация из расчетных документов','TXBD140101',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_PP','cModelVer','KOD_UBP','bb_import_BD()',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Информация из расчетных документов',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_PP',
		PROC_DOP_PARAM   = 'cModelVer',
		PROG_SAVE   = 'bb_import_BD()',
		DEP_NAME   = 'KOD_UBP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FK',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'сылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','сылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,1,1,'NAME_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,0,0,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,0,0,'NAME_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BUDG_LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'BUDG_LEVEL','Уровень бюджета','STRING',1,1,0,1,'BUDG_LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'KOD_UBP','Код УБП','STRING',5,1,1,1,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Наименование УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'NAME_UBP','Наименование УБП','STRING',254,0,1,1,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'BD'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'BD',4,0,'Общая информация',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 0,
			NAME   = 'Общая информация',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер лицевого счета клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'LS','Номер лицевого счета клиента','STRING',11,0,0,0,'LS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Дата',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'DATE','Дата','DATE',0,0,0,0,'DATE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_OTCH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'GUID_OTCH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_OTCH'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'GUID_OTCH','Глобальный уникальный идентификатор','GUID',36,1,0,1,'GUID_OTCH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'KOD_DOC','Код документа','STRING',2,1,1,1,'KOD_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OTCH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Признак принад-лежности к про-межуточному отчёту',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'VID_OTCH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OTCH'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'VID_OTCH','Признак принад-лежности к про-межуточному отчёту','STRING',1,1,1,1,'VID_OTCH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Количество документов',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'KOL','Количество документов','NUMBER',5,1,1,1,'KOL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_TOTAL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Контрольная сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_TOTAL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_TOTAL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'SUM_TOTAL','Контрольная сумма','NUMBER2',0,0,1,1,'SUM_TOTAL','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'BDPD'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'BDPD',5,2,'Информация из расчетных до-кументов',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Информация из расчетных до-кументов',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= '№ платежного поручения',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NOM_PP','№ платежного поручения','STRING',10,0,1,1,'NOM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Дата платежного поручения',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'DATE_PP','Дата платежного поручения','DATE',0,1,1,1,'DATE_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Сумма платежного поручения',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'SUM_PP','Сумма платежного поручения','NUMBER2',0,1,1,1,'SUM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Вид платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'VID_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'VID_PL','Вид платежа','STRING',1,1,0,0,'VID_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP_IN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Поступило в банк платель-щика.',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PP_IN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP_IN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'DATE_PP_IN','Поступило в банк платель-щика.','DATE',0,0,0,0,'DATE_PP_IN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP_SPS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Дата списания со счета плательщика.',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PP_SPS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP_SPS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'DATE_PP_SPS','Дата списания со счета плательщика.','DATE',0,0,0,0,'DATE_PP_SPS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OPER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Вид операции.',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'VID_OPER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OPER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'VID_OPER','Вид операции.','STRING',2,1,0,0,'VID_OPER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'ИНН Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INN_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'INN_PAY','ИНН Плательщика','STRING',12,0,0,0,'INN_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'КПП Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KPP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'KPP_PAY','КПП Плательщика','STRING',9,1,0,0,'KPP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Наименование Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'CNAME_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'CNAME_PAY','Наименование Плательщика','STRING',160,0,0,0,'CNAME_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Расчетный счет Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'BS_PAY','Расчетный счет Плательщика','STRING',20,1,0,0,'BS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'БИК банка Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BIC_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'BIC_PAY','БИК банка Плательщика','STRING',9,1,0,0,'BIC_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Наименование банка Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BIC_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'NAME_BIC_PAY','Наименование банка Плательщика','STRING',160,0,0,0,'NAME_BIC_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Коррсчет банка Плательщика в РКЦ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_KS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'BS_KS_PAY','Коррсчет банка Плательщика в РКЦ','STRING',20,1,0,0,'BS_KS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'ИНН получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INN_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 16,'INN_RCP','ИНН получателя','STRING',12,0,0,0,'INN_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'КПП получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KPP_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'KPP_RCP','КПП получателя','STRING',9,0,0,0,'KPP_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Наименование получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 18,'NAME_RCP','Наименование получателя','STRING',160,0,0,0,'NAME_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Расчетный счет Получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 19,'BS_RCP','Расчетный счет Получателя','STRING',20,0,0,0,'BS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'БИК банка Получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 20,'BIC_RCP','БИК банка Получателя','STRING',9,1,0,0,'BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Наименование банка получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 21,'NAME_BIC_RCP','Наименование банка получателя','STRING',160,0,0,0,'NAME_BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Корсчет банка получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_KS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 22,'BS_KS_RCP','Корсчет банка получателя','STRING',20,1,0,0,'BS_KS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Срок платежа',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 23,'DATE_PAY','Срок платежа','DATE',0,0,0,0,'DATE_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Очередность платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ORDER_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 24,'ORDER_PAY','Очередность платежа','STRING',1,1,0,0,'ORDER_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'UIN_CODE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Уникальный идентификатор начисления (Код)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 25,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'UIN_CODE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'UIN_CODE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 25,'UIN_CODE','Уникальный идентификатор начисления (Код)','STRING',25,0,0,0,'UIN_CODE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 26,'PURPOSE','Назначение платежа','STRING',210,0,0,0,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'Статус составителя расчетного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PAYSTATUS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 27,'PAYSTATUS','Статус составителя расчетного документа','STRING',2,0,0,0,'PAYSTATUS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Код бюджетной классификации',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 28,'KBK','Код бюджетной классификации','STRING',20,1,0,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 29,
		NAME   		= 'Код ОКТМО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKATO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 29,'OKATO','Код ОКТМО','STRING',11,0,0,0,'OKATO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OSNPLAT')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 30,
		NAME   		= 'Показатель основания платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OSNPLAT',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OSNPLAT'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 30,'OSNPLAT','Показатель основания платежа','STRING',2,0,0,0,'OSNPLAT','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAL_PER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 31,
		NAME   		= 'Показатель налогового периода',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAL_PER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAL_PER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 31,'NAL_PER','Показатель налогового периода','STRING',10,0,0,0,'NAL_PER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'Показатель номера документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_DOK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 32,'NOM_DOK','Показатель номера документа','STRING',15,0,0,0,'NOM_DOK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 33,
		NAME   		= 'Показатель даты документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_DOK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 33,'DATE_DOK','Показатель даты документа','STRING',10,0,0,0,'DATE_DOK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 34,
		NAME   		= 'Тип платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 34,'TYPE_PL','Тип платежа','STRING',2,0,0,0,'TYPE_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PL_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 35,
		NAME   		= 'Номер частичного платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_PL_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PL_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 35,'NOM_PL_PO','Номер частичного платежа','STRING',3,0,0,0,'NOM_PL_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SHIFR_RD_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 36,
		NAME   		= 'Шифр платежно-го документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SHIFR_RD_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SHIFR_RD_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 36,'SHIFR_RD_PO','Шифр платежно-го документа','STRING',2,1,0,0,'SHIFR_RD_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_RD_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 37,
		NAME   		= 'Номер платежного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_RD_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_RD_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 37,'NOM_RD_PO','Номер платежного документа','STRING',3,0,0,0,'NOM_RD_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_RD_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 38,
		NAME   		= 'Дата платежного документа',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_RD_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_RD_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 38,'DATE_RD_PO','Дата платежного документа','DATE',0,0,0,0,'DATE_RD_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_OST_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 39,
		NAME   		= 'Сумма остатка платежа',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_OST_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_OST_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 39,'SUM_OST_PO','Сумма остатка платежа','NUMBER2',0,0,0,0,'SUM_OST_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OPER_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 40,
		NAME   		= 'Содержание опе-рации',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 16,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OPER_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OPER_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 40,'OPER_PO','Содержание опе-рации','STRING',16,0,0,0,'OPER_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_IN_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 41,
		NAME   		= 'Дата выписки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_IN_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_IN_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 41,'DATE_IN_TOFK','Дата выписки','DATE',0,0,0,0,'DATE_IN_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 42,
		NAME   		= 'Глобальный уни-кальный идентификатор',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 42,'GUID','Глобальный уни-кальный идентификатор','GUID',36,1,0,0,'GUID','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'BDPDST'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'BDPDST',6,2,'Строки платежного поручения по бюджетной классификации',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 6,
			ISONCE = 2,
			NAME   = 'Строки платежного поручения по бюджетной классификации',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код по КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KBK','Код по КБК','STRING',20,1,0,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'TYPE_KBK','Тип КБК','STRING',2,1,0,0,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код цели субсидии',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'ADD_KLASS','Код цели субсидии','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_BO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Номер бюджетного обязательства',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 16,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NUM_BO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_BO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NUM_BO','Номер бюджетного обязательства','STRING',16,1,0,0,'NUM_BO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ОКАТО')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'ОКТMО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ОКАТО',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ОКАТО'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'ОКАТО','ОКТMО','STRING',11,1,0,0,'ОКАТО','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'SUM','Сумма','NUMBER2',0,1,1,1,'SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DIR_SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Направление пла-тежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DIR_SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DIR_SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'DIR_SUM','Направление пла-тежа','STRING',1,1,1,1,'DIR_SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'MES_FIN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Месяц финансиро-вания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'MES_FIN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'MES_FIN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'MES_FIN','Месяц финансиро-вания','STRING',2,1,0,0,'MES_FIN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Резервное поле',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 40,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'REZERV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'REZERV','Резервное поле','STRING',40,0,0,0,'REZERV','',''
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXBD140701' 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','Информация из расчетных документов','TXBD140701',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_PP','cModelVer','KOD_UBP','bb_import_BD()',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Информация из расчетных документов',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_PP',
		PROC_DOP_PARAM   = 'cModelVer',
		PROG_SAVE   = 'bb_import_BD()',
		DEP_NAME   = 'KOD_UBP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FK',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'сылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','сылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,1,1,'NAME_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,0,0,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,0,0,'NAME_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BUDG_LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'BUDG_LEVEL','Уровень бюджета','STRING',1,1,0,1,'BUDG_LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'KOD_UBP','Код УБП','STRING',5,1,1,1,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Наименование УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'NAME_UBP','Наименование УБП','STRING',254,0,1,1,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'BD'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'BD',4,0,'Общая информация',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 0,
			NAME   = 'Общая информация',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер лицевого счета клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'LS','Номер лицевого счета клиента','STRING',11,0,0,0,'LS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Дата',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'DATE','Дата','DATE',0,0,0,0,'DATE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_OTCH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'GUID_OTCH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_OTCH'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'GUID_OTCH','Глобальный уникальный идентификатор','GUID',36,1,0,1,'GUID_OTCH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'KOD_DOC','Код документа','STRING',2,1,1,1,'KOD_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OTCH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Признак принад-лежности к про-межуточному отчёту',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'VID_OTCH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OTCH'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'VID_OTCH','Признак принад-лежности к про-межуточному отчёту','STRING',1,1,1,1,'VID_OTCH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Количество документов',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'KOL','Количество документов','NUMBER',5,1,1,1,'KOL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_TOTAL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Контрольная сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_TOTAL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_TOTAL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'SUM_TOTAL','Контрольная сумма','NUMBER2',0,0,1,1,'SUM_TOTAL','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'BDPD'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'BDPD',5,2,'Информация из расчетных до-кументов',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Информация из расчетных до-кументов',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= '№ платежного поручения',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NOM_PP','№ платежного поручения','STRING',10,0,1,1,'NOM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Дата платежного поручения',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'DATE_PP','Дата платежного поручения','DATE',0,1,1,1,'DATE_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Сумма платежного поручения',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'SUM_PP','Сумма платежного поручения','NUMBER2',0,1,1,1,'SUM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Вид платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'VID_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'VID_PL','Вид платежа','STRING',1,1,0,0,'VID_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP_IN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Поступило в банк платель-щика.',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PP_IN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP_IN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'DATE_PP_IN','Поступило в банк платель-щика.','DATE',0,0,0,0,'DATE_PP_IN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP_SPS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Дата списания со счета плательщика.',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PP_SPS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP_SPS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'DATE_PP_SPS','Дата списания со счета плательщика.','DATE',0,0,0,0,'DATE_PP_SPS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OPER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Вид операции.',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'VID_OPER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OPER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'VID_OPER','Вид операции.','STRING',2,1,0,0,'VID_OPER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'ИНН Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INN_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'INN_PAY','ИНН Плательщика','STRING',12,0,0,0,'INN_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'КПП Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KPP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'KPP_PAY','КПП Плательщика','STRING',9,1,0,0,'KPP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Наименование Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'CNAME_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CNAME_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'CNAME_PAY','Наименование Плательщика','STRING',160,0,0,0,'CNAME_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Расчетный счет Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'BS_PAY','Расчетный счет Плательщика','STRING',20,1,0,0,'BS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'БИК банка Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BIC_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'BIC_PAY','БИК банка Плательщика','STRING',9,1,0,0,'BIC_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Наименование банка Плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BIC_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'NAME_BIC_PAY','Наименование банка Плательщика','STRING',160,0,0,0,'NAME_BIC_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Коррсчет банка Плательщика в РКЦ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_KS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'BS_KS_PAY','Коррсчет банка Плательщика в РКЦ','STRING',20,1,0,0,'BS_KS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'ИНН получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INN_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 16,'INN_RCP','ИНН получателя','STRING',12,0,0,0,'INN_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'КПП получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KPP_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'KPP_RCP','КПП получателя','STRING',9,0,0,0,'KPP_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Наименование получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 18,'NAME_RCP','Наименование получателя','STRING',160,0,0,0,'NAME_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Расчетный счет Получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 19,'BS_RCP','Расчетный счет Получателя','STRING',20,0,0,0,'BS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'БИК банка Получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 20,'BIC_RCP','БИК банка Получателя','STRING',9,1,0,0,'BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Наименование банка получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 21,'NAME_BIC_RCP','Наименование банка получателя','STRING',160,0,0,0,'NAME_BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Корсчет банка получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_KS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_KS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 22,'BS_KS_RCP','Корсчет банка получателя','STRING',20,1,0,0,'BS_KS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Срок платежа',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 23,'DATE_PAY','Срок платежа','DATE',0,0,0,0,'DATE_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Очередность платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ORDER_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 24,'ORDER_PAY','Очередность платежа','STRING',1,1,0,0,'ORDER_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'UIN_CODE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Уникальный идентификатор начисления (Код)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 25,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'UIN_CODE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'UIN_CODE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 25,'UIN_CODE','Уникальный идентификатор начисления (Код)','STRING',25,0,0,0,'UIN_CODE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 26,'PURPOSE','Назначение платежа','STRING',210,0,0,0,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'Статус составителя расчетного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PAYSTATUS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 27,'PAYSTATUS','Статус составителя расчетного документа','STRING',2,0,0,0,'PAYSTATUS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Код бюджетной классификации',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 28,'KBK','Код бюджетной классификации','STRING',20,1,0,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 29,
		NAME   		= 'Код ОКТМО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKATO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 29,'OKATO','Код ОКТМО','STRING',11,0,0,0,'OKATO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OSNPLAT')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 30,
		NAME   		= 'Показатель основания платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OSNPLAT',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OSNPLAT'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 30,'OSNPLAT','Показатель основания платежа','STRING',2,0,0,0,'OSNPLAT','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAL_PER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 31,
		NAME   		= 'Показатель налогового периода',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAL_PER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAL_PER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 31,'NAL_PER','Показатель налогового периода','STRING',10,0,0,0,'NAL_PER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'Показатель номера документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_DOK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 32,'NOM_DOK','Показатель номера документа','STRING',15,0,0,0,'NOM_DOK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 33,
		NAME   		= 'Показатель даты документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_DOK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 33,'DATE_DOK','Показатель даты документа','STRING',10,0,0,0,'DATE_DOK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 34,
		NAME   		= 'Тип платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 34,'TYPE_PL','Тип платежа','STRING',2,0,0,0,'TYPE_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PL_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 35,
		NAME   		= 'Номер частичного платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_PL_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PL_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 35,'NOM_PL_PO','Номер частичного платежа','STRING',3,0,0,0,'NOM_PL_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SHIFR_RD_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 36,
		NAME   		= 'Шифр платежно-го документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SHIFR_RD_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SHIFR_RD_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 36,'SHIFR_RD_PO','Шифр платежно-го документа','STRING',2,1,0,0,'SHIFR_RD_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_RD_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 37,
		NAME   		= 'Номер платежного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_RD_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_RD_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 37,'NOM_RD_PO','Номер платежного документа','STRING',3,0,0,0,'NOM_RD_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_RD_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 38,
		NAME   		= 'Дата платежного документа',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_RD_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_RD_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 38,'DATE_RD_PO','Дата платежного документа','DATE',0,0,0,0,'DATE_RD_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_OST_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 39,
		NAME   		= 'Сумма остатка платежа',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_OST_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_OST_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 39,'SUM_OST_PO','Сумма остатка платежа','NUMBER2',0,0,0,0,'SUM_OST_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OPER_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 40,
		NAME   		= 'Содержание опе-рации',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 16,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OPER_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OPER_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 40,'OPER_PO','Содержание опе-рации','STRING',16,0,0,0,'OPER_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_IN_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 41,
		NAME   		= 'Дата выписки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_IN_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_IN_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 41,'DATE_IN_TOFK','Дата выписки','DATE',0,0,0,0,'DATE_IN_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 42,
		NAME   		= 'Глобальный уни-кальный идентификатор',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 42,'GUID','Глобальный уни-кальный идентификатор','GUID',36,1,0,0,'GUID','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'BDPDST'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'BDPDST',6,2,'Строки платежного поручения по бюджетной классификации',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 6,
			ISONCE = 2,
			NAME   = 'Строки платежного поручения по бюджетной классификации',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код по КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KBK','Код по КБК','STRING',20,1,0,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'TYPE_KBK','Тип КБК','STRING',2,1,0,0,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код цели субсидии',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'ADD_KLASS','Код цели субсидии','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_BO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Номер бюджетного обязательства',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 16,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NUM_BO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_BO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NUM_BO','Номер бюджетного обязательства','STRING',16,1,0,0,'NUM_BO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ОКАТО')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'ОКТMО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ОКАТО',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ОКАТО'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'ОКАТО','ОКТMО','STRING',11,1,0,0,'ОКАТО','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'SUM','Сумма','NUMBER2',0,1,1,1,'SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DIR_SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Направление пла-тежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DIR_SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DIR_SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'DIR_SUM','Направление пла-тежа','STRING',1,1,1,1,'DIR_SUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'MES_FIN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Месяц финансиро-вания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'MES_FIN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'MES_FIN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'MES_FIN','Месяц финансиро-вания','STRING',2,1,0,0,'MES_FIN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Резервное поле',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 40,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'REZERV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'REZERV'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'REZERV','Резервное поле','STRING',40,0,0,0,'REZERV','',''
GO

GO
update EXPORT_MODELS set DATE_END   = '20140930' WHERE MODEL_VER = 'TXVP130101' AND CODE = 'VP'
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXVP141001' 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','Выписка из лицевого счета получателя бюджетных средств','TXVP141001',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 	= 20,
		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',20,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
/****** Объект: Код ЭКР******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_CODE_EKR_PR_T_DGH')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_CODE_EKR_PR_T_DGH')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_CODE_EKR_PR_T_DGH')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'COLUMN_CODE_EKR_PR_T_DGH')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_CODE_EKR_PR_T_DGH'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_CODE_EKR_PR_T_DGH')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_CODE_EKR_PR_T_DGH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_CODE_EKR_PR_T_DGH', 'Код ЭКР', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DED_PR_TABLE_DGH'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_CODE_EKR_PR_T_DGH', NAME = 'Код ЭКР', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_DED_PR_TABLE_DGH'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_CODE_EKR_PR_T_DGH'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_PR_T_DGH', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_PR_T_DGH', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_ITEM'', oForm.APageframe1.Page2.BSpisok.BGrid1.RecordSource, ''LINK,CODE'', ''LINK_EKR,CODE_EKR'', '''', '''', "CODE LIKE ''21%'' OR CODE LIKE ''22%'' OR CODE LIKE ''26%''", .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_PR_T_DGH', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_PR_T_DGH', 'CONTROLSOURCE', 'm.cAlias + ".CODE_EKR"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_PR_T_DGH', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_PR_T_DGH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_EKR"'
GO




GO
/****** Объект: Ссылка на вышестоящее подразделение******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SUBDIVISION_PARENT')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'SUBDIVISION_PARENT')
	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 = 'SUBDIVISION_PARENT')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'SUBDIVISION_PARENT')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SUBDIVISION_PARENT'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SUBDIVISION_PARENT')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SUBDIVISION_PARENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SUBDIVISION_PARENT', 'Ссылка на вышестоящее подразделение', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_SUBDIVISION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SUBDIVISION_PARENT', NAME = 'Ссылка на вышестоящее подразделение', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_SUBDIVISION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SUBDIVISION_PARENT'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT', 'REFERENCE_TO_DICT', 'DICTIONARY_SUBDIVISION'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT', 'SHORT_CODE_OBJ', 'LINK_SELF'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT', 'COMMENTARY', 'Ссылка на вышестоящее подразделение'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/

GO

/****** Объект: Наименование вышестоящего подразделения******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SUBDIVISION_PARENT_NAME')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'SUBDIVISION_PARENT_NAME')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'SUBDIVISION_PARENT_NAME')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'SUBDIVISION_PARENT_NAME')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SUBDIVISION_PARENT_NAME'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SUBDIVISION_PARENT_NAME')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SUBDIVISION_PARENT_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SUBDIVISION_PARENT_NAME', 'Наименование вышестоящего подразделения', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_SUBDIVISION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SUBDIVISION_PARENT_NAME', NAME = 'Наименование вышестоящего подразделения', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_SUBDIVISION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SUBDIVISION_PARENT_NAME'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT_NAME', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_SUBDIVISION", oForm.ALIAS, "link,NAME", "LINK_SELF, PARENT_NAME", "", "", " imageindex = ''subdiv''", .t., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT_NAME', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT_NAME', 'CONTROLSOURCE', 'm.cAlias+".PARENT_NAME"'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT_NAME', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT_NAME', 'REFERENCE_TO_DICT', 'DICTIONARY_SUBDIVISION'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT_NAME', 'TYPE_FIELD_DICT', 'varchar(250)'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT_NAME', 'SHORT_CODE_OBJ', 'PARENT_NAME'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".PARENT_NAME"'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT_NAME', 'CONTROL_NAME', 'ASel_Spr2'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT_NAME', 'CONTROL_NAME_EDIT', 'ASel_Spr2'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT_NAME', 'REFERENCE_TO_FIELD', 'PARENT_NAME'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT_NAME', 'ASPTYPE', 'ASel_Spr2'
GO
EXEC X_SET_PROP 'SUBDIVISION_PARENT_NAME', 'FIELD_DATA', 'PARENT_NAME'
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='ESN_OPTIONS_8'

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_ESN_OPTIONS_8]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_ESN_OPTIONS_8]

CREATE TABLE  dbo._UPD_OPT_ESN_OPTIONS_8 (CODE VARCHAR(30), [SID] varbinary(85), VALUE VARCHAR(1000))

INSERT INTO _UPD_OPT_ESN_OPTIONS_8 (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 = 'ESN_OPTIONS_8')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'ESN_OPTIONS_8')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'ESN_OPTIONS_8')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'ESN_OPTIONS_8')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'ESN_OPTIONS_8'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'ESN_OPTIONS_8')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ESN_OPTIONS_8')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ESN_OPTIONS_8', 'Начислять доп. тариф на доходы внутренних совместителей', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='ESN_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ESN_OPTIONS_8', NAME = 'Начислять доп. тариф на доходы внутренних совместителей', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ESN_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ESN_OPTIONS_8'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_8', 'COMMENTARY', 'При включенной опции программа будет начислять страховые взносы по доп. тарифам на доходы внутренних совместителей.'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_8', 'CONTROL_NAME_EDIT', 'Acheckbox8'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_8', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_8', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_8', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_8', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_8', 'TITLE', 'Начислять доп. тариф на доходы внутренних совместителей'
GO
/******--Восстановить, либо установить настройки на базе пользователя ******/
DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'ESN_OPTIONS_8' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_ESN_OPTIONS_8] WHERE CODE = 'ESN_OPTIONS_8')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'ESN_OPTIONS_8'), SID, VALUE FROM [dbo].[_UPD_OPT_ESN_OPTIONS_8] WHERE CODE = 'ESN_OPTIONS_8'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '0' FROM  dbo.S_OBJECTS WHERE CODE = 'ESN_OPTIONS_8'

GO


IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_ESN_OPTIONS_8]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_ESN_OPTIONS_8]

GO


/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'ESN_OPTIONS_8', 'Зарплата-КС', 63,0
GO


GO

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- ОТЧЕТ: КАССОВЫЙ ПЛАН (FB_REPORT_KP_VYL) --- 
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'FB_REPORT_KP_VYL')
	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_CATALOG_FINANS_REATR'), 'FB_REPORT_KP_VYL', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'FB_REPORT_KP_VYL_OPT')
	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 = 'FB_REPORT_KP_VYL'), 'FB_REPORT_KP_VYL_OPT', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'FB_REPORT_KP_VYL_OPT_BATEB')
	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 = 'FB_REPORT_KP_VYL_OPT'), 'FB_REPORT_KP_VYL_OPT_BATEB', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'FB_REPORT_KP_VYL_OPT_BATEE')
	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 = 'FB_REPORT_KP_VYL_OPT'), 'FB_REPORT_KP_VYL_OPT_BATEE', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'FB_REPORT_KP_VYL_OPT_DOP_EKR')
	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 = 'FB_REPORT_KP_VYL_OPT'), 'FB_REPORT_KP_VYL_OPT_DOP_EKR', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'FB_REPORT_KP_VYL_OPT_NUM')
	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_TEXTBOX'), 'Номер документа', 8, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'FB_REPORT_KP_VYL_OPT'), 'FB_REPORT_KP_VYL_OPT_NUM', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'FB_REPORT_KP_VYL_OPT_PLAND')
	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'), 'План по доходам', 4, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'FB_REPORT_KP_VYL_OPT'), 'FB_REPORT_KP_VYL_OPT_PLAND', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'FB_REPORT_KP_VYL_OPT_SUM_TYPE')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_CHECKBOX'), 'Суммы в тыс. рублей', 6, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'FB_REPORT_KP_VYL_OPT'), 'FB_REPORT_KP_VYL_OPT_SUM_TYPE', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'FB_REPORT_KP_VYL_OPT_ZB')
	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'), 'Очет по ЦБ', 7, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'FB_REPORT_KP_VYL_OPT'), 'FB_REPORT_KP_VYL_OPT_ZB', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'FB_REPORT_KP_VYL_OPT_PLAN_FIN')
	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 = 'FB_REPORT_KP_VYL_OPT'), 'FB_REPORT_KP_VYL_OPT_PLAN_FIN', NULL, NULL, 1
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'INIT_OBJECT_METHOD', 'm_print_query(nLink_Var)', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'CHECK_VALUE_IN_TABLE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'AFTER_CHANGE_PROG_NASTR', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'BEFORE_CHANGE_PROG_NASTR', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'NASTR_XL_CENTER_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'NASTR_XL_DATETIME', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'NASTR_XL_FOOTER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'NASTR_XL_FREEZEPANES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'NASTR_XL_LEFT_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'NASTR_XL_PAGES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'NASTR_XL_RIGHT_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_ADDFROM', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_ADDINTO', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_ADDSELECT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_ADDWHERE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_AFTER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_BEFORE', 'EXEC dbo.FB_PRINT_KP_VYLUCH @dDateB1, @dDateE1, '''',@nCheck1 , @nCheck2 , @nCheck3 ,@nCheck4, @nCheck5', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_DATETIME', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_DISTINCT', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_FOOTER', '="Исполнитель                               " & User_FIO
                                 подпись', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_FREEZEPANES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_HEADER', '=User_Name', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_PAGES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_PROCEDURE', '#FB_REPORT_KP_VYL', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_REPMAKER', 'KIRREPMAKER.XLS', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_REPORT', 'IIF(@nCheck1 = 0,"FB_KASS_PLAN_VYL.XLT",IIF(@nCheck1 = 1,"FB_KASS_PLAN_VYL_D.XLT",""))', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_REPORT_PATH', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_SQL', 'CREATE PROCEDURE #FB_REPORT_KP_VYL
	@dDateB1 datetime	/* Дата начала периода расчета */,
	@dDateE1 datetime	/* Дата окончания периода расчета */,
	@nCheck1 int	/* План по доходам */,
	@nCheck2 int	/* Выводить группировочные коды ЭКР */,
	@nCheck3 int	/* Суммы в тыс. рублей */,
	@nCheck4 int	/* Очет по ЦБ */,
	@cText1 varchar(8000)	/* Номер документа */,
	@nCheck5 int	/* План с учетом финансирования */
AS
BEGIN

EXEC dbo.FB_PRINT_KP_VYLUCH @dDateB1, @dDateE1, '''',@nCheck1 , @nCheck2 , @nCheck3 ,@nCheck4, @nCheck5

END', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_SYSTEM', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_TOP', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_TOTAL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_TOTALCOL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_TOTALROW', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_AP_LIST', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'EOD_PROTOCOL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'AFTER_REPORT_PROG', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_ADD_MODULE', 'KIRREPCOMMON.BAS', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_CODE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'QUERY_DATE_TYPE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'SQUERY_NO_SHOW', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL', 'REPORT_EXTERNAL_GENERATOR', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEB', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEB', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEB', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEB', 'QUERY_NASTR_CAPTION', 'Дата начала периода расчета', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEB', 'QUERY_NASTR_CONTROL', 'DATEBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEB', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEB', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEB', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEB', 'QUERY_NASTR_SOURCE', 'Текущая дата,Расчетная дата,Начало расч. периода,Конец расч. периода,Начало года,Конец года,Начало расч. месяца,Конец расч. месяца', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEB', 'QUERY_NASTR_SQLPARAM', '@dDateB1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEB', 'QUERY_NASTR_SQLTYPE', 'datetime', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEB', 'QUERY_NASTR_VALUE', 'Текущая дата', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEB', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEB', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEE', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEE', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEE', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEE', 'QUERY_NASTR_CAPTION', 'Дата окончания периода расчета', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEE', 'QUERY_NASTR_CONTROL', 'DATEBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEE', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEE', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEE', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEE', 'QUERY_NASTR_SOURCE', 'Текущая дата,Расчетная дата,Начало расч. периода,Конец расч. периода,Начало года,Конец года,Начало расч. месяца,Конец расч. месяца', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEE', 'QUERY_NASTR_SQLPARAM', '@dDateE1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEE', 'QUERY_NASTR_SQLTYPE', 'datetime', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEE', 'QUERY_NASTR_VALUE', 'Текущая дата', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEE', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_BATEE', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_DOP_EKR', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_DOP_EKR', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_DOP_EKR', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_DOP_EKR', 'QUERY_NASTR_CAPTION', 'Выводить группировочные коды ЭКР', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_DOP_EKR', 'QUERY_NASTR_CONTROL', 'CHECKBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_DOP_EKR', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_DOP_EKR', 'QUERY_NASTR_NUMPARAM', '2', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_DOP_EKR', 'QUERY_NASTR_SAVE', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_DOP_EKR', 'QUERY_NASTR_SOURCE', 'Выкл.,Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_DOP_EKR', 'QUERY_NASTR_SQLPARAM', '@nCheck2', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_DOP_EKR', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_DOP_EKR', 'QUERY_NASTR_VALUE', 'Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_DOP_EKR', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_DOP_EKR', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_NUM', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_NUM', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_NUM', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_NUM', 'QUERY_NASTR_CAPTION', 'Номер документа', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_NUM', 'QUERY_NASTR_CONTROL', 'TEXTBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_NUM', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_NUM', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_NUM', 'QUERY_NASTR_SAVE', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_NUM', 'QUERY_NASTR_SOURCE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_NUM', 'QUERY_NASTR_SQLPARAM', '@cText1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_NUM', 'QUERY_NASTR_SQLTYPE', 'varchar(8000)', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_NUM', 'QUERY_NASTR_VALUE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_NUM', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_NUM', 'SQUERY_NASTR_OPTIONAL', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAND', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAND', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAND', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAND', 'QUERY_NASTR_CAPTION', 'План по доходам', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAND', 'QUERY_NASTR_CONTROL', 'CHECKBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAND', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAND', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAND', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAND', 'QUERY_NASTR_SOURCE', 'Выкл.,Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAND', 'QUERY_NASTR_SQLPARAM', '@nCheck1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAND', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAND', 'QUERY_NASTR_VALUE', 'Выкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAND', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAND', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_SUM_TYPE', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_SUM_TYPE', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_SUM_TYPE', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_SUM_TYPE', 'QUERY_NASTR_CAPTION', 'Суммы в тыс. рублей', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_SUM_TYPE', 'QUERY_NASTR_CONTROL', 'CHECKBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_SUM_TYPE', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_SUM_TYPE', 'QUERY_NASTR_NUMPARAM', '3', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_SUM_TYPE', 'QUERY_NASTR_SAVE', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_SUM_TYPE', 'QUERY_NASTR_SOURCE', 'Выкл.,Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_SUM_TYPE', 'QUERY_NASTR_SQLPARAM', '@nCheck3', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_SUM_TYPE', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_SUM_TYPE', 'QUERY_NASTR_VALUE', 'Выкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_SUM_TYPE', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_SUM_TYPE', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_ZB', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_ZB', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_ZB', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_ZB', 'QUERY_NASTR_CAPTION', 'Очет по ЦБ', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_ZB', 'QUERY_NASTR_CONTROL', 'CHECKBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_ZB', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_ZB', 'QUERY_NASTR_NUMPARAM', '4', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_ZB', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_ZB', 'QUERY_NASTR_SOURCE', 'Выкл.,Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_ZB', 'QUERY_NASTR_SQLPARAM', '@nCheck4', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_ZB', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_ZB', 'QUERY_NASTR_VALUE', 'Выкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_ZB', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_ZB', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAN_FIN', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAN_FIN', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAN_FIN', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAN_FIN', 'QUERY_NASTR_CAPTION', 'План с учетом финансирования', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAN_FIN', 'QUERY_NASTR_CONTROL', 'CHECKBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAN_FIN', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAN_FIN', 'QUERY_NASTR_NUMPARAM', '5', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAN_FIN', 'QUERY_NASTR_SAVE', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAN_FIN', 'QUERY_NASTR_SOURCE', 'Выкл.,Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAN_FIN', 'QUERY_NASTR_SQLPARAM', '@nCheck5', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAN_FIN', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAN_FIN', 'QUERY_NASTR_VALUE', 'Выкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAN_FIN', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'FB_REPORT_KP_VYL_OPT_PLAN_FIN', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO

GO
IF not exists(select * from dbo.formula_bridge where name = '4ФСС_РАЗДЕЛ_ПП1' and PROC_NAME = 'I_REPORT_FORMULA_4_FSS_PP_RAZD1')
begin
  	
  IF not exists(select * from dbo.DICTION where name = '4ФСС_РАЗДЕЛ_ПП1')
  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ФСС_РАЗДЕЛ_ПП1', @linkObjF, NULL, '17530101','99991231')

		set @LinkOBJ = (select link from dbo.DICTION where name = '4ФСС_РАЗДЕЛ_ПП1')
		
		
		-- insert порядка для формулы в таблицу dbo.DICTION_APP 
		IF not exists(select * from dbo.DICTION_APP where link_up = (select link from dbo.DICTION where name = '4ФСС_РАЗДЕЛ_ПП1') 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ФСС_РАЗДЕЛ_ПП1') 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, 'I_REPORT_FORMULA_4_FSS_PP_RAZD1')		
 
		end
			
  end	
 
end   

GO

GO
/****** Объект: Должность сотрудника******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'KADR_REZERV_EMPL_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 = 'KADR_REZERV_EMPL_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 = 'KADR_REZERV_EMPL_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 = 'KADR_REZERV_EMPL_POST')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'KADR_REZERV_EMPL_POST'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'KADR_REZERV_EMPL_POST')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KADR_REZERV_EMPL_POST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KADR_REZERV_EMPL_POST', 'Должность сотрудника', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_KADR_REZERV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KADR_REZERV_EMPL_POST', NAME = 'Должность сотрудника', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KJ_KADR_REZERV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KADR_REZERV_EMPL_POST'
GO
EXEC X_SET_PROP 'KADR_REZERV_EMPL_POST', 'TITLE', 'Должность сотрудника'
GO
EXEC X_SET_PROP 'KADR_REZERV_EMPL_POST', 'ORDER_NUMBER', '2'
GO
EXEC X_SET_PROP 'KADR_REZERV_EMPL_POST', 'VISIBLE', '27'
GO
EXEC X_SET_PROP 'KADR_REZERV_EMPL_POST', 'CONTROLSOURCE', 'm.cAlias+".EMPL_POST"'
GO
EXEC X_SET_PROP 'KADR_REZERV_EMPL_POST', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'KADR_REZERV_EMPL_POST', 'TYPE_FIELD_DICT', 'VARCHAR(200)'
GO
EXEC X_SET_PROP 'KADR_REZERV_EMPL_POST', 'CONTROLSOURCE_EDIT', 'm.cAlias+".EMPL_POST"'
GO
EXEC X_SET_PROP 'KADR_REZERV_EMPL_POST', 'CONTROL_NAME_EDIT', 'atxt2'
GO
EXEC X_SET_PROP 'KADR_REZERV_EMPL_POST', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 100; LEFT: 16px; POSITION: absolute; TOP: 8px"'
GO
EXEC X_SET_PROP 'KADR_REZERV_EMPL_POST', 'DICTIONARY', 'KU_PERSON'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
EXEC X_SET_PROP 'KADR_REZERV_NAZN', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("ORDERS_REESTR",oForm.ALIAS,"LINK, ''№ '' + alltrim(NUMBER) + LOWER('' от '') + DTOC(DATE) + LOWER('' г.'')", "ORDER_LINK, NAZN", "", "", "TYPE in (1,101,2,102) AND STATUS = 1 AND FIO LIKE ''%" + ALLTRIM(EVALUATE(oForm.ALIAS + ''.FIO'')) +"%''  AND DATE >= ''" + ALLTRIM(DTOC(EVALUATE(oForm.ALIAS + ''.DATE''),1)) + "''", .T., 1, oForm, oObj,.F.,.T.)'
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 = '3813')

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 = '3813'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KU_PERS_PENSION_NAV'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'KU_PERS_PENSION_NAV', 'Пенсионеры', @ORD, NULL, 1, @LINK_SELF, 'DICTIONARY', @OBJECT, @LINK_VAR, 3
GO



UPDATE s
	SET ORDERS =( SELECT COALESCE(ORDERS,0) + 1  FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '3813') AND code = 'PERSON_SALARY') 
	             FROM DBO.S_NAVIGATOR s WHERE  code = 'KU_PERS_PENSION_NAV' AND LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '3813')                               


GO

GO
/*Обновление значения настройки "Код начисления для районного коэффициента" */
update dbo.S_OPTIONS
SET VALUE = null
WHERE [OBJECT] = (SELECT link FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPTIONS3_1')

GO


GO
/****** Объект: Источники финансирования******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SALARY_SRC_FIN')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'SALARY_SRC_FIN')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'SALARY_SRC_FIN')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'SALARY_SRC_FIN')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SALARY_SRC_FIN'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SALARY_SRC_FIN')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SALARY_SRC_FIN', 'Источники финансирования', 24, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICT_SAL_KADR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SALARY_SRC_FIN', NAME = 'Источники финансирования', ORDERS = '24', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICT_SAL_KADR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='SALARY_SRC_FIN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_NAME', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_NAME', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_SOURCE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_SOURCE', 'Вид деятельности', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_SOURCE', NAME = 'Вид деятельности', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_SOURCE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_NSOURCE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_NSOURCE', 'Вид деятельности', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_NSOURCE', NAME = 'Вид деятельности', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_NSOURCE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_ENVD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_ENVD', 'ЕНВД', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_ENVD', NAME = 'ЕНВД', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_ENVD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_NENVD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_NENVD', 'ЕНВД', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_NENVD', NAME = 'ЕНВД', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_NENVD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_CODE_KBK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_CODE_KBK', 'Код КБК', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_CODE_KBK', NAME = 'Код КБК', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_CODE_KBK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_NAME_KBK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_NAME_KBK', 'Наименование КБК', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_NAME_KBK', NAME = 'Наименование КБК', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_NAME_KBK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_USER_ACC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_USER_ACC', 'Дополнительные разряды счета', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_USER_ACC', NAME = 'Дополнительные разряды счета', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_USER_ACC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_CODE_KAU')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_CODE_KAU', 'Код КАУ', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_CODE_KAU', NAME = 'Код КАУ', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_CODE_KAU'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_NAME_KAU')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_NAME_KAU', 'Наименование КАУ', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_NAME_KAU', NAME = 'Наименование КАУ', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_NAME_KAU'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_CODE_DOP_KL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_CODE_DOP_KL', 'Код признака доп. кл.', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_CODE_DOP_KL', NAME = 'Код признака доп. кл.', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_CODE_DOP_KL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_NAME_DOP_KL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_NAME_DOP_KL', 'Наименование доп. кл.', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_NAME_DOP_KL', NAME = 'Наименование доп. кл.', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_NAME_DOP_KL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_COMMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_COMMENT', 'Комментарий', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_COMMENT', NAME = 'Комментарий', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_COMMENT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_ACC_ESN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_ACC_ESN', 'Счет для расходов на начисления на оплату труда', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_ACC_ESN', NAME = 'Счет для расходов на начисления на оплату труда', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_ACC_ESN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_LACC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_LACC', 'Номер лицевого счета', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_LACC', NAME = 'Номер лицевого счета', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_LACC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_NAME_LACC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_NAME_LACC', 'Наименование лицевого счета', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_NAME_LACC', NAME = 'Наименование лицевого счета', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_NAME_LACC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_USED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_USED', 'Использовать', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_USED', NAME = 'Использовать', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_USED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_N_USED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_N_USED', 'Использовать в учете(да/нет)', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_N_USED', NAME = 'Использовать в учете(да/нет)', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_N_USED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_NSF_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_NSF_CODE', 'Заменен на источник', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_NSF_CODE', NAME = 'Заменен на источник', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_NSF_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_SFIN_NSF_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_SFIN_NSF_DATE', 'Дата замены', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_SFIN_NSF_DATE', NAME = 'Дата замены', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_SRC_FIN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_SFIN_NSF_DATE'
GO
EXEC X_SET_PROP 'SALARY_SRC_FIN', 'TITLE', 'Источники финансирования'
GO
EXEC X_SET_PROP 'SALARY_SRC_FIN', 'INIT_OBJECT_METHOD', 'X_SPISOK("SALARY_SRC_FIN")'
GO
EXEC X_SET_PROP 'SALARY_SRC_FIN', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "SALARY_SRC_FIN", "SA_SFIN_DEL", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'SALARY_SRC_FIN', 'SAVE_OBJECT_METHOD', 'salary_save_sfin(oForm)'
GO
EXEC X_SET_PROP 'SALARY_SRC_FIN', 'EDIT_OBJECT_METHOD', 'SALARY_BROW(''SAL_SFIN_EDIT'')'
GO
EXEC X_SET_PROP 'SALARY_SRC_FIN', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS("SALARY_SRC_FIN")'
GO
EXEC X_SET_PROP 'SALARY_SRC_FIN', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS("SALARY_SRC_FIN")'
GO
EXEC X_SET_PROP 'SALARY_SRC_FIN', 'OPEN_CODE', 'CODE'
GO
EXEC X_SET_PROP 'SALARY_SRC_FIN', 'MSG_SEL_ONE', 'IIF(ISNULL(CODE), '''',CODE)'
GO
EXEC X_SET_PROP 'SALARY_SRC_FIN', 'SERVER_TABLE_NAME', 'SAL_SFIN'
GO
EXEC X_SET_PROP 'SALARY_SRC_FIN', 'HELP_TOPIC', 'Ставки удержаний/ отчислений'
GO
EXEC X_SET_PROP 'SALARY_SRC_FIN', 'OPERATION_MASK', '9'
GO
EXEC X_SET_PROP 'SAL_SFIN_CHECKED', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'SAL_SFIN_CHECKED', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SAL_SFIN_CHECKED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE', 'COMMENTARY', 'Код источника финансирования'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME', 'CONTROLSOURCE', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(120)'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME', 'CONTROL_NAME_EDIT', 'ATxtN2'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME', 'COMMENTARY', 'Наименование источника финансирования'
GO
EXEC X_SET_PROP 'SAL_SFIN_SOURCE', 'TITLE', 'Вид деятельности'
GO
EXEC X_SET_PROP 'SAL_SFIN_SOURCE', 'CONTROLSOURCE', 'm.cAlias + ".SOURCE"'
GO
EXEC X_SET_PROP 'SAL_SFIN_SOURCE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_SOURCE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SAL_SFIN_SOURCE', 'TYPE_FIELD_DICT', 'tinyint'
GO
EXEC X_SET_PROP 'SAL_SFIN_SOURCE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SOURCE"'
GO
EXEC X_SET_PROP 'SAL_SFIN_SOURCE', 'CONTROL_NAME_EDIT', 'acombobox3'
GO
EXEC X_SET_PROP 'SAL_SFIN_SOURCE', 'COMMENTARY', 'Признак вида деятельности'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSOURCE', 'TITLE', 'Вид деятельности'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSOURCE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSOURCE', 'CONTROLSOURCE', 'm.cAlias + ".NSOURCE"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSOURCE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSOURCE', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSOURCE', 'SHORT_CODE_OBJ', 'NSOURCE'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSOURCE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NSOURCE"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSOURCE', 'COMMENTARY', 'Признак вида деятельности'
GO
EXEC X_SET_PROP 'SAL_SFIN_ENVD', 'TITLE', 'ЕНВД'
GO
EXEC X_SET_PROP 'SAL_SFIN_ENVD', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SAL_SFIN_ENVD', 'CONTROLSOURCE', 'm.cAlias + ".ENVD"'
GO
EXEC X_SET_PROP 'SAL_SFIN_ENVD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_ENVD', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SAL_SFIN_ENVD', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ENVD"'
GO
EXEC X_SET_PROP 'SAL_SFIN_ENVD', 'CONTROL_NAME_EDIT', 'ACheckBox9'
GO
EXEC X_SET_PROP 'SAL_SFIN_ENVD', 'COMMENTARY', 'Признак ЕНВД, На доходы по данному источнику страховые взносы рассчитываются по ставкам ЕНВД.'
GO
EXEC X_SET_PROP 'SAL_SFIN_NENVD', 'TITLE', 'ЕНВД'
GO
EXEC X_SET_PROP 'SAL_SFIN_NENVD', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SAL_SFIN_NENVD', 'CONTROLSOURCE', 'm.cAlias + ".NENVD"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NENVD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_NENVD', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SAL_SFIN_NENVD', 'COMMENTARY', 'Признак ЕНВД'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KBK', 'TITLE', 'Код КБК'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KBK', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''BI_DICTION_KBK'', oForm.ALIAS, ''LINK, CODE, NAME'', ''LINK_KBK,CODE_KBK,NAME_KBK'', '''', '''', ''TYPE = 1'', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KBK', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KBK', 'CONTROLSOURCE', 'm.cAlias + ".CODE_KBK"'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KBK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KBK', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KBK', 'SHORT_CODE_OBJ', 'CODE_KBK'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KBK', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_KBK"'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KBK', 'CONTROL_NAME_EDIT', 'asel_spr4'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KBK', 'COMMENTARY', 'Код КБК'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_KBK', 'TITLE', 'Наименование КБК'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_KBK', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_KBK', 'CONTROLSOURCE', 'm.cAlias + ".NAME_KBK"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_KBK', 'TYPE_FIELD_DICT', 'VARCHAR(250)'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_KBK', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_KBK"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_KBK', 'CONTROL_NAME_EDIT', 'ATxtN4'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_KBK', 'COMMENTARY', 'Наименование КБК'
GO
EXEC X_SET_PROP 'SAL_SFIN_USER_ACC', 'TITLE', 'Доп. счет'
GO
EXEC X_SET_PROP 'SAL_SFIN_USER_ACC', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SAL_SFIN_USER_ACC', 'CONTROLSOURCE', 'm.cAlias + ".USER_ACC"'
GO
EXEC X_SET_PROP 'SAL_SFIN_USER_ACC', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_USER_ACC', 'TYPE_FIELD_DICT', 'VARCHAR(4)'
GO
EXEC X_SET_PROP 'SAL_SFIN_USER_ACC', 'SHORT_CODE_OBJ', 'USER_ACC'
GO
EXEC X_SET_PROP 'SAL_SFIN_USER_ACC', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".USER_ACC"'
GO
EXEC X_SET_PROP 'SAL_SFIN_USER_ACC', 'CONTROL_NAME_EDIT', 'ATxtN5'
GO
EXEC X_SET_PROP 'SAL_SFIN_USER_ACC', 'COMMENTARY', 'Доп. разряды счета'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KAU', 'TITLE', 'Код КАУ'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KAU', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_ANALYTICAL_CODES", oForm.Alias, "LINK, CODE, NAME", "LINK_KAU,CODE_KAU,NAME_KAU", "", "", "dbo.AccountsHasNoChild(LINK)=1", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KAU', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KAU', 'CONTROLSOURCE', 'm.cAlias + ".CODE_KAU"'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KAU', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KAU', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KAU', 'SHORT_CODE_OBJ', 'CODE_KAU'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KAU', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_KAU"'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KAU', 'CONTROL_NAME_EDIT', 'asel_spr6'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_KAU', 'COMMENTARY', 'Код КАУ'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_KAU', 'TITLE', 'Наименование КАУ'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_KAU', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_KAU', 'CONTROLSOURCE', 'm.cAlias + ".NAME_KAU"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_KAU', 'TYPE_FIELD_DICT', 'VARCHAR(100)'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_KAU', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_KAU"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_KAU', 'CONTROL_NAME_EDIT', 'ATxtN6'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_KAU', 'COMMENTARY', 'Наименование КБК'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_DOP_KL', 'TITLE', 'Код  доп. кл.'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_DOP_KL', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("BD_DOP_CLASSIF", oForm.Alias, "LINK, CODE, NAME", "LINK_DOP_KL,CODE_DOP_KL,NAME_DOP_KL", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_DOP_KL', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_DOP_KL', 'CONTROLSOURCE', 'm.cAlias + ".CODE_DOP_KL"'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_DOP_KL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_DOP_KL', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_DOP_KL', 'SHORT_CODE_OBJ', 'CODE_DOP_KL'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_DOP_KL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_DOP_KL"'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_DOP_KL', 'CONTROL_NAME_EDIT', 'asel_spr7'
GO
EXEC X_SET_PROP 'SAL_SFIN_CODE_DOP_KL', 'COMMENTARY', 'Код признака доп. классификации'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_DOP_KL', 'TITLE', 'Наименование доп. кл.'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_DOP_KL', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_DOP_KL', 'CONTROLSOURCE', 'm.cAlias + ".NAME_DOP_KL"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_DOP_KL', 'TYPE_FIELD_DICT', 'VARCHAR(150)'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_DOP_KL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_DOP_KL"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_DOP_KL', 'CONTROL_NAME_EDIT', 'ATxtN7'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_DOP_KL', 'COMMENTARY', 'Наименование признака доп. классификации'
GO
EXEC X_SET_PROP 'SAL_SFIN_COMMENT', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'SAL_SFIN_COMMENT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SAL_SFIN_COMMENT', 'CONTROLSOURCE', 'm.cAlias + ".COMMENT"'
GO
EXEC X_SET_PROP 'SAL_SFIN_COMMENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_COMMENT', 'TYPE_FIELD_DICT', 'VARCHAR(100)'
GO
EXEC X_SET_PROP 'SAL_SFIN_COMMENT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COMMENT"'
GO
EXEC X_SET_PROP 'SAL_SFIN_COMMENT', 'CONTROL_NAME_EDIT', 'ATxtN8'
GO
EXEC X_SET_PROP 'SAL_SFIN_COMMENT', 'COMMENTARY', 'Дополнительная информация'
GO
EXEC X_SET_PROP 'SAL_SFIN_ACC_ESN', 'TITLE', 'Счет для расходов на оплату труда'
GO
EXEC X_SET_PROP 'SAL_SFIN_ACC_ESN', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SAL_SFIN_ACC_ESN', 'CONTROLSOURCE', 'm.cAlias + ".ACC_ESN"'
GO
EXEC X_SET_PROP 'SAL_SFIN_ACC_ESN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_ACC_ESN', 'TYPE_FIELD_DICT', 'VARCHAR(6)'
GO
EXEC X_SET_PROP 'SAL_SFIN_ACC_ESN', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ACC_ESN"'
GO
EXEC X_SET_PROP 'SAL_SFIN_ACC_ESN', 'CONTROL_NAME_EDIT', 'ATxtN9'
GO
EXEC X_SET_PROP 'SAL_SFIN_ACC_ESN', 'INPUT_MASK', '999.99'
GO
EXEC X_SET_PROP 'SAL_SFIN_ACC_ESN', 'COMMENTARY', 'Используется для формирования проводок по страховым взносам'
GO
EXEC X_SET_PROP 'SAL_SFIN_LACC', 'TITLE', 'Номер л/с'
GO
EXEC X_SET_PROP 'SAL_SFIN_LACC', 'EDIT_OBJECT_METHOD', 'xd_vibor_grouped_01(''DICTIONARY_ACCOUNTS'', oForm.ALIAS, ''LINK, CODE, ANAME'', ''LINK_LACC, CODE_LACC, NAME_LACC'', '''', '''', '''', .T., 1, oForm, oObj, "",.T.,"DEP_ACCOUNTS_GROUPS")'
GO
EXEC X_SET_PROP 'SAL_SFIN_LACC', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SAL_SFIN_LACC', 'CONTROLSOURCE', 'm.cAlias + ".CODE_LACC"'
GO
EXEC X_SET_PROP 'SAL_SFIN_LACC', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_LACC', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SAL_SFIN_LACC', 'SHORT_CODE_OBJ', 'CODE_LACC'
GO
EXEC X_SET_PROP 'SAL_SFIN_LACC', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE_LACC"'
GO
EXEC X_SET_PROP 'SAL_SFIN_LACC', 'CONTROL_NAME_EDIT', 'asel_spr10'
GO
EXEC X_SET_PROP 'SAL_SFIN_LACC', 'COMMENTARY', 'Номер л/с'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_LACC', 'TITLE', 'Лицевой счет'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_LACC', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_LACC', 'CONTROLSOURCE', 'm.cAlias + ".NAME_LACC"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_LACC', 'TYPE_FIELD_DICT', 'VARCHAR(250)'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_LACC', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_LACC"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_LACC', 'CONTROL_NAME_EDIT', 'ATxtN10'
GO
EXEC X_SET_PROP 'SAL_SFIN_NAME_LACC', 'COMMENTARY', 'Лицевой счет'
GO
EXEC X_SET_PROP 'SAL_SFIN_USED', 'TITLE', 'Использовать в учете'
GO
EXEC X_SET_PROP 'SAL_SFIN_USED', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SAL_SFIN_USED', 'CONTROLSOURCE', 'm.cAlias+".USED"'
GO
EXEC X_SET_PROP 'SAL_SFIN_USED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_USED', 'TYPE_FIELD_DICT', 'bit'
GO
EXEC X_SET_PROP 'SAL_SFIN_USED', 'SHORT_CODE_OBJ', 'USED'
GO
EXEC X_SET_PROP 'SAL_SFIN_USED', 'CONTROLSOURCE_EDIT', 'm.cAlias+".USED"'
GO
EXEC X_SET_PROP 'SAL_SFIN_USED', 'CONTROL_NAME_EDIT', 'aChkUsed'
GO
EXEC X_SET_PROP 'SAL_SFIN_USED', 'REFERENCE_TO_FIELD', 'USED'
GO
EXEC X_SET_PROP 'SAL_SFIN_USED', 'FIELD_DATA', 'USED'
GO
EXEC X_SET_PROP 'SAL_SFIN_USED', 'FIELD_KEY', 'USED'
GO
EXEC X_SET_PROP 'SAL_SFIN_N_USED', 'TITLE', 'Использовать'
GO
EXEC X_SET_PROP 'SAL_SFIN_N_USED', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SAL_SFIN_N_USED', 'CONTROLSOURCE', 'm.cAlias+".N_USED"'
GO
EXEC X_SET_PROP 'SAL_SFIN_N_USED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_N_USED', 'TYPE_FIELD_DICT', 'char(3)'
GO
EXEC X_SET_PROP 'SAL_SFIN_N_USED', 'SHORT_CODE_OBJ', 'N_USED'
GO
EXEC X_SET_PROP 'SAL_SFIN_N_USED', 'CONTROLSOURCE_EDIT', 'm.cAlias+".N_USED"'
GO
EXEC X_SET_PROP 'SAL_SFIN_N_USED', 'REFERENCE_TO_FIELD', 'N_USED'
GO
EXEC X_SET_PROP 'SAL_SFIN_N_USED', 'FIELD_DATA', 'N_USED'
GO
EXEC X_SET_PROP 'SAL_SFIN_N_USED', 'FIELD_KEY', 'N_USED'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_CODE', 'TITLE', 'Заменен на источник'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SALARY_SRC_FIN'', oForm.ALIAS, ''LINK, CODE'', ''LINK_CH_SFIN,NSF_CODE'', '''', '''', ''USED=1'', .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_CODE', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_CODE', 'CONTROLSOURCE', 'm.cAlias + ".NSF_CODE"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_CODE', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_CODE', 'SHORT_CODE_OBJ', 'NSF_CODE'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NSF_CODE"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_CODE', 'CONTROL_NAME_EDIT', 'Asel_spr13'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_CODE', 'COMMENTARY', 'В этом поле указывается новый источник финансирования, на который заменен данный источник.'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_DATE', 'TITLE', 'Дата замены'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_DATE', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_DATE', 'CONTROLSOURCE', 'm.cAlias + ".DATE_CHANGE"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_DATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_DATE', 'SHORT_CODE_OBJ', 'DATE_CHANGE'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE_CHANGE"'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_DATE', 'CONTROL_NAME_EDIT', 'Asel_spr14'
GO
EXEC X_SET_PROP 'SAL_SFIN_NSF_DATE', 'COMMENTARY', 'В этом поле указывается дата, начиная с которой действует новый источник.'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'SALARY_SRC_FIN', 'Кадры-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_SRC_FIN', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_SRC_FIN', 'Свод-КС', 5,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_SRC_FIN', 'Кадры-КС (чтение)', 5,26
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Источники финансирования"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'NV_SAL_DICTIONS')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SALARY_SRC_FIN')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'NV_SAL_DICTIONS'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SALARY_SRC_FIN_NV'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'SALARY_SRC_FIN_NV', 'Источники финансирования', @ORD, NULL, 1, @LINK_SELF, 'DICTIONARY', @OBJECT, @LINK_VAR, 3
GO

GO
declare @code varchar(20), @name varchar(254), @FTYPE tinyint, @FVALUE varchar(254), @DATATYPE char(1), @del bit
set @del = 0									--Признак удаления (0-нет, 1- да)
set @code = 'RND'								--Код
set @name = 'Случайное буквенно-цифровое число'	--Нименование
set @FTYPE = 1
set @FVALUE = ''
set @DATATYPE = 'C'								--Тип (C\N\D)
if @del = 1
	begin
		delete from S_BANK_FORMAT_BASE where CODE = @code
	end
	else
		begin
			if not exists (select * from S_BANK_FORMAT_BASE where CODE = @code)
				begin
					INSERT INTO dbo.[S_BANK_FORMAT_BASE]([CODE], [NAME], [FTYPE], [FVALUE], [DATATYPE])  
					VALUES (@code, @name, @FTYPE, @FVALUE, @DATATYPE)  
				end
				else
				begin
					update S
					set [CODE] =@code, [NAME]= @name, [FTYPE] = @FTYPE, [FVALUE] = @FVALUE, [DATATYPE] = @DATATYPE
					from S_BANK_FORMAT_BASE S
					where CODE = @code
				end
		end
GO

declare @code varchar(20), @name varchar(254), @FTYPE tinyint, @FVALUE varchar(254), @DATATYPE char(1), @del bit
set @del = 0									--Признак удаления (0-нет, 1- да)
set @code = 'DATE'								--Код
set @name = 'Текущая дата в формате ГГГГММДД'	--Нименование
set @FTYPE = 1
set @FVALUE = ''
set @DATATYPE = 'C'								--Тип (C\N\D)
if @del = 1
	begin
		delete from S_BANK_FORMAT_BASE where CODE = @code
	end
	else
		begin
			if not exists (select * from S_BANK_FORMAT_BASE where CODE = @code)
				begin
					INSERT INTO dbo.[S_BANK_FORMAT_BASE]([CODE], [NAME], [FTYPE], [FVALUE], [DATATYPE])  
					VALUES (@code, @name, @FTYPE, @FVALUE, @DATATYPE)  
				end
				else
				begin
					update S
					set [CODE] =@code, [NAME]= @name, [FTYPE] = @FTYPE, [FVALUE] = @FVALUE, [DATATYPE] = @DATATYPE
					from S_BANK_FORMAT_BASE S
					where CODE = @code
				end
		end
GO

declare @code varchar(20), @name varchar(254), @FTYPE tinyint, @FVALUE varchar(254), @DATATYPE char(1), @del bit
set @del = 0									--Признак удаления (0-нет, 1- да)
set @code = 'TIME'								--Код
set @name = 'Текущее время в формате ЧЧММСС'	--Нименование
set @FTYPE = 1
set @FVALUE = ''
set @DATATYPE = 'C'								--Тип (C\N\D)
if @del = 1
	begin
		delete from S_BANK_FORMAT_BASE where CODE = @code
	end
	else
		begin
			if not exists (select * from S_BANK_FORMAT_BASE where CODE = @code)
				begin
					INSERT INTO dbo.[S_BANK_FORMAT_BASE]([CODE], [NAME], [FTYPE], [FVALUE], [DATATYPE])  
					VALUES (@code, @name, @FTYPE, @FVALUE, @DATATYPE)  
				end
				else
				begin
					update S
					set [CODE] =@code, [NAME]= @name, [FTYPE] = @FTYPE, [FVALUE] = @FVALUE, [DATATYPE] = @DATATYPE
					from S_BANK_FORMAT_BASE S
					where CODE = @code
				end
		end
GO

GO
EXEC X_SET_PROP 'COLUMN_NUM_DOC_DIS', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''ALL_DISABILITY_SHEET'', oForm.ALIAS, ''LINK, NUMBER'', ''REF_DOC, NUM_DOC'', '''','''', " (REF_DOC IS NULL OR LAST_DIS = 1) AND LINK<>"+ str(eval(oForm.Alias+''.LINK''))+" and ref_empl ="+str(eval(oForm.Alias+''.REF_EMPL'')), .T., 1, oForm, oObj, "")'
GO

GO
EXEC X_SET_PROP 'COLUMN_CODE_EKR_DED_PR_DGH', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''DICTIONARY_ITEM'', oForm.ALIAS, ''LINK,CODE'', ''LINK_EKR,CODE_EKR'', '''', '''', "CODE LIKE ''21%'' OR CODE LIKE ''22%''  OR CODE LIKE ''26%'' OR CODE LIKE ''29%''", .T., 1, oForm, oObj, "")'
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='ESN_OPTIONS_7'

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_ESN_OPTIONS_7]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_ESN_OPTIONS_7]

CREATE TABLE  dbo._UPD_OPT_ESN_OPTIONS_7 (CODE VARCHAR(30), [SID] varbinary(85), VALUE VARCHAR(1000))

INSERT INTO _UPD_OPT_ESN_OPTIONS_7 (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 = 'ESN_OPTIONS_7')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'ESN_OPTIONS_7')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'ESN_OPTIONS_7')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'ESN_OPTIONS_7')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'ESN_OPTIONS_7'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'ESN_OPTIONS_7')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ESN_OPTIONS_7')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ESN_OPTIONS_7', 'Начислять доп. тариф только для полной ставки', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='ESN_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ESN_OPTIONS_7', NAME = 'Начислять доп. тариф только для полной ставки', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ESN_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ESN_OPTIONS_7'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_7', 'TITLE', 'Начислять доп. тариф только для полной ставки'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_7', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_7', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_7', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_7', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_7', 'CONTROL_NAME_EDIT', 'Acheckbox7'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_7', 'COMMENTARY', 'При включенной опции программа будет начислять страховые взносы по доп. тарифам только если у сотрудника по основной должности полная ставка. Если ставка не полная, то доп. тариф не начисляется.'
GO
/******--Восстановить, либо установить настройки на базе пользователя ******/
DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'ESN_OPTIONS_7' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_ESN_OPTIONS_7] WHERE CODE = 'ESN_OPTIONS_7')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'ESN_OPTIONS_7'), SID, VALUE FROM [dbo].[_UPD_OPT_ESN_OPTIONS_7] WHERE CODE = 'ESN_OPTIONS_7'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '1' FROM  dbo.S_OBJECTS WHERE CODE = 'ESN_OPTIONS_7'

GO

IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_ESN_OPTIONS_7]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_ESN_OPTIONS_7]

GO


EXEC DBO.W_SPERM_WRITE 'ESN_OPTIONS_7', 'Зарплата-КС', 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='ESN_OPTIONS_8'

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_ESN_OPTIONS_8]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_ESN_OPTIONS_8]

CREATE TABLE  dbo._UPD_OPT_ESN_OPTIONS_8 (CODE VARCHAR(30), [SID] varbinary(85), VALUE VARCHAR(1000))

INSERT INTO _UPD_OPT_ESN_OPTIONS_8 (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 = 'ESN_OPTIONS_8')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'ESN_OPTIONS_8')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'ESN_OPTIONS_8')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'ESN_OPTIONS_8')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'ESN_OPTIONS_8'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'ESN_OPTIONS_8')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ESN_OPTIONS_8')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ESN_OPTIONS_8', 'Начислять доп. тариф на доходы внутренних совместителяй', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='ESN_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ESN_OPTIONS_8', NAME = 'Начислять доп. тариф на доходы внутренних совместителяй', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ESN_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ESN_OPTIONS_8'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_8', 'TITLE', 'Начислять доп. тариф на доходы внутренних совместителяй'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_8', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_8', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_8', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_8', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_8', 'CONTROL_NAME_EDIT', 'Acheckbox8'
GO
EXEC X_SET_PROP 'ESN_OPTIONS_8', 'COMMENTARY', 'При включенной опции программа будет начислять страховые взносы по доп. тарифам на доходы внутренних совместителей.'
GO
/******--Восстановить, либо установить настройки на базе пользователя ******/
DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'ESN_OPTIONS_8' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_ESN_OPTIONS_8] WHERE CODE = 'ESN_OPTIONS_8')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'ESN_OPTIONS_8'), SID, VALUE FROM [dbo].[_UPD_OPT_ESN_OPTIONS_8] WHERE CODE = 'ESN_OPTIONS_8'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '0' FROM  dbo.S_OBJECTS WHERE CODE = 'ESN_OPTIONS_8'

GO

IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_ESN_OPTIONS_8]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_ESN_OPTIONS_8]

GO


EXEC DBO.W_SPERM_WRITE 'ESN_OPTIONS_8', 'Зарплата-КС', 63,0
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RELATED_LIST_SAL_SFIN]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[RELATED_LIST_SAL_SFIN]
GO

EXEC dbo.XI_CREATE_TEST_REC_FUNC 'SAL_SFIN'
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[SDOC_DIS_KIRUPDATE2]') AND OBJECTPROPERTY(id, N'IsTrigger') = 1)
DROP TRIGGER dbo.[SDOC_DIS_KIRUPDATE2]
GO

GO
/****** Объект: Сведения о трудовом стаже застрахованного лица (СЗВ-К)******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV_K_PACHKA')
	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_SZV_K_PACHKA')
	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_SZV_K_PACHKA')
	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_SZV_K_PACHKA')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV_K_PACHKA'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV_K_PACHKA')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_PACHKA', 'Сведения о трудовом стаже застрахованного лица (СЗВ-К)', 35, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICT_SAL_KADR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_PACHKA', NAME = 'Сведения о трудовом стаже застрахованного лица (СЗВ-К)', ORDERS = '35', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICT_SAL_KADR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='SA_SZV_K_PACHKA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_PACHKA_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_PACHKA_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_PACHKA_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_PACHKA_LINK', '№ п/п', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_PACHKA_LINK', NAME = '№ п/п', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_PACHKA_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_PACHKA_DATE', 'Дата формирования', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_PACHKA_DATE', NAME = 'Дата формирования', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_PACHKA_DATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA_NUMER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_PACHKA_NUMER', '№ первой пачки', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_PACHKA_NUMER', NAME = '№ первой пачки', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_PACHKA_NUMER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_PACHKA_TYPE', 'Тип сведений (код)', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_PACHKA_TYPE', NAME = 'Тип сведений (код)', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_PACHKA_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA_NTYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_PACHKA_NTYPE', 'Тип сведений', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_PACHKA_NTYPE', NAME = 'Тип сведений', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_PACHKA_NTYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA_PROVER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_PACHKA_PROVER', 'Проверка', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_PACHKA_PROVER', NAME = 'Проверка', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_PACHKA_PROVER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_PACHKA_CODE', 'Комментарий', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_PACHKA_CODE', NAME = 'Комментарий', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_PACHKA_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA_NUM_RASCH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_PACHKA_NUM_RASCH', 'Номер исходного расчета', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_PACHKA_NUM_RASCH', NAME = 'Номер исходного расчета', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_PACHKA_NUM_RASCH'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SVEDENIA', 'Сведения о застрахованном лице', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SVEDENIA', NAME = 'Сведения о застрахованном лице', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SVEDENIA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_DEP_PERIOD', 'Период трудовой или иной общественно-полезной деятельности', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_DEP_PERIOD', NAME = 'Период трудовой или иной общественно-полезной деятельности', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_DEP_PERIOD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_OSN', 'Стаж работы за расчетный период', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_OSN', NAME = 'Стаж работы за расчетный период', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_OSN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_DOP', 'Дополнительные сведения о льготном стаже', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_DOP', NAME = 'Дополнительные сведения о льготном стаже', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_DOP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SPR', 'Классификатор параметров персонифицированного учета', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SPR', NAME = 'Классификатор параметров персонифицированного учета', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SPR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_OPTIONS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_OPTIONS', 'Настройки СЗВ-К', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_OPTIONS', NAME = 'Настройки СЗВ-К', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_OPTIONS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_PFR_KATEG_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_PFR_KATEG_1', 'Категория застрахованного лица', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_PFR_KATEG_1', NAME = 'Категория застрахованного лица', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_PACHKA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_PFR_KATEG_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SVEDENIA_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SVEDENIA_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SVEDENIA_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA_PACHKA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SVEDENIA_PACHKA', '№ пачки', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SVEDENIA_PACHKA', NAME = '№ пачки', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SVEDENIA_PACHKA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA_ORDERS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SVEDENIA_ORDERS', '№ в пачке', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SVEDENIA_ORDERS', NAME = '№ в пачке', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SVEDENIA_ORDERS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA_FIO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SVEDENIA_FIO', 'Ф.И.О.', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SVEDENIA_FIO', NAME = 'Ф.И.О.', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SVEDENIA_FIO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA_FM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SVEDENIA_FM', 'Фамилия', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SVEDENIA_FM', NAME = 'Фамилия', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SVEDENIA_FM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA_IM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SVEDENIA_IM', 'Имя', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SVEDENIA_IM', NAME = 'Имя', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SVEDENIA_IM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA_OT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SVEDENIA_OT', 'Отчество', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SVEDENIA_OT', NAME = 'Отчество', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SVEDENIA_OT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA_PF_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SVEDENIA_PF_NUM', 'Страховой номер в ПФ', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SVEDENIA_PF_NUM', NAME = 'Страховой номер в ПФ', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SVEDENIA_PF_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA_ADDRESS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SVEDENIA_ADDRESS', 'Адрес', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SVEDENIA_ADDRESS', NAME = 'Адрес', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SVEDENIA_ADDRESS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVED_BIRTHDATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SVED_BIRTHDATE', 'Дата рождения', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SVED_BIRTHDATE', NAME = 'Дата рождения', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SVED_BIRTHDATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV4_SVEDENIA_DPER_VN_M_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV4_SVEDENIA_DPER_VN_M_1', 'вр.нетруд, мес.', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV4_SVEDENIA_DPER_VN_M_1', NAME = 'вр.нетруд, мес.', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV4_SVEDENIA_DPER_VN_M_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV4_SVEDENIA_DPER_VN_D_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV4_SVEDENIA_DPER_VN_D_1', 'вр.нетруд, дн.', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV4_SVEDENIA_DPER_VN_D_1', NAME = 'вр.нетруд, дн.', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV4_SVEDENIA_DPER_VN_D_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV4_SVEDENIA_DPER_OZ_M_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV4_SVEDENIA_DPER_OZ_M_1', 'Отпуск без З/П, мес.', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV4_SVEDENIA_DPER_OZ_M_1', NAME = 'Отпуск без З/П, мес.', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV4_SVEDENIA_DPER_OZ_M_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV4_SVEDENIA_ISUM_STR_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV4_SVEDENIA_ISUM_STR_1', 'Отпуск без З/П, дн.', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV4_SVEDENIA_ISUM_STR_1', NAME = 'Отпуск без З/П, дн.', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV4_SVEDENIA_ISUM_STR_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA_TER_USL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SVEDENIA_TER_USL', 'Территориальные условия труда, код', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SVEDENIA_TER_USL', NAME = 'Территориальные условия труда, код', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SVEDENIA_TER_USL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA_TER_KOEF')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SVEDENIA_TER_KOEF', 'Территориальные условия труда, коэфф.', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SVEDENIA_TER_KOEF', NAME = 'Территориальные условия труда, коэфф.', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SVEDENIA_TER_KOEF'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA_ALL_ST_Y')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SVEDENIA_ALL_ST_Y', 'Общий стаж, лет', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SVEDENIA_ALL_ST_Y', NAME = 'Общий стаж, лет', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SVEDENIA_ALL_ST_Y'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA_ALL_ST_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SVEDENIA_ALL_ST_M', 'Общий стаж, мес.', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SVEDENIA_ALL_ST_M', NAME = 'Общий стаж, мес.', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SVEDENIA_ALL_ST_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA_ALL_ST_D')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SVEDENIA_ALL_ST_D', 'Общий стаж, дн.', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SVEDENIA_ALL_ST_D', NAME = 'Общий стаж, дн.', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SVEDENIA'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SVEDENIA_ALL_ST_D'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_ORDERS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_ORDERS', '№ п/п', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_ORDERS', NAME = '№ п/п', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_ORDERS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV4_STAZH_DATE1_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV4_STAZH_DATE1_1', 'Начало периода', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV4_STAZH_DATE1_1', NAME = 'Начало периода', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV4_STAZH_DATE1_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DATE2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_DATE2', 'Конец периода', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_DATE2', NAME = 'Конец периода', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_DATE2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_POST_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_POST_NAME', 'Должность', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_POST_NAME', NAME = 'Должность', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_POST_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_F_TER_USL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_F_TER_USL', 'Территориальные условия', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_F_TER_USL', NAME = 'Территориальные условия', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_F_TER_USL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_TER_USL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_TER_USL', 'Код терр.условий', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_TER_USL', NAME = 'Код терр.условий', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_TER_USL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_N_TER_USL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_N_TER_USL', 'Наименование:Территориальные условия', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_N_TER_USL', NAME = 'Наименование:Территориальные условия', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_N_TER_USL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_TER_KOEF')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_TER_KOEF', 'Районный коэффициент', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_TER_KOEF', NAME = 'Районный коэффициент', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_TER_KOEF'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_F_OSOB_USL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_F_OSOB_USL', 'Особые условия', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_F_OSOB_USL', NAME = 'Особые условия', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_F_OSOB_USL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSOB_USL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_OSOB_USL', 'Код особого условия', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_OSOB_USL', NAME = 'Код особого условия', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_OSOB_USL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_N_OSOB_USL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_N_OSOB_USL', 'Наименование особого условия', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_N_OSOB_USL', NAME = 'Наименование особого условия', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_N_OSOB_USL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSOB_K1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_OSOB_K1', 'Код позиции списка №1', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_OSOB_K1', NAME = 'Код позиции списка №1', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_OSOB_K1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_N_OSOB_K1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_N_OSOB_K1', 'Наименование позиции списка №1', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_N_OSOB_K1', NAME = 'Наименование позиции списка №1', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_N_OSOB_K1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSOB_K2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_OSOB_K2', 'Код позиции списка №2', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_OSOB_K2', NAME = 'Код позиции списка №2', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_OSOB_K2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_N_OSOB_K2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_N_OSOB_K2', 'Наименование позиции списка №2', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_N_OSOB_K2', NAME = 'Наименование позиции списка №2', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_N_OSOB_K2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSOB_K3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_OSOB_K3', 'Код позиции списка №3', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_OSOB_K3', NAME = 'Код позиции списка №3', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_OSOB_K3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_N_OSOB_K3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_N_OSOB_K3', 'Наименование позиции списка №3', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_N_OSOB_K3', NAME = 'Наименование позиции списка №3', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_N_OSOB_K3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_F_IS_OSNOV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_F_IS_OSNOV', 'Исчисление страхового стажа', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_F_IS_OSNOV', NAME = 'Исчисление страхового стажа', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_F_IS_OSNOV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_IS_OSNOV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_IS_OSNOV', 'Код основания для исчисления трудового стажа', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_IS_OSNOV', NAME = 'Код основания для исчисления трудового стажа', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_IS_OSNOV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_N_IS_OSNOV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_N_IS_OSNOV', 'Наименование основания для исчисления трудового стажа', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_N_IS_OSNOV', NAME = 'Наименование основания для исчисления трудового стажа', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_N_IS_OSNOV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_IS_DOP_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_IS_DOP_M', 'Доп.св. для исчисления трудового стажа, м.', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_IS_DOP_M', NAME = 'Доп.св. для исчисления трудового стажа, м.', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_IS_DOP_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_IS_DOP_D')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_IS_DOP_D', 'Доп.св. для исчисления трудового стажа, дн.', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_IS_DOP_D', NAME = 'Доп.св. для исчисления трудового стажа, дн.', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_IS_DOP_D'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_IS_DOP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_IS_DOP', 'Доп.св для исчисления трудового стажа', 24, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_IS_DOP', NAME = 'Доп.св для исчисления трудового стажа', ORDERS = '24', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_IS_DOP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_N_IS_DOP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_N_IS_DOP', 'Наименование доп.сведения для исчисления трудового стажа', 25, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_N_IS_DOP', NAME = 'Наименование доп.сведения для исчисления трудового стажа', ORDERS = '25', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_N_IS_DOP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_F_UD_OSNOV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_F_UD_OSNOV', 'Условия для досрочного назначения тр.пенсии', 26, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_F_UD_OSNOV', NAME = 'Условия для досрочного назначения тр.пенсии', ORDERS = '26', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_F_UD_OSNOV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_UD_OSNOV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_UD_OSNOV', 'Основание для досрочного назначения тр.пенсии', 27, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_UD_OSNOV', NAME = 'Основание для досрочного назначения тр.пенсии', ORDERS = '27', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_UD_OSNOV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_N_UD_OSNOV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_N_UD_OSNOV', 'Наименование основания для досрочного назначения тр.пенсии', 28, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_N_UD_OSNOV', NAME = 'Наименование основания для досрочного назначения тр.пенсии', ORDERS = '28', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_N_UD_OSNOV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_UD_DOP_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_UD_DOP_M', 'Доп.усл.для доср. пенс.,м.', 29, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_UD_DOP_M', NAME = 'Доп.усл.для доср. пенс.,м.', ORDERS = '29', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_UD_DOP_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_UD_DOP_D')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_UD_DOP_D', 'Доп.усл.для доср. пенс.,дн.', 30, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_UD_DOP_D', NAME = 'Доп.усл.для доср. пенс.,дн.', ORDERS = '30', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_UD_DOP_D'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_UD_DOP_K')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_UD_DOP_K', 'Доп.усл.для доср. пенс.,значение', 31, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_UD_DOP_K', NAME = 'Доп.усл.для доср. пенс.,значение', ORDERS = '31', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_OSN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_UD_DOP_K'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SPR_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SPR_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SPR_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR_SPR_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SPR_SPR_CODE', 'Код справочника', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SPR_SPR_CODE', NAME = 'Код справочника', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SPR_SPR_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SPR_NAME', 'Справочник', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SPR_NAME', NAME = 'Справочник', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SPR_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SPR_CODE', 'Код', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SPR_CODE', NAME = 'Код', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SPR_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR_NAME_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SPR_NAME_1', 'Наименование', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SPR_NAME_1', NAME = 'Наименование', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SPR_NAME_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR_DATE1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SPR_DATE1', 'Начало периода', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SPR_DATE1', NAME = 'Начало периода', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SPR_DATE1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR_DATE2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SPR_DATE2', 'Конец периода', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SPR_DATE2', NAME = 'Конец периода', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SPR_DATE2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR_PAR1CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SPR_PAR1CODE', 'Код параметра №1', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SPR_PAR1CODE', NAME = 'Код параметра №1', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SPR_PAR1CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR_PAR1NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SPR_PAR1NAME', 'Наименование параметра №1', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SPR_PAR1NAME', NAME = 'Наименование параметра №1', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SPR_PAR1NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR_PAR2CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SPR_PAR2CODE', 'Код параметра №2', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SPR_PAR2CODE', NAME = 'Код параметра №2', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SPR_PAR2CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR_PAR2NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SPR_PAR2NAME', 'Наименование параметра №2', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SPR_PAR2NAME', NAME = 'Наименование параметра №2', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SPR_PAR2NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR_PAR3CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SPR_PAR3CODE', 'Код параметра №3', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SPR_PAR3CODE', NAME = 'Код параметра №3', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SPR_PAR3CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR_PAR3NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_SPR_PAR3NAME', 'Наименование параметра №3', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_SPR_PAR3NAME', NAME = 'Наименование параметра №3', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_SPR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_SPR_PAR3NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_OPT1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_OPT1', 'Количество строк в пачке', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_OPT1', NAME = 'Количество строк в пачке', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_OPT1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV4_SPR_CHECKED_1_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV4_SPR_CHECKED_1_1', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PFR_KATEG_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV4_SPR_CHECKED_1_1', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PFR_KATEG_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV4_SPR_CHECKED_1_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV4_SPR_CODE_1_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV4_SPR_CODE_1_1', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PFR_KATEG_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV4_SPR_CODE_1_1', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PFR_KATEG_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV4_SPR_CODE_1_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV4_SPR_NAME_2_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV4_SPR_NAME_2_1', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PFR_KATEG_1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV4_SPR_NAME_2_1', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_PFR_KATEG_1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV4_SPR_NAME_2_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_ORDERS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_ORDERS', '№ п/п', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_ORDERS', NAME = '№ п/п', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_ORDERS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_DATE1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_DATE1', 'Начало периода', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_DATE1', NAME = 'Начало периода', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_DATE1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_DATE2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_DATE2', 'Конец периода', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_DATE2', NAME = 'Конец периода', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_DATE2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_POST_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_POST_NAME', 'Должность', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_POST_NAME', NAME = 'Должность', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_POST_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_F_TER_USL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_F_TER_USL', 'Территориальные условия', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_F_TER_USL', NAME = 'Территориальные условия', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_F_TER_USL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_TER_USL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_TER_USL', 'Код терр.условий', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_TER_USL', NAME = 'Код терр.условий', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_TER_USL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_N_TER_USL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_N_TER_USL', 'Наименование:Территориальные условия', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_N_TER_USL', NAME = 'Наименование:Территориальные условия', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_N_TER_USL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_TER_KOEF')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_TER_KOEF', 'Районный коэффициент', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_TER_KOEF', NAME = 'Районный коэффициент', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_TER_KOEF'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_F_OSOB_USL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_F_OSOB_USL', 'Особые условия', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_F_OSOB_USL', NAME = 'Особые условия', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_F_OSOB_USL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_OSOB_USL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_OSOB_USL', 'Код особого условия', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_OSOB_USL', NAME = 'Код особого условия', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_OSOB_USL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_N_OSOB_USL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_N_OSOB_USL', 'Наименование особого условия', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_N_OSOB_USL', NAME = 'Наименование особого условия', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_N_OSOB_USL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_OSOB_K1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_OSOB_K1', 'Код позиции списка №1', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_OSOB_K1', NAME = 'Код позиции списка №1', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_OSOB_K1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SSZV_K_STAZH_D_N_OSOB_K1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SSZV_K_STAZH_D_N_OSOB_K1', 'Наименование позиции списка №1', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SSZV_K_STAZH_D_N_OSOB_K1', NAME = 'Наименование позиции списка №1', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SSZV_K_STAZH_D_N_OSOB_K1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_OSOB_K2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_OSOB_K2', 'Код позиции списка №2', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_OSOB_K2', NAME = 'Код позиции списка №2', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_OSOB_K2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_N_OSOB_K2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_N_OSOB_K2', 'Наименование позиции списка №2', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_N_OSOB_K2', NAME = 'Наименование позиции списка №2', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_N_OSOB_K2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_OSOB_K3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_OSOB_K3', 'Код позиции списка №3', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_OSOB_K3', NAME = 'Код позиции списка №3', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_OSOB_K3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_N_OSOB_K3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_N_OSOB_K3', 'Наименование позиции списка №3', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_N_OSOB_K3', NAME = 'Наименование позиции списка №3', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_N_OSOB_K3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_F_IS_OSNOV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_F_IS_OSNOV', 'Исчисление страхового стажа', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_F_IS_OSNOV', NAME = 'Исчисление страхового стажа', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_F_IS_OSNOV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_IS_OSNOV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_IS_OSNOV', 'Код основания для исчисления трудового стажа', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_IS_OSNOV', NAME = 'Код основания для исчисления трудового стажа', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_IS_OSNOV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_N_IS_OSNOV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_N_IS_OSNOV', 'Наименование основания для исчисления трудового стажа', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_N_IS_OSNOV', NAME = 'Наименование основания для исчисления трудового стажа', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_N_IS_OSNOV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_IS_DOP_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_IS_DOP_M', 'Доп.св. для исчисления трудового стажа, м.', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_IS_DOP_M', NAME = 'Доп.св. для исчисления трудового стажа, м.', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_IS_DOP_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_IS_DOP_D')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_IS_DOP_D', 'Доп.св. для исчисления трудового стажа, дн.', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_IS_DOP_D', NAME = 'Доп.св. для исчисления трудового стажа, дн.', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_IS_DOP_D'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_IS_DOP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_IS_DOP', 'Доп.св для исчисления трудового стажа', 24, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_IS_DOP', NAME = 'Доп.св для исчисления трудового стажа', ORDERS = '24', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_IS_DOP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_N_IS_DOP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_N_IS_DOP', 'Наименование доп.сведения для исчисления трудового стажа', 25, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_N_IS_DOP', NAME = 'Наименование доп.сведения для исчисления трудового стажа', ORDERS = '25', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_N_IS_DOP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_F_UD_OSNOV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_F_UD_OSNOV', 'Условия для досрочного назначения тр.пенсии', 26, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_F_UD_OSNOV', NAME = 'Условия для досрочного назначения тр.пенсии', ORDERS = '26', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_F_UD_OSNOV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_UD_OSNOV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_UD_OSNOV', 'Основание для досрочного назначения тр.пенсии', 27, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_UD_OSNOV', NAME = 'Основание для досрочного назначения тр.пенсии', ORDERS = '27', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_UD_OSNOV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_N_UD_OSNOV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_N_UD_OSNOV', 'Наименование основания для досрочного назначения тр.пенсии', 28, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_N_UD_OSNOV', NAME = 'Наименование основания для досрочного назначения тр.пенсии', ORDERS = '28', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_N_UD_OSNOV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_UD_DOP_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_UD_DOP_M', 'Доп.усл.для доср. пенс.,м.', 29, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_UD_DOP_M', NAME = 'Доп.усл.для доср. пенс.,м.', ORDERS = '29', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_UD_DOP_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_UD_DOP_D')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_UD_DOP_D', 'Доп.усл.для доср. пенс.,дн.', 30, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_UD_DOP_D', NAME = 'Доп.усл.для доср. пенс.,дн.', ORDERS = '30', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_UD_DOP_D'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_D_UD_DOP_K')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_STAZH_D_UD_DOP_K', 'Доп.усл.для доср. пенс.,значение', 31, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_STAZH_D_UD_DOP_K', NAME = 'Доп.усл.для доср. пенс.,значение', ORDERS = '31', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_STAZH_DOP'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_STAZH_D_UD_DOP_K'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_D_P_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_D_P_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_D_P_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_D_P_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_D_P_ORDERS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_D_P_ORDERS', '№ п/п', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_D_P_ORDERS', NAME = '№ п/п', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_D_P_ORDERS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_D_P_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_D_P_NAME', 'Наименование организации(краткое)', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_D_P_NAME', NAME = 'Наименование организации(краткое)', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_D_P_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_D_P_INN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_D_P_INN', 'ИНН', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_D_P_INN', NAME = 'ИНН', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_D_P_INN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_D_P_KPP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_D_P_KPP', 'КПП', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_D_P_KPP', NAME = 'КПП', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_D_P_KPP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_D_P_OKPO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_D_P_OKPO', 'ОКПО', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_D_P_OKPO', NAME = 'ОКПО', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_D_P_OKPO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_D_P_VID_WORK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_D_P_VID_WORK', 'Вид деятельности', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_D_P_VID_WORK', NAME = 'Вид деятельности', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_D_P_VID_WORK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_D_P_VID_WORK_С')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_D_P_VID_WORK_С', 'Вид деятельности (код)', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_D_P_VID_WORK_С', NAME = 'Вид деятельности (код)', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_DEP_PERIOD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_D_P_VID_WORK_С'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'TITLE', 'Сведения о трудовом стаже застрахованного лица (СЗВ-К)'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'INIT_OBJECT_METHOD', 'X_SPISOK("SA_SZV_K_PACHKA")'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "SA_SZV_K_PACHKA", "SA_SZV_K_PACHKA_DELETE", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'SAVE_OBJECT_METHOD', 'SA_SZV_K_PACHKA_SAVE(oForm)'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'EDIT_OBJECT_METHOD', 'SALARY_BROW(''SA_SZV_K_PACHKA_EDIT'')'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'SELECT_RECORDS_METHOD', 'sd_select_document_list_zb1(''SA_SZV_K_PACHKA'')'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST(''SA_SZV_K_PACHKA'')'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'OPEN_CODE', 'CODE'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'MSG_SEL_ALL', '[Отобраны все]'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'MSG_SEL_NONE', '[Не отобрано]'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'MSG_SEL_ONE', 'IIF(ISNULL(LINK),'''', ALLT(STR(LINK,10,0)) + [-] + IIF(ISNULL(TYPE_N), '''',TYPE_N)'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'MSG_SEL_SOME', '[Отобрано:]'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'SERVER_TABLE_NAME', 'SZV_K_PACHKA'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'OPTIONS_OBJECT_CODE', 'SA_SZV_k_OPTIONS'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'HELP_TOPIC', '42'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'COMMENTARY', 'Режим "Сведения о трудовом стаже застрахованного лица (СЗВ-К)" предназначен для подготовки отчетов и электронных файлов формы СЗВ-К для передачи их в Пенсионный фонд.

Режим имеет свои настройки. Для просмотра настроек нажмите кнопку "Настройки" на панели инструментов списка расчетов, который отображается при открытии режима "Персонифицированный учет". В настройках указываются параметры: "Количество строк в печке" .

Для формирования расчета заполните поля в верхней части формы:
"№ первой пачки" - с этого номера начнется нумерация пачек;
"Дата расчета" - здесь указывается дата заполнения сведений;

Расчет формируется за период до 01.01.2002 г. 
Дата расчета (заполнения) должна быть всегда после даты составления.
"Тип сведений" заполняется в соответствии с назначением.

Поле "Проверка" устанавливается автоматически. Если поле имеет значение "Не выполнена", то функции "Печать" и "Выгрузка" работать не будут'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_CHECKED', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_CHECKED', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_CHECKED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_LINK', 'TITLE', '№ п/п'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_LINK', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_LINK', 'CONTROLSOURCE', 'm.cAlias + ".LINK"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_LINK', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_LINK', 'SHORT_CODE_OBJ', 'LINK'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_DATE', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_DATE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_DATE', 'CONTROLSOURCE', 'm.cAlias + ".DATE"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_DATE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_DATE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_DATE', 'TYPE_FIELD_DICT', 'datetime'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_DATE', 'SHORT_CODE_OBJ', 'DATE'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_DATE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_DATE', 'CONTROL_NAME_EDIT', 'aSelDate1'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUMER', 'TITLE', '№ первой пачки'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUMER', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUMER', 'CONTROLSOURCE', 'm.cAlias + ".numer"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUMER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUMER', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUMER', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".numer"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUMER', 'CONTROL_NAME_EDIT', 'atextbox1'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUMER', 'INPUT_MASK', '99999'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_TYPE', 'TITLE', 'Тип сведений'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_TYPE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_TYPE', 'CONTROLSOURCE', 'm.cAlias + ".type_sved"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_TYPE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_TYPE', 'ROWSOURCE', '''исходные,корректирующие,отменяющие'''
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_TYPE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_TYPE', 'TYPE_FIELD_DICT', 'tinyint'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_TYPE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".type_sved"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_TYPE', 'CONTROL_NAME_EDIT', 'acombobox2'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NTYPE', 'TITLE', 'Тип сведений'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NTYPE', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NTYPE', 'CONTROLSOURCE', 'm.cAlias + ".n_type_sved"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NTYPE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NTYPE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NTYPE', 'TYPE_FIELD_DICT', 'tinyint'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NTYPE', 'SHORT_CODE_OBJ', 'n_type_sved'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NTYPE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_type_sved"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_PROVER', 'TITLE', 'Проверка'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_PROVER', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_PROVER', 'CONTROLSOURCE', 'm.cAlias + ".nproverka"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_PROVER', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_PROVER', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".nproverka"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_PROVER', 'CONTROL_NAME_EDIT', 'Atextbox2'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_CODE', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_CODE', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_CODE', 'VISIBLE', '14'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_CODE', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_CODE', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_CODE', 'COMMENTARY', 'Комментарий'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUM_RASCH', 'TITLE', 'Номер исходного расчета'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUM_RASCH', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUM_RASCH', 'CONTROLSOURCE', 'm.cAlias + ".LINK_ISHOD"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUM_RASCH', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUM_RASCH', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUM_RASCH', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUM_RASCH', 'SHORT_CODE_OBJ', 'LINK_ISHOD'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUM_RASCH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK_ISHOD"'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUM_RASCH', 'CONTROL_NAME_EDIT', 'aSel_sprNR'
GO
EXEC X_SET_PROP 'SA_SZV_K_PACHKA_NUM_RASCH', 'COMMENTARY', 'Номер исходного расчета'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA', 'TITLE', 'Сведения о застрахованном лице'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "SA_SZV_k_SVEDENIA", "SA_SZV_k_SVEDENIA_DELETE", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA', 'CLOSE_CODE', 'LINK1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA', 'SELECT_RECORDS_METHOD', 'salary_select_table(m.nLink_SA_SZV_k_PACHKA, m.cAlias,''SA_SZV_k_SVEDENIA'',''*'')'
GO
EXEC X_SET_PROP 'SA_SZV_K_DEP_PERIOD', 'TITLE', 'Период трудовой или иной общественно-полезной деятельности'
GO
EXEC X_SET_PROP 'SA_SZV_K_DEP_PERIOD', 'SAVE_OBJECT_METHOD', 'sa_szv_k_sv_wd_save(m.SA_SZV_K_SV_WD_FORM)'
GO
EXEC X_SET_PROP 'SA_SZV_K_DEP_PERIOD', 'EDIT_OBJECT_METHOD', 'SALARY_BROW(''SA_SZV_K_SV_WD_EDIT'',m.oForm,1)'
GO
EXEC X_SET_PROP 'SA_SZV_K_DEP_PERIOD', 'CLOSE_CODE', 'LINK1'
GO
EXEC X_SET_PROP 'SA_SZV_K_DEP_PERIOD', 'SELECT_RECORDS_METHOD', 'salary_select_table(m.nLink_SA_SZV_K_SVEDENIA, m.cAlias,''SA_SZV_K_sved_WORK_DEP'',''*'')'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSN', 'TITLE', 'Стаж работы за расчетный период'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSN', 'SAVE_OBJECT_METHOD', 'SA_SZV_K_STAZH_SAVE(m.SA_SZV_K_STAZH_FORM)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSN', 'EDIT_OBJECT_METHOD', 'SALARY_BROW(''SA_SZV_K_STAZH_EDIT'',m.oForm,1)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSN', 'CLOSE_CODE', 'LINK1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSN', 'SELECT_RECORDS_METHOD', 'salary_select_table(m.nLink_SA_SZV_K_SVED_WORK_DEP, m.cAlias,''SA_SZV_K_STAZH'',''ttod(date1) as date_n, ttod(date2) as date_k,*'')'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_DOP', 'TITLE', 'Дополнительные сведения о льготном стаже'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_DOP', 'SAVE_OBJECT_METHOD', 'SA_SZV_K_STAZH_DOP_SAVE(m.SA_SZV_K_STAZH_DOP_FORM)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_DOP', 'EDIT_OBJECT_METHOD', 'SALARY_BROW(''SA_SZV_K_STAZH_EDIT'',m.oForm,1)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_DOP', 'CLOSE_CODE', 'LINK1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_DOP', 'SELECT_RECORDS_METHOD', 'salary_select_table(m.nLink_SA_SZV_K_STAZH, m.cAlias,''SA_SZV_K_STAZH_DOP'',''ttod(date1) as date_n, ttod(date2) as date_k,*'')'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR', 'TITLE', 'Классификатор параметров персонифицированного учета'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR', 'INIT_OBJECT_METHOD', 'x_spisok(m.Obj_Code)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "SA_SZV4_SPR", "SA_SZV4_SPR_DELETE", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR', 'SAVE_OBJECT_METHOD', 'X_SAVE(''SA_SZV4_SPR_SAVE'', m.cAlias,"spr_code, code, name,SQLNULL(date1),SQLNULL(date2),par1code,par1name,par2code,par2name,par3code,par3name","SA_SZV4_SPR")'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR', 'EDIT_OBJECT_METHOD', 'SALARY_BROW(''SA_SZV4_SPR_EDIT'',,)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_LIST(''SA_SZV4_SPR'')'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST(''SA_SZV4_SPR'')'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPTIONS', 'TITLE', 'Настройки СЗВ-К'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPTIONS', 'EDIT_OBJECT_METHOD', 'SALARY_FORM_LOAD(''sa_options'',''"SA_SZV_K_OPTIONS"'')'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPTIONS', 'COMMENTARY', 'Настройки устанавливают параметры для режима "СЗВ-К"'
GO
EXEC X_SET_PROP 'SA_PFR_KATEG_1', 'TITLE', 'Категория застрахованного лица'
GO
EXEC X_SET_PROP 'SA_PFR_KATEG_1', 'INIT_OBJECT_METHOD', 'x_spisok(m.Obj_Code)'
GO
EXEC X_SET_PROP 'SA_PFR_KATEG_1', 'EDIT_OBJECT_METHOD', 'SALARY_BROW(''SA_SZV4_SPR_EDIT'',,)'
GO
EXEC X_SET_PROP 'SA_PFR_KATEG_1', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''SA_PFR_KATEG'')'
GO
EXEC X_SET_PROP 'SA_PFR_KATEG_1', 'OPEN_CODE', 'CODE'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_CHECKED', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_CHECKED', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_CHECKED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_PACHKA', 'TITLE', '№ пач.'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_PACHKA', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_PACHKA', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_PACHKA', 'CONTROLSOURCE', 'm.cAlias+ ".pachka"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_PACHKA', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_PACHKA', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_PACHKA', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_PACHKA', 'CONTROLSOURCE_EDIT', 'm.cAlias+ ".pachka"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ORDERS', 'TITLE', '№'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ORDERS', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ORDERS', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ORDERS', 'CONTROLSOURCE', 'm.cAlias+ ".orders"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ORDERS', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ORDERS', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ORDERS', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ORDERS', 'CONTROLSOURCE_EDIT', 'm.cAlias+ ".orders"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_FIO', 'TITLE', 'Ф.И.О.'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_FIO', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_FIO', 'CONTROLSOURCE', 'm.cAlias + ".FIO"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_FIO', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_FIO', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_FIO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FIO"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_FM', 'TITLE', 'Фамилия'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_FM', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_FM', 'CONTROLSOURCE', 'm.cAlias + ".FM"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_FM', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_FM', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_FM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FM"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_FM', 'CONTROL_NAME_EDIT', 'Atextbox2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_IM', 'TITLE', 'Имя'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_IM', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_IM', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_IM', 'CONTROLSOURCE', 'm.cAlias + ".IM"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_IM', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_IM', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_IM', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_IM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".IM"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_OT', 'TITLE', 'Отчество'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_OT', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_OT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_OT', 'CONTROLSOURCE', 'm.cAlias + ".OT"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_OT', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_OT', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_OT', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_OT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".OT"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_PF_NUM', 'TITLE', 'Страховой номер в ПФ'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_PF_NUM', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_PF_NUM', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_PF_NUM', 'CONTROLSOURCE', 'm.cAlias + ".PF_NUM"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_PF_NUM', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_PF_NUM', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_PF_NUM', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_PF_NUM', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".PF_NUM"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ADDRESS', 'TITLE', 'Адрес'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ADDRESS', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ADDRESS', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ADDRESS', 'CONTROLSOURCE', 'm.cAlias + ".ADDRESS"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ADDRESS', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ADDRESS', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ADDRESS', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ADDRESS', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ADDRESS"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVED_BIRTHDATE', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVED_BIRTHDATE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVED_BIRTHDATE', 'CONTROLSOURCE', 'm.cAlias + ".BIRTHDATE"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVED_BIRTHDATE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVED_BIRTHDATE', 'TYPE_FIELD_DICT', 'datetime'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVED_BIRTHDATE', 'SHORT_CODE_OBJ', 'BIRTHDATE'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVED_BIRTHDATE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".BIRTHDATE"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVED_BIRTHDATE', 'CONTROL_NAME_EDIT', 'aSelDateB'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_M_1', 'TITLE', 'вр.нетруд, мес.'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_M_1', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_M_1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_M_1', 'CONTROLSOURCE', 'm.cAlias + ".dper_vn_m"'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_M_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_M_1', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_M_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_M_1', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_M_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".dper_vn_m"'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_M_1', 'INPUT_MASK', '999 999 999.99'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_D_1', 'TITLE', 'вр.нетруд, дн.'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_D_1', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_D_1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_D_1', 'CONTROLSOURCE', 'm.cAlias + ".dper_vn_d"'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_D_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_D_1', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_D_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_D_1', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_D_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".dper_vn_d"'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_VN_D_1', 'INPUT_MASK', '999 999 999.99'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_OZ_M_1', 'TITLE', 'Отпуск без З/П, мес.'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_OZ_M_1', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_OZ_M_1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_OZ_M_1', 'CONTROLSOURCE', 'm.cAlias + ".dper_oz_m"'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_OZ_M_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_OZ_M_1', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_OZ_M_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_OZ_M_1', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_OZ_M_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".dper_oz_m"'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_DPER_OZ_M_1', 'INPUT_MASK', '999 999 999.99'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_ISUM_STR_1', 'TITLE', 'Отпуск без З/П, дн.'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_ISUM_STR_1', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_ISUM_STR_1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_ISUM_STR_1', 'CONTROLSOURCE', 'm.cAlias + ".isum_str"'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_ISUM_STR_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_ISUM_STR_1', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_ISUM_STR_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_ISUM_STR_1', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_ISUM_STR_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".isum_str"'
GO
EXEC X_SET_PROP 'SA_SZV4_SVEDENIA_ISUM_STR_1', 'INPUT_MASK', '999 999 999.99'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_USL', 'TITLE', 'Тер.усл., код'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_USL', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_USL', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.bspisok.bgrid1.recordsource, ''CODE,NAME'', ''TER_USL,N_TER_USL'', '''', '''', "SPR_CODE = ''TERR_USL'' ", .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_USL', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_USL', 'CONTROLSOURCE', 'm.cAlias+ ".ter_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_USL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_USL', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_USL', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_USL', 'SHORT_CODE_OBJ', 'ter_usl'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_USL', 'CONTROLSOURCE_EDIT', 'm.cAlias+ ".ter_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_USL', 'CONTROL_NAME_EDIT', 'Asel_sprUSL'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_USL', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_USL', 'FIELD_DATA', 'ter_usl'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_KOEF', 'TITLE', 'Тер. усл., коэфф.'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_KOEF', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_KOEF', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_KOEF', 'CONTROLSOURCE', 'm.cAlias+ ".ter_koef"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_KOEF', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_KOEF', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_KOEF', 'TYPE_FIELD_DICT', 'numeric(3,2)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_KOEF', 'CONTROLSOURCE_EDIT', 'm.cAlias+ ".ter_koef"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_KOEF', 'CONTROL_NAME_EDIT', 'Atextbox6'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_TER_KOEF', 'COMMENTARY', 'Категория'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_Y', 'TITLE', 'Общий стаж, лет'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_Y', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_Y', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_Y', 'CONTROLSOURCE', 'm.cAlias + ".all_stazh_y"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_Y', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_Y', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_Y', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_Y', 'TYPE_FIELD_DICT', 'NUMERIC(2)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_Y', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".all_stazh_y"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_Y', 'CONTROL_NAME_EDIT', 'Atextbox7'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_Y', 'INPUT_MASK', '99'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_M', 'TITLE', 'Общий стаж, мес.'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_M', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_M', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_M', 'CONTROLSOURCE', 'm.cAlias + ".all_stazh_m"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_M', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_M', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_M', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_M', 'TYPE_FIELD_DICT', 'NUMERIC(2)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_M', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".all_stazh_m"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_M', 'CONTROL_NAME_EDIT', 'Atextbox8'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_M', 'INPUT_MASK', '99'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_D', 'TITLE', 'Общий стаж, дн.'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_D', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_D', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_D', 'CONTROLSOURCE', 'm.cAlias + ".all_stazh_d"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_D', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_D', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_D', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_D', 'TYPE_FIELD_DICT', 'NUMERIC(2)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_D', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".all_stazh_d"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_D', 'CONTROL_NAME_EDIT', 'Atextbox9'
GO
EXEC X_SET_PROP 'SA_SZV_K_SVEDENIA_ALL_ST_D', 'INPUT_MASK', '99'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_CHECKED', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_CHECKED', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_CHECKED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_ORDERS', 'TITLE', '№ п/п'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_ORDERS', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_ORDERS', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_ORDERS', 'CONTROLSOURCE', 'm.cAlias+ ".orders"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_ORDERS', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_ORDERS', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_ORDERS', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_ORDERS', 'CONTROLSOURCE_EDIT', 'm.cAlias+ ".orders"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_ORDERS', 'CONTROL_NAME_EDIT', 'Atextbox1'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_DATE1_1', 'TITLE', 'Нач.пер.'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_DATE1_1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_DATE1_1', 'CONTROLSOURCE', 'm.cAlias + ".date_n"'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_DATE1_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_DATE1_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_DATE1_1', 'TYPE_FIELD_DICT', 'datetime'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_DATE1_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".date_n"'
GO
EXEC X_SET_PROP 'SA_SZV4_STAZH_DATE1_1', 'CONTROL_NAME_EDIT', 'Aseldate2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_DATE2', 'TITLE', 'Кон.пер.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_DATE2', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_DATE2', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_DATE2', 'CONTROLSOURCE', 'm.cAlias + ".date_k"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_DATE2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_DATE2', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_DATE2', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_DATE2', 'TYPE_FIELD_DICT', 'datetime'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_DATE2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".date_k"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_DATE2', 'CONTROL_NAME_EDIT', 'Aseldate3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_POST_NAME', 'TITLE', 'Должность'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_POST_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_POST_NAME', 'CONTROLSOURCE', 'm.cAlias+".POST"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_POST_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_POST_NAME', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_POST_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_POST_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(150)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_POST_NAME', 'SHORT_CODE_OBJ', 'POST'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_POST_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".POST"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_POST_NAME', 'CONTROL_NAME_EDIT', 'atextBox2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_POST_NAME', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 16px"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_POST_NAME', 'FIELD_DATA', 'post'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_TER_USL', 'TITLE', 'Терр.усл.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_TER_USL', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_TER_USL', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_TER_USL', 'CONTROLSOURCE', 'm.cAlias + ".f_ter_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_TER_USL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_TER_USL', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_TER_USL', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_TER_USL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".f_ter_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_USL', 'TITLE', 'Код терр.усл'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_USL', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_USL', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.ALIAS, ''CODE,NAME'', ''TER_USL,N_TER_USL'', '''', '''', "SPR_CODE = ''TERR_USL'' and DATE BETWEEN DATE1 AND COALESCE(DATE2,''30000101'')", .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_USL', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_USL', 'CONTROLSOURCE', 'm.cAlias + ".ter_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_USL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_USL', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_USL', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_USL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ter_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_USL', 'CONTROL_NAME_EDIT', 'apageframe1.Page1.Asel_spr4'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_TER_USL', 'TITLE', 'Терр.усл.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_TER_USL', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_TER_USL', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_TER_USL', 'CONTROLSOURCE', 'm.cAlias + ".n_ter_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_TER_USL', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_TER_USL', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_TER_USL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_ter_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_TER_USL', 'CONTROL_NAME_EDIT', 'apageframe1.Page1.aTextBox5'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_KOEF', 'TITLE', 'Районный коэффициент'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_KOEF', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_KOEF', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_KOEF', 'CONTROLSOURCE', 'm.cAlias + ".ter_koef"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_KOEF', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_KOEF', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_KOEF', 'TYPE_FIELD_DICT', 'NUMERIC(3,2)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_KOEF', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ter_koef"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_TER_KOEF', 'CONTROL_NAME_EDIT', 'apageframe1.Page1.Atextbox6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_OSOB_USL', 'TITLE', 'Особ.усл.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_OSOB_USL', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_OSOB_USL', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_OSOB_USL', 'CONTROLSOURCE', 'm.cAlias + ".f_osob_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_OSOB_USL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_OSOB_USL', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_OSOB_USL', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_OSOB_USL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".f_osob_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_USL', 'TITLE', 'Код особ.усл.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_USL', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_USL', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.ALIAS, ''CODE,NAME'', ''OSOB_USL,N_OSOB_USL'', '''', '''', "SPR_CODE = ''OSOB_USL_TRUDA'' and DATE BETWEEN DATE1 AND COALESCE(DATE2,''30000101'')", .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_USL', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_USL', 'CONTROLSOURCE', 'm.cAlias + ".osob_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_USL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_USL', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_USL', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_USL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".osob_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_USL', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.Asel_spr7'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_USL', 'TITLE', 'Наимен.особ.усл.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_USL', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_USL', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_USL', 'CONTROLSOURCE', 'm.cAlias + ".n_osob_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_USL', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_USL', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_USL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_osob_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_USL', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.aTextBox8'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K1', 'TITLE', 'Код позиции списка №1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K1', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.ALIAS, ''CODE,NAME'', ''osob_k1,n_osob_k1'', '''', '''', "SPR_CODE = ''SPISOK1'' and DATE BETWEEN DATE1 AND COALESCE(DATE2,''30000101'')", .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K1', 'CONTROLSOURCE', 'm.cAlias + ".osob_k1"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K1', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K1', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".osob_k1"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K1', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.Asel_spr9'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K1', 'TITLE', 'Наим. поз.списка №1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K1', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K1', 'CONTROLSOURCE', 'm.cAlias + ".n_osob_k1"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K1', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K1', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_osob_k1"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K1', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.aTextBox10'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K2', 'TITLE', 'Код позиции списка №2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K2', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K2', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.ALIAS, ''CODE,NAME'', ''osob_k2,n_osob_k2'', '''', '''', "SPR_CODE = ''SPISOK2'' and DATE BETWEEN DATE1 AND COALESCE(DATE2,''30000101'')", .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K2', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K2', 'CONTROLSOURCE', 'm.cAlias + ".osob_k2"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K2', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K2', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".osob_k2"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K2', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.Asel_spr11'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K2', 'TITLE', 'Наим. поз.списка №2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K2', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K2', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K2', 'CONTROLSOURCE', 'm.cAlias + ".n_osob_k2"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K2', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K2', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_osob_k2"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K2', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.aTextBox12'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K3', 'TITLE', 'Код позиции списка №3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K3', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K3', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K3', 'CONTROLSOURCE', 'm.cAlias + ".osob_k3"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K3', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K3', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K3', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".osob_k3"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_OSOB_K3', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.Asel_spr13'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K3', 'TITLE', 'Наим. поз.списка №3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K3', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K3', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K3', 'CONTROLSOURCE', 'm.cAlias + ".n_osob_k3"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K3', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K3', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_osob_k3"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_OSOB_K3', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.aTextBox14'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_IS_OSNOV', 'TITLE', 'Исч.стаж.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_IS_OSNOV', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_IS_OSNOV', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_IS_OSNOV', 'CONTROLSOURCE', 'm.cAlias + ".f_is_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_IS_OSNOV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_IS_OSNOV', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_IS_OSNOV', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_IS_OSNOV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".f_is_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_OSNOV', 'TITLE', 'Основ.тр.ст.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_OSNOV', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_OSNOV', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.ALIAS, ''CODE,NAME'', ''is_osnov,n_is_osnov'', '''', '''', "SPR_CODE = ''ISCHISL_STAZH_OSNOV'' and DATE BETWEEN DATE1 AND COALESCE(DATE2,''30000101'')", .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_OSNOV', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_OSNOV', 'CONTROLSOURCE', 'm.cAlias + ".is_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_OSNOV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_OSNOV', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_OSNOV', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_OSNOV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".is_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_OSNOV', 'CONTROL_NAME_EDIT', 'apageframe1.Page3.Asel_spr15'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_IS_OSNOV', 'TITLE', 'Основ.тр.ст.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_IS_OSNOV', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_IS_OSNOV', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_IS_OSNOV', 'CONTROLSOURCE', 'm.cAlias + ".n_is_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_IS_OSNOV', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_IS_OSNOV', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_IS_OSNOV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_is_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_IS_OSNOV', 'CONTROL_NAME_EDIT', 'apageframe1.Page3.aTextBox16'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_M', 'TITLE', 'Доп. св. для исчисления трудового стажа, м.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_M', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_M', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_M', 'CONTROLSOURCE', 'm.cAlias + ".is_dop_m"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_M', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_M', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_M', 'TYPE_FIELD_DICT', 'tinyint'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_M', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".is_dop_m"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_M', 'CONTROL_NAME_EDIT', 'apageframe1.Page3.aTextBox17'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_D', 'TITLE', 'Доп. св. для исчисления трудового стажа, дн.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_D', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_D', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_D', 'CONTROLSOURCE', 'm.cAlias + ".is_dop_d"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_D', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_D', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_D', 'TYPE_FIELD_DICT', 'tinyint'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_D', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".is_dop_d"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP_D', 'CONTROL_NAME_EDIT', 'apageframe1.Page3.aTextBox18'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP', 'TITLE', 'Доп.свед.тр.ст.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.ALIAS, ''CODE,NAME'', ''is_dop,n_is_dop'', '''', '''', "SPR_CODE = ''ISCHISL_STAZH_DOP_SV'' and DATE BETWEEN DATE1 AND COALESCE(DATE2,''30000101'')", .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP', 'CONTROLSOURCE', 'm.cAlias + ".is_dop"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".is_dop"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_IS_DOP', 'CONTROL_NAME_EDIT', 'apageframe1.Page3.Asel_spr19'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_IS_DOP', 'TITLE', 'Доп.свед.тр.ст.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_IS_DOP', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_IS_DOP', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_IS_DOP', 'CONTROLSOURCE', 'm.cAlias + ".n_is_dop"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_IS_DOP', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_IS_DOP', 'TYPE_FIELD_DICT', 'varchar(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_IS_DOP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_is_dop"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_IS_DOP', 'CONTROL_NAME_EDIT', 'apageframe1.Page3.aTextBox20'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_UD_OSNOV', 'TITLE', 'Усл.доср.пенс.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_UD_OSNOV', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_UD_OSNOV', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_UD_OSNOV', 'CONTROLSOURCE', 'm.cAlias + ".f_ud_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_UD_OSNOV', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_UD_OSNOV', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_F_UD_OSNOV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".f_ud_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_OSNOV', 'TITLE', 'Осн.доср.пенс.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_OSNOV', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_OSNOV', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.ALIAS, ''CODE,NAME'', ''ud_osnov,n_ud_osnov'', '''', '''', "SPR_CODE = ''DOSR_NAZN_PEN_OSNOV'' and DATE BETWEEN DATE1 AND COALESCE(DATE2,''30000101'')", .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_OSNOV', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_OSNOV', 'CONTROLSOURCE', 'm.cAlias + ".ud_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_OSNOV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_OSNOV', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_OSNOV', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_OSNOV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ud_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_OSNOV', 'CONTROL_NAME_EDIT', 'apageframe1.Page4.Asel_spr21'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_UD_OSNOV', 'TITLE', 'Осн.доср.пенс.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_UD_OSNOV', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_UD_OSNOV', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_UD_OSNOV', 'CONTROLSOURCE', 'm.cAlias + ".n_ud_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_UD_OSNOV', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_UD_OSNOV', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_UD_OSNOV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_ud_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_N_UD_OSNOV', 'CONTROL_NAME_EDIT', 'apageframe1.Page4.aTextBox22'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_M', 'TITLE', 'Доп.усл.для доср. пенс.,м.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_M', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_M', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_M', 'CONTROLSOURCE', 'm.cAlias + ".ud_dop_m"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_M', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_M', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_M', 'TYPE_FIELD_DICT', 'tinyint'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_M', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ud_dop_m"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_M', 'CONTROL_NAME_EDIT', 'apageframe1.Page4.aTextBox23'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_D', 'TITLE', 'Доп.усл.для доср. пенс.,дн.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_D', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_D', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_D', 'CONTROLSOURCE', 'm.cAlias + ".ud_dop_d"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_D', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_D', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_D', 'TYPE_FIELD_DICT', 'tinyint'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_D', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ud_dop_d"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_D', 'CONTROL_NAME_EDIT', 'apageframe1.Page4.aTextBox24'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_K', 'TITLE', 'Доп.усл.для доср. пенс.,значение'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_K', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_K', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_K', 'CONTROLSOURCE', 'm.cAlias + ".ud_dop_k"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_K', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_K', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_K', 'TYPE_FIELD_DICT', 'NUMERIC(18,2)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_K', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ud_dop_k"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_UD_DOP_K', 'CONTROL_NAME_EDIT', 'apageframe1.Page4.aTextBox25'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_CHECKED', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_CHECKED', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_CHECKED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_SPR_CODE', 'TITLE', 'Код справочника'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_SPR_CODE', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_SPR_CODE', 'CONTROLSOURCE', 'm.cAlias+ ".spr_code"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_SPR_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_SPR_CODE', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_SPR_CODE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_SPR_CODE', 'TYPE_FIELD_DICT', 'varchar(20)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_SPR_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+ ".spr_code"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_SPR_CODE', 'CONTROL_NAME_EDIT', 'aComboBox1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME', 'TITLE', 'Справочник'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME', 'CONTROLSOURCE', 'm.cAlias + ".spr_name"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME', 'TYPE_FIELD_DICT', 'varchar(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".spr_name"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_CODE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_CODE', 'CONTROLSOURCE', 'm.cAlias + ".code"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_CODE', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_CODE', 'TYPE_FIELD_DICT', 'varchar(20)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".code"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_CODE', 'CONTROL_NAME_EDIT', 'Atextbox2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME_1', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME_1', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME_1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME_1', 'CONTROLSOURCE', 'm.cAlias + ".name"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME_1', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME_1', 'TYPE_FIELD_DICT', 'varchar(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".name"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_NAME_1', 'CONTROL_NAME_EDIT', 'Atextbox3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE1', 'TITLE', 'Начало периода'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE1', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE1', 'CONTROLSOURCE', 'm.cAlias + ".date1"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE1', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE1', 'TYPE_FIELD_DICT', 'datetime'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".date1"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE1', 'CONTROL_NAME_EDIT', 'Aseldate4'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE2', 'TITLE', 'Конец периода'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE2', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE2', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE2', 'CONTROLSOURCE', 'm.cAlias + ".date2"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE2', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE2', 'TYPE_FIELD_DICT', 'Datetime'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".date2"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_DATE2', 'CONTROL_NAME_EDIT', 'Aseldate5'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1CODE', 'TITLE', 'Код параметра №1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1CODE', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1CODE', 'CONTROLSOURCE', 'm.cAlias + ".par1code"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1CODE', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1CODE', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".par1code"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1CODE', 'CONTROL_NAME_EDIT', 'Atextbox6'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1NAME', 'TITLE', 'Параметр №1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1NAME', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1NAME', 'CONTROLSOURCE', 'm.cAlias + ".par1name"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1NAME', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1NAME', 'TYPE_FIELD_DICT', 'varchar(20)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".par1name"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR1NAME', 'CONTROL_NAME_EDIT', 'Atextbox7'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2CODE', 'TITLE', 'Код параметра №2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2CODE', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2CODE', 'CONTROLSOURCE', 'm.cAlias + ".par2code"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2CODE', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2CODE', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".par2code"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2CODE', 'CONTROL_NAME_EDIT', 'Atextbox8'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2NAME', 'TITLE', 'Параметр №2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2NAME', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2NAME', 'CONTROLSOURCE', 'm.cAlias + ".par2name"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2NAME', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2NAME', 'TYPE_FIELD_DICT', 'varchar(20)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".par2name"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR2NAME', 'CONTROL_NAME_EDIT', 'Atextbox9'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3CODE', 'TITLE', 'Код параметра №3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3CODE', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3CODE', 'CONTROLSOURCE', 'm.cAlias + ".par3code"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3CODE', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3CODE', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".par3code"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3CODE', 'CONTROL_NAME_EDIT', 'Atextbox10'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3NAME', 'TITLE', 'Параметр №3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3NAME', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3NAME', 'CONTROLSOURCE', 'm.cAlias + ".par3name"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3NAME', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3NAME', 'TYPE_FIELD_DICT', 'varchar(20)'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".par3name"'
GO
EXEC X_SET_PROP 'SA_SZV_K_SPR_PAR3NAME', 'CONTROL_NAME_EDIT', 'Atextbox11'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'TITLE', 'Количество строк в пачке'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'OPERATE_METHOD', 'SQL.EXEC("SA_SZV_K_OPT1_CHECK") 
'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'CONTROL_NAME_EDIT', 'ATextBox1'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'INPUT_MASK', '99999'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'COMMENTARY', 'Ограничивает количество строк в пачке для формирования сведений СЗВ-К.'
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_CHECKED_1_1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_CHECKED_1_1', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_CHECKED_1_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_CODE_1_1', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_CODE_1_1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_CODE_1_1', 'CONTROLSOURCE', 'm.cAlias + ".code"'
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_CODE_1_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_CODE_1_1', 'CONTROL_TYPE', ''
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_CODE_1_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_CODE_1_1', 'TYPE_FIELD_DICT', 'varchar(20)'
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_NAME_2_1', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_NAME_2_1', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_NAME_2_1', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_NAME_2_1', 'CONTROLSOURCE', 'm.cAlias + ".name"'
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_NAME_2_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_NAME_2_1', 'CONTROL_TYPE', ''
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_NAME_2_1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV4_SPR_NAME_2_1', 'TYPE_FIELD_DICT', 'varchar(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_CHECKED', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_CHECKED', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_CHECKED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_ORDERS', 'TITLE', '№ п/п'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_ORDERS', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_ORDERS', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_ORDERS', 'CONTROLSOURCE', 'm.cAlias+ ".orders"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_ORDERS', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_ORDERS', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_ORDERS', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_ORDERS', 'CONTROLSOURCE_EDIT', 'm.cAlias+ ".orders"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_ORDERS', 'CONTROL_NAME_EDIT', 'Atextbox1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_DATE1', 'TITLE', 'Нач.пер.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_DATE1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_DATE1', 'CONTROLSOURCE', 'm.cAlias + ".date_n"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_DATE1', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_DATE1', 'TYPE_FIELD_DICT', 'datetime'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_DATE1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".date_n"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_DATE1', 'CONTROL_NAME_EDIT', 'Aseldate2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_DATE2', 'TITLE', 'Кон.пер.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_DATE2', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_DATE2', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_DATE2', 'CONTROLSOURCE', 'm.cAlias + ".date_k"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_DATE2', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_DATE2', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_DATE2', 'TYPE_FIELD_DICT', 'datetime'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_DATE2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".date_k"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_DATE2', 'CONTROL_NAME_EDIT', 'Aseldate3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_POST_NAME', 'TITLE', 'Должность'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_POST_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_POST_NAME', 'CONTROLSOURCE', 'm.cAlias+".POST"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_POST_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_POST_NAME', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_POST_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_POST_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(150)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_POST_NAME', 'SHORT_CODE_OBJ', 'POST'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_POST_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".POST"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_POST_NAME', 'CONTROL_NAME_EDIT', 'atextBox2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_POST_NAME', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 16px"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_POST_NAME', 'FIELD_DATA', 'post'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_TER_USL', 'TITLE', 'Терр.усл.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_TER_USL', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_TER_USL', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_TER_USL', 'CONTROLSOURCE', 'm.cAlias + ".f_ter_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_TER_USL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_TER_USL', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_TER_USL', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_TER_USL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".f_ter_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_USL', 'TITLE', 'Код терр.усл'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_USL', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_USL', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.ALIAS, ''CODE,NAME'', ''TER_USL,N_TER_USL'', '''', '''', "SPR_CODE = ''TERR_USL'' and DATE BETWEEN DATE1 AND COALESCE(DATE2,''30000101'')", .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_USL', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_USL', 'CONTROLSOURCE', 'm.cAlias + ".ter_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_USL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_USL', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_USL', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_USL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ter_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_USL', 'CONTROL_NAME_EDIT', 'apageframe1.Page1.Asel_spr4'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_TER_USL', 'TITLE', 'Терр.усл.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_TER_USL', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_TER_USL', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_TER_USL', 'CONTROLSOURCE', 'm.cAlias + ".n_ter_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_TER_USL', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_TER_USL', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_TER_USL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_ter_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_TER_USL', 'CONTROL_NAME_EDIT', 'apageframe1.Page1.aTextBox5'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_KOEF', 'TITLE', 'Районный коэффициент'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_KOEF', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_KOEF', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_KOEF', 'CONTROLSOURCE', 'm.cAlias + ".ter_koef"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_KOEF', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_KOEF', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_KOEF', 'TYPE_FIELD_DICT', 'NUMERIC(3,2)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_KOEF', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ter_koef"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_TER_KOEF', 'CONTROL_NAME_EDIT', 'apageframe1.Page1.Atextbox6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_OSOB_USL', 'TITLE', 'Особ.усл.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_OSOB_USL', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_OSOB_USL', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_OSOB_USL', 'CONTROLSOURCE', 'm.cAlias + ".f_osob_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_OSOB_USL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_OSOB_USL', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_OSOB_USL', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_OSOB_USL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".f_osob_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_USL', 'TITLE', 'Код особ.усл.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_USL', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_USL', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.ALIAS, ''CODE,NAME'', ''OSOB_USL,N_OSOB_USL'', '''', '''', "SPR_CODE = ''OSOB_USL_TRUDA'' and DATE BETWEEN DATE1 AND COALESCE(DATE2,''30000101'')", .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_USL', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_USL', 'CONTROLSOURCE', 'm.cAlias + ".osob_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_USL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_USL', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_USL', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_USL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".osob_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_USL', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.Asel_spr7'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_USL', 'TITLE', 'Наимен.особ.усл.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_USL', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_USL', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_USL', 'CONTROLSOURCE', 'm.cAlias + ".n_osob_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_USL', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_USL', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_USL', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_osob_usl"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_USL', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.aTextBox8'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K1', 'TITLE', 'Код позиции списка №1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K1', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.ALIAS, ''CODE,NAME'', ''osob_k1,n_osob_k1'', '''', '''', "SPR_CODE = ''SPISOK1'' and DATE BETWEEN DATE1 AND COALESCE(DATE2,''30000101'')", .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K1', 'CONTROLSOURCE', 'm.cAlias + ".osob_k1"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K1', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K1', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".osob_k1"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K1', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.Asel_spr9'
GO
EXEC X_SET_PROP 'SA_SSZV_K_STAZH_D_N_OSOB_K1', 'TITLE', 'Наим. поз.списка №1'
GO
EXEC X_SET_PROP 'SA_SSZV_K_STAZH_D_N_OSOB_K1', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SSZV_K_STAZH_D_N_OSOB_K1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SSZV_K_STAZH_D_N_OSOB_K1', 'CONTROLSOURCE', 'm.cAlias + ".n_osob_k1"'
GO
EXEC X_SET_PROP 'SA_SSZV_K_STAZH_D_N_OSOB_K1', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SSZV_K_STAZH_D_N_OSOB_K1', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SSZV_K_STAZH_D_N_OSOB_K1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_osob_k1"'
GO
EXEC X_SET_PROP 'SA_SSZV_K_STAZH_D_N_OSOB_K1', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.aTextBox10'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K2', 'TITLE', 'Код позиции списка №2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K2', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K2', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.ALIAS, ''CODE,NAME'', ''osob_k2,n_osob_k2'', '''', '''', "SPR_CODE = ''SPISOK2'' and DATE BETWEEN DATE1 AND COALESCE(DATE2,''30000101'')", .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K2', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K2', 'CONTROLSOURCE', 'm.cAlias + ".osob_k2"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K2', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K2', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".osob_k2"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K2', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.Asel_spr11'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_K2', 'TITLE', 'Наим. поз.списка №2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_K2', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_K2', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_K2', 'CONTROLSOURCE', 'm.cAlias + ".n_osob_k2"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_K2', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_K2', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_K2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_osob_k2"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_K2', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.aTextBox12'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K3', 'TITLE', 'Код позиции списка №3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K3', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K3', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K3', 'CONTROLSOURCE', 'm.cAlias + ".osob_k3"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K3', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K3', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K3', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".osob_k3"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_OSOB_K3', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.Asel_spr13'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_K3', 'TITLE', 'Наим. поз.списка №3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_K3', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_K3', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_K3', 'CONTROLSOURCE', 'm.cAlias + ".n_osob_k3"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_K3', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_K3', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_K3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_osob_k3"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_OSOB_K3', 'CONTROL_NAME_EDIT', 'apageframe1.Page2.aTextBox14'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_IS_OSNOV', 'TITLE', 'Исч.стаж.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_IS_OSNOV', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_IS_OSNOV', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_IS_OSNOV', 'CONTROLSOURCE', 'm.cAlias + ".f_is_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_IS_OSNOV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_IS_OSNOV', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_IS_OSNOV', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_IS_OSNOV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".f_is_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_OSNOV', 'TITLE', 'Основ.тр.ст.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_OSNOV', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_OSNOV', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.ALIAS, ''CODE,NAME'', ''is_osnov,n_is_osnov'', '''', '''', "SPR_CODE = ''ISCHISL_STAZH_OSNOV'' and DATE BETWEEN DATE1 AND COALESCE(DATE2,''30000101'')", .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_OSNOV', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_OSNOV', 'CONTROLSOURCE', 'm.cAlias + ".is_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_OSNOV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_OSNOV', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_OSNOV', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_OSNOV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".is_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_OSNOV', 'CONTROL_NAME_EDIT', 'apageframe1.Page3.Asel_spr15'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_IS_OSNOV', 'TITLE', 'Основ.тр.ст.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_IS_OSNOV', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_IS_OSNOV', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_IS_OSNOV', 'CONTROLSOURCE', 'm.cAlias + ".n_is_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_IS_OSNOV', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_IS_OSNOV', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_IS_OSNOV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_is_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_IS_OSNOV', 'CONTROL_NAME_EDIT', 'apageframe1.Page3.aTextBox16'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_M', 'TITLE', 'Доп. св. для исчисления трудового стажа, м.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_M', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_M', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_M', 'CONTROLSOURCE', 'm.cAlias + ".is_dop_m"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_M', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_M', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_M', 'TYPE_FIELD_DICT', 'tinyint'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_M', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".is_dop_m"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_M', 'CONTROL_NAME_EDIT', 'apageframe1.Page3.aTextBox17'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_D', 'TITLE', 'Доп. св. для исчисления трудового стажа, дн.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_D', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_D', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_D', 'CONTROLSOURCE', 'm.cAlias + ".is_dop_d"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_D', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_D', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_D', 'TYPE_FIELD_DICT', 'tinyint'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_D', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".is_dop_d"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP_D', 'CONTROL_NAME_EDIT', 'apageframe1.Page3.aTextBox18'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP', 'TITLE', 'Доп.свед.тр.ст.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.ALIAS, ''CODE,NAME'', ''is_dop,n_is_dop'', '''', '''', "SPR_CODE = ''ISCHISL_STAZH_DOP_SV'' and DATE BETWEEN DATE1 AND COALESCE(DATE2,''30000101'')", .T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP', 'CONTROLSOURCE', 'm.cAlias + ".is_dop"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".is_dop"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_IS_DOP', 'CONTROL_NAME_EDIT', 'apageframe1.Page3.Asel_spr19'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_IS_DOP', 'TITLE', 'Доп.свед.тр.ст.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_IS_DOP', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_IS_DOP', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_IS_DOP', 'CONTROLSOURCE', 'm.cAlias + ".n_is_dop"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_IS_DOP', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_IS_DOP', 'TYPE_FIELD_DICT', 'varchar(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_IS_DOP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_is_dop"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_IS_DOP', 'CONTROL_NAME_EDIT', 'apageframe1.Page3.aTextBox20'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_UD_OSNOV', 'TITLE', 'Усл.доср.пенс.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_UD_OSNOV', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_UD_OSNOV', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_UD_OSNOV', 'CONTROLSOURCE', 'm.cAlias + ".f_ud_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_UD_OSNOV', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_UD_OSNOV', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_F_UD_OSNOV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".f_ud_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_OSNOV', 'TITLE', 'Осн.доср.пенс.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_OSNOV', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_OSNOV', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.ALIAS, ''CODE,NAME'', ''ud_osnov,n_ud_osnov'', '''', '''', "SPR_CODE = ''DOSR_NAZN_PEN_OSNOV'' and DATE BETWEEN DATE1 AND COALESCE(DATE2,''30000101'')", .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_OSNOV', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_OSNOV', 'CONTROLSOURCE', 'm.cAlias + ".ud_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_OSNOV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_OSNOV', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_OSNOV', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_OSNOV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ud_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_OSNOV', 'CONTROL_NAME_EDIT', 'apageframe1.Page4.Asel_spr21'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_UD_OSNOV', 'TITLE', 'Осн.доср.пенс.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_UD_OSNOV', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_UD_OSNOV', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_UD_OSNOV', 'CONTROLSOURCE', 'm.cAlias + ".n_ud_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_UD_OSNOV', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_UD_OSNOV', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_UD_OSNOV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".n_ud_osnov"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_N_UD_OSNOV', 'CONTROL_NAME_EDIT', 'apageframe1.Page4.aTextBox22'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_M', 'TITLE', 'Доп.усл.для доср. пенс.,м.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_M', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_M', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_M', 'CONTROLSOURCE', 'm.cAlias + ".ud_dop_m"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_M', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_M', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_M', 'TYPE_FIELD_DICT', 'tinyint'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_M', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ud_dop_m"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_M', 'CONTROL_NAME_EDIT', 'apageframe1.Page4.aTextBox23'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_D', 'TITLE', 'Доп.усл.для доср. пенс.,дн.'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_D', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_D', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_D', 'CONTROLSOURCE', 'm.cAlias + ".ud_dop_d"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_D', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_D', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_D', 'TYPE_FIELD_DICT', 'tinyint'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_D', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ud_dop_d"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_D', 'CONTROL_NAME_EDIT', 'apageframe1.Page4.aTextBox24'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_K', 'TITLE', 'Доп.усл.для доср. пенс.,значение'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_K', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_K', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_K', 'CONTROLSOURCE', 'm.cAlias + ".ud_dop_k"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_K', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_K', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_K', 'TYPE_FIELD_DICT', 'NUMERIC(18,2)'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_K', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ud_dop_k"'
GO
EXEC X_SET_PROP 'SA_SZV_K_STAZH_D_UD_DOP_K', 'CONTROL_NAME_EDIT', 'apageframe1.Page4.aTextBox25'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_CHECKED', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_CHECKED', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_CHECKED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_ORDERS', 'TITLE', '№ п/п'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_ORDERS', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_ORDERS', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_ORDERS', 'CONTROLSOURCE', 'm.cAlias+ ".orders"'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_ORDERS', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_ORDERS', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_ORDERS', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_ORDERS', 'CONTROLSOURCE_EDIT', 'm.cAlias+ ".orders"'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_ORDERS', 'CONTROL_NAME_EDIT', 'Atextbox1'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_NAME', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_NAME', 'CONTROLSOURCE', 'm.cAlias + ".NAME_DEP"'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_NAME', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_NAME', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(100)'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_NAME', 'SHORT_CODE_OBJ', 'NAME_DEP'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_DEP"'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_NAME', 'CONTROL_NAME_EDIT', 'Atextbox2'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_NAME', 'FIELD_DATA', 'NAME_DEP'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_INN', 'TITLE', 'ИНН'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_INN', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_INN', 'CONTROLSOURCE', 'm.cAlias+''.INN'''
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_INN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_INN', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_INN', 'TYPE_FIELD_DICT', 'CHAR(12)'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_INN', 'SHORT_CODE_OBJ', 'INN'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_INN', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.INN'''
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_INN', 'CONTROL_NAME_EDIT', 'Atextbox3'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_INN', 'INPUT_MASK', '999999999999'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_INN', 'COMMENTARY', 'Идентификационный номер налогоплательщика'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_INN', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_INN', 'FIELD_DATA', 'INN'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_KPP', 'TITLE', 'КПП'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_KPP', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_KPP', 'CONTROLSOURCE', 'm.cALias+".KPP"'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_KPP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_KPP', 'ROWSOURCE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_KPP', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_KPP', 'TYPE_FIELD_DICT', 'char(9)'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_KPP', 'SHORT_CODE_OBJ', 'KPP'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_KPP', 'CONTROLSOURCE_EDIT', 'm.cALias+".KPP"'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_KPP', 'CONTROL_NAME_EDIT', 'Atextbox4'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_KPP', 'INPUT_MASK', '999999999'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_KPP', 'COMMENTARY', 'Код причины постановки на учёт'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_KPP', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_KPP', 'FIELD_DATA', 'KPP'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_OKPO', 'TITLE', 'ОКПО'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_OKPO', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_OKPO', 'CONTROLSOURCE', 'm.cAlias+".OKPO"'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_OKPO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_OKPO', 'ROWSOURCE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_OKPO', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_OKPO', 'TYPE_FIELD_DICT', 'char(20)'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_OKPO', 'SHORT_CODE_OBJ', 'OKPO'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_OKPO', 'CONTROLSOURCE_EDIT', 'm.cAlias+".OKPO"'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_OKPO', 'CONTROL_NAME_EDIT', 'Atextbox5'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_OKPO', 'INPUT_MASK', '99999999999999999999'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_OKPO', 'COMMENTARY', 'Код по общероссийскому классификатору предприятий и организаций'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_OKPO', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_OKPO', 'FIELD_DATA', 'OKPO'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK', 'TITLE', 'Вид деятельности'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK', 'CONTROLSOURCE', 'm.cAlias + ".vid_work_n"'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK', 'TYPE_FIELD_DICT', 'VARCHAR(160)'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".vid_work_n"'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK', 'CONTROL_NAME_EDIT', 'Atextbox6'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK_С', 'TITLE', 'код'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK_С', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''SA_SZV4_SPR'', oForm.ALIAS, ''CODE,NAME'',''vid_work,vid_work_n'','''','''', "SPR_CODE = ''VID_WORK'' ",.T., 1, oForm, oObj, "")
'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK_С', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK_С', 'CONTROLSOURCE', 'm.cAlias + ".vid_work"'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK_С', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK_С', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK_С', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK_С', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK_С', 'SHORT_CODE_OBJ', 'vid_work'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK_С', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".vid_work"'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK_С', 'CONTROL_NAME_EDIT', 'Asel_spr2'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK_С', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'SA_SZV_K_D_P_VID_WORK_С', 'FIELD_DATA', 'vid_work'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'SA_SZV_K_PACHKA', 'Смета-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SA_SZV_K_PACHKA', 'Свод-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SA_SZV_K_PACHKA', 'Зарплата-КС', 63,0
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Сведения о трудовом стаже застрахованного лица (СЗВ-К)"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'SZV_K')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SALARY_ESN')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV_K_PACHKA')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SALARY_ESN'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'EOD_DOC_SZV_K'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'EOD_DOC_SZV_K', 'Сведения о трудовом стаже застрахованного лица (СЗВ-К)', @ORD, NULL, 1, @LINK_SELF, 'RUN', @OBJECT, @LINK_VAR, 3
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='SA_SZV_K_OPT1'

WHILE EXISTS(SELECT * FROM dbo.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM @T WHERE FLAG=1))
BEGIN
	INSERT @T (LINK, CODE,FLAG)
	SELECT LINK, CODE, 0 
	FROM dbo.S_OBJECTS SO WHERE LINK_SELF IN (SELECT LINK FROM @T WHERE FLAG=1)
	UPDATE @T SET FLAG=2 WHERE FLAG=1
	UPDATE @T SET FLAG=1 WHERE FLAG=0
END

IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_SA_SZV_K_OPT1]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_SA_SZV_K_OPT1]

CREATE TABLE  dbo._UPD_OPT_SA_SZV_K_OPT1 (CODE VARCHAR(30), [SID] varbinary(85), VALUE VARCHAR(1000))

INSERT INTO _UPD_OPT_SA_SZV_K_OPT1 (CODE, [SID], VALUE)
SELECT T.CODE, so.[sid], so.VALUE
FROM 
	@T T INNER JOIN dbo.S_OPTIONS so ON so.[OBJECT] = T.LINK

GO

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV_K_OPT1')
	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_SZV_K_OPT1')
	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_SZV_K_OPT1')
	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_SZV_K_OPT1')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV_K_OPT1'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV_K_OPT1')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV_K_OPT1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV_K_OPT1', 'Количество строк в пачке', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV_K_OPT1', NAME = 'Количество строк в пачке', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV_K_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV_K_OPT1'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'TITLE', 'Количество строк в пачке'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'OPERATE_METHOD', 'SQL.EXEC("SA_SZV_K_OPT1_CHECK") 
'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'CONTROL_NAME_EDIT', 'ATextBox1'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'INPUT_MASK', '99999'
GO
EXEC X_SET_PROP 'SA_SZV_K_OPT1', 'COMMENTARY', 'Ограничивает количество строк в пачке для формирования сведений СЗВ-К.'
GO
/******--Восстановить, либо установить настройки на базе пользователя ******/
DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'SA_SZV_K_OPT1' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_SA_SZV_K_OPT1] WHERE CODE = 'SA_SZV_K_OPT1')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'SA_SZV_K_OPT1'), SID, VALUE FROM [dbo].[_UPD_OPT_SA_SZV_K_OPT1] WHERE CODE = 'SA_SZV_K_OPT1'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '200' FROM  dbo.S_OBJECTS WHERE CODE = 'SA_SZV_K_OPT1'

GO


IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_SA_SZV_K_OPT1]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_SA_SZV_K_OPT1]

GO


/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
-- Отчет "ФОТ по видам начислений"
-- Сгенерировано скриптом scriptObjectVar 'SQL_REP_SA_FOT_NLIST'

/*** Сам отчет ***/

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_FOT_NLIST'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'SQL_REP_SA_FOT_NLIST'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'ФОТ по видам начислений',401, 
	(Select link from object_var where code = 'SQL_REPORT_CATALOG_SALARY'),
	'SQL_REP_SA_FOT_NLIST',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'SQL_REP_SA_FOT_NLIST') 
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'EXEC 	DBO.SA_FOT_NLIST 
	@dDateB1 /* Начало периода */,
	@dDateE1 /* Конец периода */,
	@nCombo2 /* Внешние совместители */,
	@cVal1, @nOtborLink1 /* Отбор сотрудников */,
	@cVal2, @nOtborLink2 /* Отбор видов начислений */'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#SQL_REP_SA_FOT_NLIST'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"FOT_NLIST.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #SQL_REP_SA_FOT_NLIST
	@dDateB1 datetime	/* Начало периода */,
	@dDateE1 datetime	/* Конец периода */,
	@nCombo2 int	/* Внешние совместители */,
	@nFilterLink int	/* Фильтр */
AS
BEGIN
	DECLARE @cVal1 char(1), @nOtborLink1 int	/* Отбор сотрудников */
	SELECT @nOtborLink1 = (SELECT LINK FROM OBJECT_VAR WHERE LINK_SELF=@nFilterLink AND OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE=''OTBOR_QUERY_SQL_EMPL''))
	SELECT @cVal1 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink1 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE=''QUERY_OTBOR_CHECK''))
	DECLARE @cVal2 char(1), @nOtborLink2 int	/* Отбор видов начислений */
	SELECT @nOtborLink2 = (SELECT LINK FROM OBJECT_VAR WHERE LINK_SELF=@nFilterLink AND OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE=''OTBOR_QUERY_SQL_PAY_SALARY''))
	SELECT @cVal2 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink2 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE=''QUERY_OTBOR_CHECK''))

EXEC 	DBO.SA_FOT_NLIST 
	@dDateB1 /* Начало периода */,
	@dDateE1 /* Конец периода */,
	@nCombo2 /* Внешние совместители */,
	@cVal1, @nOtborLink1 /* Отбор сотрудников */,
	@cVal2, @nOtborLink2 /* Отбор видов начислений */

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') 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_FOT_NLIST'),
	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_FOT_NLIST') and  PROPERTY = (Select LINK from s_property where code = 'SQUERY_NO_SHOW')
	INSERT INTO object_var_values (LINK_UP, PROPERTY, VALUE)
	Select  LINK_UP= (Select link from object_var OV where code = 'SQL_REP_SA_FOT_NLIST'),
	PROPERTY= (Select LINK from s_property where code = 'SQUERY_NO_SHOW'),
	VALUE= '0'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_REP_SA_FOT_NLIST') 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_FOT_NLIST'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SQL_REP_SA_FOT_NLIST_F1' 
		INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
		Select (Select link from s_objects where code = 'QUERY_FILTER'),
		'Стандартный фильтр для запроса',0, 
		(Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST'),
		'SQL_REP_SA_FOT_NLIST_F1',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SA_FOT_NLIST_O1' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'OTBOR_QUERY_SQL_EMPL'),
					'Отбор сотрудников',1, 
					(Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_F1'),
					'SQL_REP_SA_FOT_NLIST_O1',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O1'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_CHECK') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O1'),
							(Select link from s_property where code = 'QUERY_OTBOR_CHECK'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O1'),
							(Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE'),
							'DICT_EMPLOYERS01'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_FIELD') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O1'),
							(Select link from s_property where code = 'QUERY_OTBOR_FIELD'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_PARENT_CODE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O1'),
							(Select link from s_property where code = 'QUERY_OTBOR_PARENT_CODE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O1'),
							(Select link from s_property where code = 'QUERY_OTBOR_VALUE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE2') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O1'),
							(Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE2'),
							'DICTIONARY_SUBDIVISION01'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SA_FOT_NLIST_O2' 
					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_PAY_SALARY'),
					'Отбор видов начислений',2, 
					(Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_F1'),
					'SQL_REP_SA_FOT_NLIST_O2',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O2'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_CHECK') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O2'),
							(Select link from s_property where code = 'QUERY_OTBOR_CHECK'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O2'),
							(Select link from s_property where code = 'QUERY_OTBOR_DICTIONARY_CODE'),
							'DICTIONARY_PAY_SALARY'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_FIELD') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O2'),
							(Select link from s_property where code = 'QUERY_OTBOR_FIELD'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_PARENT_CODE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O2'),
							(Select link from s_property where code = 'QUERY_OTBOR_PARENT_CODE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_OTBOR_VALUE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_O2'),
							(Select link from s_property where code = 'QUERY_OTBOR_VALUE'),
							''
						
GO
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SQL_REP_SA_FOT_NLIST_G' 
		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_REP_SA_FOT_NLIST'),
		'SQL_REP_SA_FOT_NLIST_G',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SA_FOT_NLIST_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_DATEBOX_PB'),
					'Начало периода',4, 
					(Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_G'),
					'SQL_REP_SA_FOT_NLIST_N1',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_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_REP_SA_FOT_NLIST_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Начало периода'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1'),
							(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_FOT_NLIST_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							'На эту дату выводятся все показатели свода'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1'),
							(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_FOT_NLIST_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Текущая дата,Расчетная дата,Начало расч. периода,Конец расч. периода,Начало года,Конец года,Начало расч. месяца,Конец расч. месяца'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1'),
							(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_FOT_NLIST_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1'),
							(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_FOT_NLIST_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Начало расч. месяца'

						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N1'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SA_FOT_NLIST_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_DATEBOX_PE'),
					'Конец периода',5, 
					(Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_G'),
					'SQL_REP_SA_FOT_NLIST_N2',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Конец периода'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2'),
							(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_FOT_NLIST_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							'До этого периода определяются даты и новый процент по стажу'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2'),
							(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_FOT_NLIST_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Текущая дата,Расчетная дата,Начало расч. периода,Конец расч. периода,Начало года,Конец года,Начало расч. месяца,Конец расч. месяца'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2'),
							(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_FOT_NLIST_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2'),
							(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_FOT_NLIST_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Конец расч. месяца'

						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_REP_SA_FOT_NLIST_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_CHECKBOX'),
					'Внешние совместители',6, 
					(Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_G'),
					'SQL_REP_SA_FOT_NLIST_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_REP_SA_FOT_NLIST_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_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_REP_SA_FOT_NLIST_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_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_REP_SA_FOT_NLIST_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_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_REP_SA_FOT_NLIST_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_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_REP_SA_FOT_NLIST_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'COMBOBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_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_REP_SA_FOT_NLIST_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_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_REP_SA_FOT_NLIST_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_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 = 'SQL_REP_SA_FOT_NLIST_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_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_REP_SA_FOT_NLIST_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCombo2'
						
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_FOT_NLIST_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_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_REP_SA_FOT_NLIST_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_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_REP_SA_FOT_NLIST_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_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_REP_SA_FOT_NLIST_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_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_REP_SA_FOT_NLIST_N3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_REP_SA_FOT_NLIST_N3'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Группа настроек    ***/
GO





/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА в зарплату "ФОТ по видам начислений"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'SQL_REP_SA_FOT_NLIST')

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_REP_SA_FOT_NLIST'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'NV_REP_SA_FOT_NLIST', 'ФОТ по видам начислений', @ORD, NULL, 1, @LINK_SELF, 'REPORT', @OBJECT, @LINK_VAR, 3
GO



/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА в кадры "ФОТ по видам начислений"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'SQL_REP_SA_FOT_NLIST')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADRY_FREE_PERSONS')

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_FREE_PERSONS'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'NV_REP_SA_FOT_NLIST_1'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'NV_REP_SA_FOT_NLIST_1', 'ФОТ по видам начислений', @ORD, NULL, 1, @LINK_SELF, 'REPORT_QUERY', @OBJECT, @LINK_VAR, 3
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'KJ_REP_REP_SA_FOT_NLIST_1', 'Кадры-КС', 4,59
GO
EXEC DBO.W_SPERM_WRITE 'KJ_REP_REP_SA_FOT_NLIST_1', 'Зарплата-КС', 4,0
GO
EXEC DBO.W_SPERM_WRITE 'KJ_REP_REP_SA_FOT_NLIST_1', 'Свод-КС', 4,59
GO
EXEC DBO.W_SPERM_WRITE 'KJ_REP_REP_SA_FOT_NLIST_1', 'Смета-КС', 4,59
GO
EXEC DBO.W_SPERM_WRITE 'KJ_REP_REP_SA_FOT_NLIST_1', 'Кадры-КС (чтение)', 4,59
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'MENU_BAR_REP_SA_FOT_NLIST', 'Зарплата-КС', 63,0
GO


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (июл  3 2014 11:51:50:803AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0503074G (Отчет о расходах и числ работников гос. органов субъектов РФ (годовая))
-- Дата ввода : 20101231
-- Дата окончания действия :
-- Версия : 2014-07-03 11:51:50.803
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = '0503074G' AND [START_DATE] = '20101231'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-07-03 11:51:50.803',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '0503074G',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '0503074G'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20101231')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SMETA'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Отчет о расходах и числ работников гос. органов субъектов РФ (годовая)',@vcNEW_FORM_CODE,@dNEW_START_DATE,1,1,1,1,18186,'RA_EXPORT_FORM_0503074#RA_IMPORT_FORM_0503074',0,0,'19000101',NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'svodprint_14_ask()','Sv_0503074G_20101231.bas','','KirRepMakerMultiSheet.xls','Sv_0503074G_20101231.xlt','',NULL,'RA_EXPORT_FORM_0503074#RA_IMPORT_FORM_0503074',0,NULL,NULL,'FORM14_EDIT#26#1','014       ','',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Таблица', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Утверждено',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Фактически',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Таблица', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Численность', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Утверждено',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Фактически',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Среднесписочная численность',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Численность', @iLINK_FORM,2, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Справка1', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Фактически',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Справка1', @iLINK_FORM,3, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Справка2', @iLINK_FORM,4
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,100,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'На отчетную дату',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В среднем',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Справка2', @iLINK_FORM,4, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (3,1,1,1)
INSERT #R VALUES (4,1,2,1)
INSERT #R VALUES (5,1,3,1)
INSERT #R VALUES (28,1,32,1)
INSERT #R VALUES (2,1,24,1)
INSERT #R VALUES (6,1,25,1)
INSERT #R VALUES (7,1,4,1)
INSERT #R VALUES (8,1,5,1)
INSERT #R VALUES (9,1,6,1)
INSERT #R VALUES (10,1,7,1)
INSERT #R VALUES (11,1,8,1)
INSERT #R VALUES (12,1,26,1)
INSERT #R VALUES (13,1,9,1)
INSERT #R VALUES (14,1,10,1)
INSERT #R VALUES (15,1,11,1)
INSERT #R VALUES (16,1,27,1)
INSERT #R VALUES (17,1,12,1)
INSERT #R VALUES (18,1,13,1)
INSERT #R VALUES (19,1,14,1)
INSERT #R VALUES (20,1,15,1)
INSERT #R VALUES (21,1,16,1)
INSERT #R VALUES (22,1,30,1)
INSERT #R VALUES (23,1,31,1)
INSERT #R VALUES (24,1,17,1)
INSERT #R VALUES (25,1,28,1)
INSERT #R VALUES (26,1,18,1)
INSERT #R VALUES (27,1,19,1)
INSERT #R VALUES (29,1,29,1)
INSERT #R VALUES (30,1,20,1)
INSERT #R VALUES (31,1,21,1)
INSERT #R VALUES (32,1,22,1)
INSERT #R VALUES (33,1,33,1)
INSERT #R VALUES (1,2,1,1)
INSERT #R VALUES (2,2,2,1)
INSERT #R VALUES (3,2,3,1)
INSERT #R VALUES (4,2,23,1)
INSERT #R VALUES (5,2,8,1)
INSERT #R VALUES (6,2,5,1)
INSERT #R VALUES (7,2,6,1)
INSERT #R VALUES (8,2,7,1)
INSERT #R VALUES (9,2,12,1)
INSERT #R VALUES (10,2,9,1)
INSERT #R VALUES (11,2,10,1)
INSERT #R VALUES (12,2,11,1)
INSERT #R VALUES (13,2,17,1)
INSERT #R VALUES (14,2,13,1)
INSERT #R VALUES (15,2,14,1)
INSERT #R VALUES (16,2,15,1)
INSERT #R VALUES (17,2,16,1)
INSERT #R VALUES (18,2,22,1)
INSERT #R VALUES (19,2,18,1)
INSERT #R VALUES (20,2,19,1)
INSERT #R VALUES (21,2,20,1)
INSERT #R VALUES (22,2,21,1)
INSERT #R VALUES (23,2,23,1)
INSERT #R VALUES (24,2,24,1)
INSERT #R VALUES (25,2,25,1)
INSERT #R VALUES (26,2,26,1)
INSERT #R VALUES (1,3,1,1)
INSERT #R VALUES (2,3,20,1)
INSERT #R VALUES (3,3,5,1)
INSERT #R VALUES (4,3,2,1)
INSERT #R VALUES (5,3,3,1)
INSERT #R VALUES (6,3,4,1)
INSERT #R VALUES (7,3,9,1)
INSERT #R VALUES (8,3,6,1)
INSERT #R VALUES (9,3,7,1)
INSERT #R VALUES (10,3,8,1)
INSERT #R VALUES (11,3,14,1)
INSERT #R VALUES (12,3,10,1)
INSERT #R VALUES (13,3,11,1)
INSERT #R VALUES (14,3,12,1)
INSERT #R VALUES (15,3,13,1)
INSERT #R VALUES (16,3,19,1)
INSERT #R VALUES (17,3,15,1)
INSERT #R VALUES (18,3,16,1)
INSERT #R VALUES (19,3,17,1)
INSERT #R VALUES (20,3,18,1)
INSERT #R VALUES (1,4,1,1)
INSERT #R VALUES (2,4,2,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 80
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,2,1,'Заработная плата лиц, замещающих государственные должности, всего  (сумма строк 011+012+013)                                                                                                                                                              ')
INSERT #F VALUES (1,3,1,'в т.ч.:денежное вознаграждение (денежное содержание, заработная плата судей)                                                                                                                                                                              ')
INSERT #F VALUES (1,4,1,'ежемесячное (ежеквартальное) денежное поощрение                                                                                                                                                                                                           ')
INSERT #F VALUES (1,5,1,'другие выплаты , предусмотренные действующим законодательством                                                                                                                                                                                            ')
INSERT #F VALUES (1,6,1,'Заработная плата  лиц, замещающих должности государственной гражданской службы, всего (сумма строк 021+023+025)                                                                                                                                           ')
INSERT #F VALUES (1,7,1,'в т.ч.:оклад денежного содержания                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,8,1,'из него  оклад по занимаемой должности                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,9,1,'дополнительные выплаты                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,10,1,'из них:  ежемесячное денежное поощрение                                                                                                                                                                                                                   ')
INSERT #F VALUES (1,11,1,'другие выплаты , предусмотренные действующим законодательством                                                                                                                                                                                            ')
INSERT #F VALUES (1,12,1,'Заработная плата лиц, замещающих отдельные должности государственной гражданской службы, 1) всего                               (сумма строк 031+032+033)                                                                                                 ')
INSERT #F VALUES (1,13,1,'в том числе: единое денежное вознаграждение                                                                                                                                                                                                               ')
INSERT #F VALUES (1,14,1,'ежемесячное денежное поощрение и премии                                                                                                                                                                                                                   ')
INSERT #F VALUES (1,15,1,'другие выплаты , предусмотренные действующим законодательством                                                                                                                                                                                            ')
INSERT #F VALUES (1,16,1,'Заработная плата лиц, замещающих  должности  иного вида федеральной государственной службы, 2) всего                     (сумма строк 041+042)                                                                                                            ')
INSERT #F VALUES (1,17,1,'в том числе: оклад денежного содержания                                                                                                                                                                                                                   ')
INSERT #F VALUES (1,18,1,'дополнительные выплаты                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,19,1,'из них ежемесячное денежное поощрение                                                                                                                                                                                                                     ')
INSERT #F VALUES (1,20,1,'Заработная плата лиц, замещающих должности, не являющиеся должностями государственной гражданской службы                                                                                                                                                  ')
INSERT #F VALUES (1,21,1,'Заработная плата работников государственного органа, переведенных на новые системы оплаты труда 3)                                                                                                                                                        ')
INSERT #F VALUES (1,22,1,'Итого расходов на заработную плату работников государственного органа (сумма строк 010+020+030+040+050+060)                                                                                                                                               ')
INSERT #F VALUES (1,23,1,'Прочие выплаты  работникам   государственного органа                                                                                                                                                                                                      ')
INSERT #F VALUES (1,24,1,'из них: компенсации работникам за использование личных легковых автомобилей для служебных целей                                                                                                                                                           ')
INSERT #F VALUES (1,25,1,'суточные при служебных командировках - всего  (сумма строк 083+084)                                                                                                                                                                                       ')
INSERT #F VALUES (1,26,1,'в том числе: на территории Российской Федерации                                                                                                                                                                                                           ')
INSERT #F VALUES (1,27,1,'на территории иностранных государств                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,28,1,'Другие расходы  на содержание   государственного органа                                                                                                                                                                                                   ')
INSERT #F VALUES (1,29,1,'в том числе: на служебные командировки (оплата проезда и проживания) - всего (сумма строк 092+093)                                                                                                                                                        ')
INSERT #F VALUES (1,30,1,'из них: на территории Российской Федерации                                                                                                                                                                                                                ')
INSERT #F VALUES (1,31,1,'на территории иностранных государств                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,32,1,'на содержание служебных легковых автомобилей                                                                                                                                                                                                              ')
INSERT #F VALUES (1,33,1,'Итого расходов  на содержание  государственного органа (сумма строк 070+080+090)                                                                                                                                                                          ')
INSERT #F VALUES (1,2,2,'010                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,3,2,'011                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,4,2,'012')
INSERT #F VALUES (1,5,2,'013                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,6,2,'020                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,7,2,'021')
INSERT #F VALUES (1,8,2,'022                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,9,2,'023')
INSERT #F VALUES (1,10,2,'024                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,11,2,'025                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,12,2,'030                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,13,2,'031                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,14,2,'032                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,15,2,'033                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,16,2,'040                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,17,2,'041                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,18,2,'042')
INSERT #F VALUES (1,19,2,'043                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,20,2,'050                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,21,2,'060                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,22,2,'070                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,23,2,'080                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,24,2,'081                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,25,2,'082                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,26,2,'083                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,27,2,'084                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,28,2,'090                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,29,2,'091                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,30,2,'092                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,31,2,'093                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,32,2,'094                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,33,2,'100                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,3,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,4,3,'ЗАПРЕТ()                                                                                                                                                                                                                                                  ')
INSERT #F VALUES (1,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,7,3,'ЗАПРЕТ()                                                                                                                                                                                                                                                  ')
INSERT #F VALUES (1,8,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,9,3,'ЗАПРЕТ()                                                                                                                                                                                                                                                  ')
INSERT #F VALUES (1,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,11,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,12,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,13,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,14,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,15,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,17,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,18,3,'ЗАПРЕТ()                                                                                                                                                                                                                                                  ')
INSERT #F VALUES (1,19,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,20,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,21,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,24,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,25,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,26,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,27,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,29,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,30,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,31,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,32,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,33,3,'ИТОГ_Ф14("070+080+090")')
INSERT #F VALUES (1,2,4,'ИТОГ_Ф14("011+012+013")')
INSERT #F VALUES (1,3,4,'14_УСТАНОВКА()+14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,4,4,'14_ФАКТ_РАСХОД(К.СТР.)                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,5,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,6,4,'ИТОГ_Ф14("021+023+025")')
INSERT #F VALUES (1,7,4,'14_ФАКТ_РАСХОД(К.СТР.)                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,8,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,9,4,'14_ФАКТ_РАСХОД(К.СТР.)                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,10,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,11,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,12,4,'ИТОГ_Ф14("031+032+033")')
INSERT #F VALUES (1,13,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,14,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,15,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,16,4,'ИТОГ_Ф14("041+042")')
INSERT #F VALUES (1,17,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,18,4,'14_ФАКТ_РАСХОД(К.СТР.)                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,19,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,20,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,21,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,22,4,'ИТОГ_Ф14("010+020+030+040+050+060")')
INSERT #F VALUES (1,23,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,24,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,25,4,'ИТОГ_Ф14("083+084")')
INSERT #F VALUES (1,26,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,27,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,28,4,'14_ФАКТ_РАСХОД("092") + 14_ФАКТ_РАСХОД("094")')
INSERT #F VALUES (1,29,4,'ИТОГ_Ф14("092+093")')
INSERT #F VALUES (1,30,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,31,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,32,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,33,4,'ИТОГ_Ф14("070+080+090")')
INSERT #F VALUES (2,1,1,'Государственные  должности                                                                                                                                                                                                                                ')
INSERT #F VALUES (2,2,1,'Должности государственной гражданской службы                                                                                                                                                                                                              ')
INSERT #F VALUES (2,3,1,'Отдельные должности государственной гражданской   службы 2)                                                                                                                                                                                               ')
INSERT #F VALUES (2,4,1,'Итого  должностей государственной гражданской службы (сумма строк 210+220)                                                                                                                                                                                ')
INSERT #F VALUES (2,5,1,'в том числе по категориям: руководители  (сумма строк 241+242+243)                                                                                                                                                                                        ')
INSERT #F VALUES (2,6,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (2,7,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,8,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,9,1,'помощники (советники) (сумма строк 251+252+253)                                                                                                                                                                                                           ')
INSERT #F VALUES (2,10,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (2,11,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,12,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,13,1,'специалисты  (сумма строк 261+262+263+264)                                                                                                                                                                                                                ')
INSERT #F VALUES (2,14,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (2,15,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,16,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,17,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,18,1,'Обеспечивающие специалисты (сумма строк 271+272+273+274)                                                                                                                                                                                                  ')
INSERT #F VALUES (2,19,1,'из них по группам: главные                                                                                                                                                                                                                                ')
INSERT #F VALUES (2,20,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,21,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,22,1,'младшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,23,1,'Должности иного вида федеральной государственной службы 3)                                                                                                                                                                                                ')
INSERT #F VALUES (2,24,1,'Должности, не являющиеся должностями государственной гражданской службы                                                                                                                                                                                   ')
INSERT #F VALUES (2,25,1,'Должности работников государственного органа, переведенных на новые системы оплаты труда 4)                                                                                                                                                               ')
INSERT #F VALUES (2,26,1,'Всего должностей работнриков (сумма строк 200+230+280+290+300)                                                                                                                                                                                            ')
INSERT #F VALUES (2,1,2,'200                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,2,2,'210                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,3,2,'220                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,4,2,'230                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,5,2,'240                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,6,2,'241                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,7,2,'242')
INSERT #F VALUES (2,8,2,'243')
INSERT #F VALUES (2,9,2,'250                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,10,2,'251                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,11,2,'252')
INSERT #F VALUES (2,12,2,'253')
INSERT #F VALUES (2,13,2,'260                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,14,2,'261                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,15,2,'262')
INSERT #F VALUES (2,16,2,'263')
INSERT #F VALUES (2,17,2,'264')
INSERT #F VALUES (2,18,2,'270')
INSERT #F VALUES (2,19,2,'271                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,20,2,'272')
INSERT #F VALUES (2,21,2,'273')
INSERT #F VALUES (2,22,2,'274')
INSERT #F VALUES (2,23,2,'280                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,24,2,'290                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,25,2,'300                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,26,2,'310                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,1,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,2,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,3,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,4,3,'ИТОГ_Ф14("210+220")')
INSERT #F VALUES (2,5,3,'ИТОГ_Ф14("241+242+243")')
INSERT #F VALUES (2,6,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,7,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,8,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,9,3,'ИТОГ_Ф14("251+252+253")')
INSERT #F VALUES (2,10,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,11,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,12,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,13,3,'ИТОГ_Ф14("261+262+263+264")')
INSERT #F VALUES (2,14,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,15,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,16,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,17,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,18,3,'ИТОГ_Ф14("271+272+273+274")                                                                                                                                                                                                                               ')
INSERT #F VALUES (2,19,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,20,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,21,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,22,3,'14_ШТАТ(К.СТР.)                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,23,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,24,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,25,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,26,3,'ИТОГ_Ф14("200+230+280+290+300")')
INSERT #F VALUES (2,1,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,2,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,3,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,4,4,'ИТОГ_Ф14("210+220")')
INSERT #F VALUES (2,5,4,'ИТОГ_Ф14("241+242+243")')
INSERT #F VALUES (2,6,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,7,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,8,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,9,4,'ИТОГ_Ф14("251+252+253")')
INSERT #F VALUES (2,10,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,11,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,12,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,13,4,'ИТОГ_Ф14("261+262+263+264")')
INSERT #F VALUES (2,14,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,15,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,16,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,17,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,18,4,'ИТОГ_Ф14("271+272+273+274")                                                                                                                                                                                                                               ')
INSERT #F VALUES (2,19,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,20,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,21,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,22,4,'14_ФАКТ_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,23,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,24,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,25,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,26,4,'ИТОГ_Ф14("200+230+280+290+300")')
INSERT #F VALUES (2,1,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,2,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,3,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,4,5,'ИТОГ_Ф14("210+220")')
INSERT #F VALUES (2,5,5,'ИТОГ_Ф14("241+242+243")')
INSERT #F VALUES (2,6,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,7,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,8,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,9,5,'ИТОГ_Ф14("251+252+253")')
INSERT #F VALUES (2,10,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,11,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,12,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,13,5,'ИТОГ_Ф14("261+262+263+264")')
INSERT #F VALUES (2,14,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,15,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,16,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,17,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,18,5,'ИТОГ_Ф14("271+272+273+274")                                                                                                                                                                                                                               ')
INSERT #F VALUES (2,19,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,20,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,21,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,22,5,'14_СРЕД_ЧИСЛО(К.СТР.)                                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,23,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,24,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,25,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,26,5,'ИТОГ_Ф14("200+230+280+290+300")')
INSERT #F VALUES (3,1,1,'Количество государственных органов                                                                                                                                                                                                                        ')
INSERT #F VALUES (3,2,1,'Расходы на выплату денежного содержания, учтенного в строках 020 и 030 всего  (сумма строк 410+420+430+440)                                                                                                                                               ')
INSERT #F VALUES (3,3,1,'в том числе по категориям: руководители  (сумма строк 411+412+413)                                                                                                                                                                                        ')
INSERT #F VALUES (3,4,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,5,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,6,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,7,1,'помощники (советники) сумма строк (421+422+423)                                                                                                                                                                                                           ')
INSERT #F VALUES (3,8,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,9,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,10,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,11,1,'специалисты  (сумма строк 431+432+433+434)                                                                                                                                                                                                                ')
INSERT #F VALUES (3,12,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,13,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,14,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,15,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,16,1,'обеспечивающие специалисты (сумма строк 441+442+443+444)                                                                                                                                                                                                  ')
INSERT #F VALUES (3,17,1,'из них по группам: главные                                                                                                                                                                                                                                ')
INSERT #F VALUES (3,18,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,19,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,20,1,'младшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,1,2,'320                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,2,2,'400                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,3,2,'410                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,4,2,'411                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,5,2,'412                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,6,2,'413                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,7,2,'420                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,8,2,'421                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,9,2,'422                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,10,2,'423                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,11,2,'430                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,12,2,'431                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,13,2,'432                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,14,2,'433                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,15,2,'434                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,16,2,'440                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,17,2,'441                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,18,2,'442                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,19,2,'443                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,20,2,'444                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,2,3,'ИТОГ_Ф14("410+420+430+440KBK")')
INSERT #F VALUES (3,3,3,'ИТОГ_Ф14("411+412+413")')
INSERT #F VALUES (3,4,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,5,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,6,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,7,3,'ИТОГ_Ф14("421+422+423")')
INSERT #F VALUES (3,8,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,9,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,10,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,11,3,'ИТОГ_Ф14("431+432+433+434")')
INSERT #F VALUES (3,12,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,13,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,14,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,15,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,16,3,'ИТОГ_Ф14("441+442+443+444")')
INSERT #F VALUES (3,17,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,18,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,19,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (3,20,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (4,1,1,'Служебные легковые автомобили, состоящие на балансе государственного органа                                                                                                                                                                               ')
INSERT #F VALUES (4,2,1,'Служебные легковые автомобили, арендованные у других организаций по договорам найма                                                                                                                                                                       ')
INSERT #F VALUES (4,1,2,'450                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,2,2,'460                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,1,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (4,2,3,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (4,1,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (4,2,4,'14_ФАКТ_РАСХОД(К.СТР.)')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 322
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,1,0,0,0,'020-(021-023-025) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(2,NULL,0,NULL,2,1,0,0,0,'030-(031+032+033) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(3,NULL,0,NULL,3,1,0,0,0,'040-(041+042) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(4,NULL,0,NULL,4,7,0,0,0,'070-(010+020+030+040+050+060) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(5,NULL,0,NULL,5,1,0,0,0,'082-(083+084) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(6,NULL,0,NULL,6,3,8,0,0,'091-(092+093) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(7,NULL,0,NULL,7,1,0,0,0,'100-(070+080+090) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(8,NULL,0,NULL,8,7,0,0,0,'230-(210+220) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(9,NULL,0,NULL,9,1,0,0,0,'240-(241+242+243) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(10,NULL,0,NULL,10,1,0,0,0,'250-(251+252+253) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(11,NULL,0,NULL,11,1,0,0,0,'260-(261+262+263+264) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(12,NULL,0,NULL,12,5,0,0,0,'270-(271+272+273+274) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(13,NULL,0,NULL,13,7,0,0,0,'310-(200+230+280+290+300) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(14,NULL,0,NULL,14,1,0,0,0,'400-(410+420+430+440) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(15,NULL,0,NULL,15,5,0,0,0,'410-(411+412+413) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(16,NULL,0,NULL,16,1,0,0,0,'420-(421+422+423) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(17,NULL,0,NULL,17,1,0,0,0,'430-(431+432+433+434) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(18,NULL,0,NULL,18,5,0,0,0,'440-(441+442+443+444) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(19,NULL,0,NULL,19,7,0,0,0,'070Гр3>=070Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(20,NULL,0,NULL,20,7,0,0,0,'080Гр3>=080Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(21,NULL,0,NULL,21,7,0,0,0,'100Гр3>=100Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(22,NULL,0,NULL,22,1,0,0,0,'080>=081+082 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(23,NULL,0,NULL,23,7,0,0,0,'200Гр3>=200Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(24,NULL,0,NULL,24,7,0,0,0,'210Гр3>=210Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(25,NULL,0,NULL,25,7,0,0,0,'220Гр3>=220Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(26,NULL,0,NULL,26,7,0,0,0,'230Гр3>=230Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(27,NULL,0,NULL,27,1,0,0,0,'240Гр3>=240Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(28,NULL,0,NULL,28,1,0,0,0,'241Гр3>=241Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(29,NULL,0,NULL,29,1,0,0,0,'242Гр3>=242Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(30,NULL,0,NULL,30,1,0,0,0,'243Гр3>=243Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(31,NULL,0,NULL,31,1,0,0,0,'250Гр3>=250Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(32,NULL,0,NULL,32,1,0,0,0,'251Гр3>=251Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(33,NULL,0,NULL,33,1,0,0,0,'252Гр3>=252Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(34,NULL,0,NULL,34,1,0,0,0,'253Гр3>=253Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(35,NULL,0,NULL,35,1,0,0,0,'260Гр3>=260Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(36,NULL,0,NULL,36,1,0,0,0,'261Гр3>=261Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(37,NULL,0,NULL,37,1,0,0,0,'262Гр3>=262Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(38,NULL,0,NULL,38,1,0,0,0,'263Гр3>=263Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(39,NULL,0,NULL,39,1,0,0,0,'264Гр3>=264Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(40,NULL,0,NULL,40,1,0,0,0,'270Гр3>=270Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(41,NULL,0,NULL,41,5,0,0,0,'271Гр3>=271Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(42,NULL,0,NULL,42,1,0,0,0,'272Гр3>=272Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(43,NULL,0,NULL,43,1,0,0,0,'273Гр3>=273Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(44,NULL,0,NULL,44,1,0,0,0,'230-(240+250+260+270) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(45,NULL,0,NULL,45,1,0,0,0,'010-(011+012+013) =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(46,NULL,0,NULL,46,1,0,0,0,'021Гр4>=021Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(47,NULL,0,NULL,47,1,0,0,0,'023Гр4>=024Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(48,NULL,0,NULL,48,1,0,0,0,'042Гр4>=043Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(49,NULL,0,NULL,49,1,0,0,0,'080Гр4>=081Гр4+082Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(50,NULL,0,NULL,50,1,0,0,0,'090Гр4>=091Гр4+094Гр4+095Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(51,NULL,0,NULL,51,1,0,0,0,'090Гр3>=090Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(52,NULL,0,NULL,52,1,0,0,0,'274Гр3>=274Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(53,NULL,0,NULL,53,7,0,0,0,'280Гр3>=280Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(54,NULL,0,NULL,54,7,0,0,0,'290Гр3>=290Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(55,NULL,0,NULL,55,7,0,0,0,'300Гр3>=300Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(56,NULL,0,NULL,56,7,0,0,0,'310Гр3>=310Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(57,NULL,0,NULL,57,5,0,0,0,'400Гр3 =020Гр4-025Гр4+030Гр4-033Гр4 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(58,NULL,0,NULL,58,3,0,0,0,'100>=070 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(59,NULL,0,NULL,59,3,0,0,0,'Укажите расходы по строке 010 или 200 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(60,NULL,0,NULL,60,3,0,0,0,'Укажите расходы по строке 020 или 210 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(61,NULL,0,NULL,61,3,0,0,0,'Укажите данные по строке 030 или 220 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(62,NULL,0,NULL,62,3,0,0,0,'Укажите данные по строке 040 или 280 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(63,NULL,0,NULL,63,3,0,0,0,'Укажите данные по строке 050 или 290 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(64,NULL,0,NULL,64,3,0,0,0,'Укажите данные по строке 060 или 300 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(65,NULL,0,NULL,65,3,0,0,0,'Укажите данные по строке 070 или 310 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(66,NULL,0,NULL,66,1,0,0,0,'Укажите данные по строке 230 или 400 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(67,NULL,0,NULL,67,1,0,0,0,'Укажите данные по строке 240 или 410 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(68,NULL,0,NULL,68,1,0,0,0,'Укажите данные по строке 241 или 411 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(69,NULL,0,NULL,69,1,0,0,0,'Укажите данные по строке 242 или 412 =  0',0,0,1,'20100121','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(70,NULL,0,NULL,70,1,0,0,0,'Укажите данные по строке 243 или 413 =  0',0,0,1,'20100121','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(71,NULL,0,NULL,71,1,0,0,0,'Укажите данные по строке 250 или 420 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(72,NULL,0,NULL,72,1,0,0,0,'Укажите данные по строке 251 или 421 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(73,NULL,0,NULL,73,1,0,0,0,'Укажите данные по строке 252 или 422 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(74,NULL,0,NULL,74,1,0,0,0,'Укажите данные по строке 253 или 423 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(75,NULL,0,NULL,75,1,0,0,0,'Укажите данные по строке 260 или 430 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(76,NULL,0,NULL,76,1,0,0,0,'Укажите данные по строке 261 или 431 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(77,NULL,0,NULL,77,1,0,0,0,'Укажите данные по строке 262 или 432 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(78,NULL,0,NULL,78,1,0,0,0,'Укажите данные по строке 263 или 433 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(79,NULL,0,NULL,79,1,0,0,0,'Укажите данные по строке 264 или 434 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(80,NULL,0,NULL,80,1,0,0,0,'Укажите данные по строке 270 или 440 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(81,NULL,0,NULL,81,1,0,0,0,'Укажите данные по строке 271 или 441 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(82,NULL,0,NULL,82,1,0,0,0,'Укажите данные по строке 272 или 442 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(83,NULL,0,NULL,83,1,0,0,0,'Укажите данные по строке 273 или 443 =  0',0,0,1,'20100211','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(84,NULL,0,NULL,84,1,0,0,0,'Укажите данные по строке 274 или 444 =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(85,NULL,0,NULL,85,1,0,0,0,'Укажите данные по строке 94 или 450 или 460 =  0',0,0,1,'20110112','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(86,NULL,0,NULL,86,7,0,0,0,'Средняя заработная плата лиц, замещающих  государственные должности =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(87,NULL,0,NULL,87,7,0,0,0,'Средняя заработная плата лиц, замещающие должности государственной гражданской службы =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(88,NULL,0,NULL,88,7,0,0,0,'Сред. заработн. плата лиц, замещающих отдельные должности гос. гражд. службы =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(89,NULL,0,NULL,89,7,0,0,0,'Сред. заработн. плата лиц, замещающих  должности иного вида фед. гос. службы =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(90,NULL,0,NULL,90,7,0,0,0,'Сред. заработн. плата работников государственного органа, замещающих  должности, не являющиеся  должн. гос. гражд. службы =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(91,NULL,0,NULL,91,7,0,0,0,'Сред. заработн. плата работников гос. органа, оплата труда которых производится на основе ETC =  0',0,0,1,'20090116','','','','0503074G','20101231','','=',9,'','')
INSERT #A VALUES(92,NULL,0,NULL,92,3,0,0,0,'Укажите данные по строке 320 или 310 =  0',0,0,1,'20120131','','','','0503074G','20101231','','=',9,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 92
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%020%=%021%+%023%+%025%'',''4'')','020-(021-023-025)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%030%=%031%+%032%+%033%'',''4'')','030-(031+032+033)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%040%=%041%+%042%'',''4'')','040-(041+042)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%070%=%010%+%020%+%030%+%040%+%050%+%060%'',''4'')','070-(010+020+030+040+050+060)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%082%=%083%+%084%'',''4'')','082-(083+084)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%091%=%092%+%093%'',''4'')','091-(092+093)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%100%=%070%+%080%+%090%'',''*'')','100-(070+080+090)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%230%=%210%+%220%'' ,''*'')','230-(210+220)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%240%=%241%+%242%+%243%'' ,''*'')','240-(241+242+243)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%250%=%251%+%252%+%253%'' ,''*'')','250-(251+252+253)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%260%=%261%+%262%+%263%+%264%'' ,''*'')','260-(261+262+263+264)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%270%=%271%+%272%+%273%+%274%'' ,''*'')','270-(271+272+273+274)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%310%=%200%+%230%+%280%+%290%+%300%'' ,''*'')','310-(200+230+280+290+300)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%400%=%410%+%420%+%430%+%440%'' ,''*'')','400-(410+420+430+440)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%410%=%411%+%412%+%413%'',''*'')','410-(411+412+413)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%420%=%421%+%422%+%423%'',''*'')','420-(421+422+423)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%430%=%431%+%432%+%433%+%434%'',''*'')','430-(431+432+433+434)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%440%=%441%+%442%+%443%+%444%'',''*'')','440-(441+442+443+444)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%070Гр3%>=%070Гр4% '','''')','070Гр3>=070Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%080Гр3%>=%080Гр4%'','''')','080Гр3>=080Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%100Гр3%>=%100Гр4%'','''')','100Гр3>=100Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%080%>=%081%+%082% '',''*'')','080>=081+082','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%200Гр3%>=%200Гр4%'','''')','200Гр3>=200Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%210Гр3%>=%210Гр4%'','''')','210Гр3>=210Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%220Гр3%>=%220Гр4%'','''')','220Гр3>=220Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%230Гр3%>=%230Гр4%'','''')','230Гр3>=230Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(26,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%240Гр3%>=%240Гр4%'','''')','240Гр3>=240Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(27,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%241Гр3%>=%241Гр4%'','''')','241Гр3>=241Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(28,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%242Гр3%>=%242Гр4%'','''')','242Гр3>=242Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(29,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%243Гр3%>=%243Гр4%'','''')','243Гр3>=243Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(30,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%250Гр3%>=%250Гр4%'','''')','250Гр3>=250Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(31,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%251Гр3%>=%251Гр4%'','''')','251Гр3>=251Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(32,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%252Гр3%>=%252Гр4%'','''')','252Гр3>=252Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(33,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%253Гр3%>=%253Гр4%'','''')','253Гр3>=253Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(34,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%260Гр3%>=%260Гр4%'','''')','260Гр3>=260Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(35,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%261Гр3%>=%261Гр4%'','''')','261Гр3>=261Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(36,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%262Гр3%>=%262Гр4%'','''')','262Гр3>=262Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(37,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%263Гр3%>=%263Гр4%'','''')','263Гр3>=263Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(38,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%264Гр3%>=%264Гр4%'','''')','264Гр3>=264Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(39,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%270Гр3%>=%270Гр4%'','''')','270Гр3>=270Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(40,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%271Гр3%>=%271Гр4%'','''')','271Гр3>=271Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(41,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%272Гр3%>=%272Гр4%'','''')','272Гр3>=272Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(42,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%273Гр3%>=%273Гр4%'','''')','273Гр3>=273Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(43,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%230%=%240%+%250%+%260%+%270%'',''*'')','230-(240+250+260+270)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(44,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%010%=%011%+%012%+%013%'',''*'')','010-(011+012+013)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(45,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%021Гр4%>=%022Гр4%'','''')','021Гр4>=021Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(46,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%023Гр4%>=%024Гр4%'','''')','023Гр4>=024Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(47,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%042Гр4%>=%043Гр4%'','''')','042Гр4>=043Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(48,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%080Гр4%>=%081Гр4%+%082Гр4%'','''')','080Гр4>=081Гр4+082Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(49,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%090Гр4%>=%091Гр4%+%094Гр4%+%095Гр4%'','''')','090Гр4>=091Гр4+094Гр4+095Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(50,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%090Гр3%>=%090Гр4%'','''')','090Гр3>=090Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(51,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%274Гр3%>=%274Гр4%'','''')','274Гр3>=274Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(52,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%280Гр3%>=%280Гр4%'','''')','280Гр3>=280Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(53,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%290Гр3%>=%290Гр4%'','''')','290Гр3>=290Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(54,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%300Гр3%>=%300Гр4%'','''')','300Гр3>=300Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(55,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%310Гр3%>=%310Гр4%'','''')','310Гр3>=310Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(56,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%400Гр3%=%020Гр4%-%025Гр4%+%030Гр4%-%033Гр4%'' ,'''')','400Гр3 =020Гр4-025Гр4+030Гр4-033Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(57,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%100%>=%070%'',''*'')','100>=070','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(58,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %010Гр4%=0 AND %200Гр5%=0 OR %010Гр4%>0 AND %200Гр5%>0 then 1 else 0 end'',''*#Укажите расходы по строке 010 или 200'')','Укажите расходы по строке 010 или 200','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(59,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %020Гр4%=0 AND %210Гр5%=0 OR %020Гр4%>0 AND %210Гр5%>0 then 1 else 0 end'',''*#Укажите расходы по строке 020 или 210'')','Укажите расходы по строке 020 или 210','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(60,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %030Гр4%=0 AND %220Гр5%=0 OR %030Гр4%>0 AND %220Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 030 или 220'')','Укажите данные по строке 030 или 220','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(61,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %040Гр4%=0 AND %280Гр5%=0 OR %040Гр4%>0 AND %280Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 040 или 280'')','Укажите данные по строке 040 или 280','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(62,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %050Гр4%=0 AND %290Гр5%=0 OR %050Гр4%>0 AND %290Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 050 или 290'')','Укажите данные по строке 050 или 290','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(63,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %060Гр4%=0 AND %300Гр5%=0 OR %060Гр4%>0 AND %300Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 060 или 300'')','Укажите данные по строке 060 или 300','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(64,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %070Гр4%=0 AND %310Гр5%=0 OR %070Гр4%>0 AND %310Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 070 или 310'')','Укажите данные по строке 070 или 310','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(65,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %230Гр5%=0 AND %400Гр3%=0 OR %230Гр5%>0 AND %400Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 230 или 400'')','Укажите данные по строке 230 или 400','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(66,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %240Гр5%=0 AND %410Гр3%=0 OR %240Гр5%>0 AND %410Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 240 или 410'')','Укажите данные по строке 240 или 410','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(67,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(68,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %241Гр5%=0 AND %411Гр3%=0 OR %241Гр5%>0 AND %411Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 241 или 411'')','Укажите данные по строке 241 или 411','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(68,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(69,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %242Гр5%=0 AND %412Гр3%=0 OR %242Гр5%>0 AND %412Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 242 или 412'')','Укажите данные по строке 242 или 412','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(69,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %243Гр5%=0 AND %413Гр3%=0 OR %243Гр5%>0 AND %413Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 243 или 413'')','Укажите данные по строке 243 или 413','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(70,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %250Гр5%=0 AND %420Гр3%=0 OR %250Гр5%>0 AND %420Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 250 или 420'')','Укажите данные по строке 250 или 420','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(71,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %251Гр5%=0 AND %421Гр3%=0 OR %251Гр5%>0 AND %421Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 251 или 421'')','Укажите данные по строке 251 или 421','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(72,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %252Гр5%=0 AND %422Гр3%=0 OR %252Гр5%>0 AND %422Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 252 или 422'')','Укажите данные по строке 252 или 422','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(73,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %253Гр5%=0 AND %423Гр3%=0 OR %253Гр5%>0 AND %423Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 253 или 423'')','Укажите данные по строке 253 или 423','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(74,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %260Гр5%=0 AND %430Гр3%=0 OR %260Гр5%>0 AND %430Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 260 или 430'')','Укажите данные по строке 260 или 430','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(75,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %261Гр5%=0 AND %431Гр3%=0 OR %261Гр5%>0 AND %431Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 261 или 431'')','Укажите данные по строке 261 или 431','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(76,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %262Гр5%=0 AND %432Гр3%=0 OR %262Гр5%>0 AND %432Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 262 или 432'')','Укажите данные по строке 262 или 432','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(77,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %263Гр5%=0 AND %433Гр3%=0 OR %263Гр5%>0 AND %433Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 263 или 433'')','Укажите данные по строке 263 или 433','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(78,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %264Гр5%=0 AND %434Гр3%=0 OR %264Гр5%>0 AND %434Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 264 или 434'')','Укажите данные по строке 264 или 434','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(79,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %270Гр5%=0 AND %440Гр3%=0 OR %270Гр5%>0 AND %440Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 270 или 440'')','Укажите данные по строке 270 или 440','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(80,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %271Гр5%=0 AND %441Гр3%=0 OR %271Гр5%>0 AND %441Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 271 или 441'')','Укажите данные по строке 271 или 441','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(81,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %272Гр5%=0 AND %442Гр3%=0 OR %272Гр5%>0 AND %442Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 272 или 442'')','Укажите данные по строке 272 или 442','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(82,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %273Гр5%=0 AND %443Гр3%=0 OR %273Гр5%>0 AND %443Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 273 или 443'')','Укажите данные по строке 273 или 443','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(83,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(84,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %274Гр5%=0 AND %444Гр3%=0 OR %274Гр5%>0 AND %444Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 274 или 444'')','Укажите данные по строке 274 или 444','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(84,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(85,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when (%094Гр4%>0 AND %450Гр4%>0 OR %094Гр4%>0 AND %460Гр4%>0) OR (%094Гр4%=0 AND %450Гр4%=0 AND %460Гр4%=0) then 1 else 0 end'',''*#Укажите данные по строке 094 или 450 или 460'')','Укажите данные по строке 94 или 450 или 460','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(85,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(86,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещ. гос. долж.=%%010Гр4%/%200Гр5%/%MONTH%'','''')','Средняя заработная плата лиц, замещающих  государственные должности','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(86,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(87,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещ. долж. гос. гражданской службы=%%020Гр4%/%210Гр5%/%MONTH%'','''')','Средняя заработная плата лиц, замещающие должности государственной гражданской службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(87,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещающих отдельные должности =%%030Гр4%/%220Гр5%/%MONTH%'','''')','Сред. заработн. плата лиц, замещающих отдельные должности гос. гражд. службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(88,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещающих  должности иного вида фед. гос. службы=%%040Гр4%/%280Гр5%/%MONTH%'','''')','Сред. заработн. плата лиц, замещающих  должности иного вида фед. гос. службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(89,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата работников государственного органа, замещающих  должности, не являющиеся  должн. гос. гражд. службы=%%050Гр4%/%290Гр5%/%MONTH%'','''')','Сред. заработн. плата работников государственного органа, замещающих  должности, не являющиеся  должн. гос. гражд. службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(90,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата работников гос. органа, оплата труда которых производится на основе ETC=%%060Гр4%/%300Гр5%/%MONTH%'','''')','Сред. заработн. плата работников гос. органа, оплата труда которых производится на основе ETC','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(91,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %320Гр3%=0 AND %310Гр3%=0 OR %320Гр3%>0 AND %310Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 310 или 320'')','Укажите данные по строке 320 или 310','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(92,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 184
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '5         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'5','Годовые формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '8         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'8','14-ые формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '999999    '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'999999','формы отчетности',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-07-03 11:51:50.803',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-07-03 11:51:50.803'
	BEGIN
		SELECT @vcMessage = 'Форма 0503074G с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0503074G с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-07-03 11:51:50.803. Обновление отклонено.'
	END

	 IF OBJECT_ID('tempdb..#tabUpdateMessages') IS NOT NULL
	 BEGIN
		 INSERT #tabUpdateMessages([TXT]) VALUES (@vcMessage)
	 END
	 SELECT @vcMessage
END
GO

-- Загрузить подсказку.
DECLARE @iLINK_FORM INT
SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo
if object_id('tempdb..#F1') is NOT NULL drop table #r_files
create table #F1 (ID int, Name varchar(254), Path varchar(254), CreateDate datetime, FileSize int)
if object_id('tempdb..#F2') is NOT NULL drop table #r_fileparts
create table #F2 (File_ID int, Orders int, Body varchar(8000))
insert #F1 (ID, Name, Path, CreateDate, FileSize) values(115,'СПРАВКА ПО РАСЧЁТУ 14 ФОРМЫ.MHT', 'D:\TEST', convert(datetime, '2011-02-22 08:31:00.000', 121), 109829)
insert #F2 (File_ID, Orders, Body) values(115,1, 'MIME-Version: 1.0
Content-Type: multipart/related; boundary="----=_NextPart_01CBD26A.F54A6190"

Данный документ является веб-страницей в одном файле, также называемой файлом веб-архива. Если вы видите это сообщение, значит, данный обозреватель или редактор не поддерживает файлы веб-архива. Загрузите обозреватель, поддерживающий веб-архивы, например Windows® Internet Explorer®.

------=_NextPart_01CBD26A.F54A6190
Content-Location: file:///C:/90708BCB/file4923.htm
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset="us-ascii"

<html xmlns:v=3D"urn:schemas-microsoft-com:vml"
xmlns:o=3D"urn:schemas-microsoft-com:office:office"
xmlns:w=3D"urn:schemas-microsoft-com:office:word"
xmlns:m=3D"http://schemas.microsoft.com/office/2004/12/omml"
xmlns=3D"http://www.w3.org/TR/REC-html40">

<head>
<meta http-equiv=3DContent-Type content=3D"text/html; charset=3Dus-ascii">
<meta name=3DProgId content=3DWord.Document>
<meta name=3DGenerator content=3D"Microsoft Word 12">
<meta name=3DOriginator content=3D"Microsoft Word 12">
<link rel=3DFile-List href=3D"file4923.files/filelist.xml">
<!--[if gte mso 9]><xml>
 <o:DocumentProperties>
  <o:Author>&#1048;&#1075;&#1085;&#1072;&#1090;&#1100;&#1077;&#1074;</o:Aut=
hor>
  <o:Template>Normal</o:Template>
  <o:LastAuthor>&#1048;&#1075;&#1085;&#1072;&#1090;&#1100;&#1077;&#1074;</o=
:LastAuthor>
  <o:Revision>1</o:Revision>
  <o:TotalTime>1</o:TotalTime>
  <o:Created>2011-02-22T05:30:00Z</o:Created>
  <o:LastSaved>2011-02-22T05:31:00Z</o:LastSaved>
  <o:Pages>4</o:Pages>
  <o:Words>1312</o:Words>
  <o:Characters>7481</o:Characters>
  <o:Company>&#1054;&#1054;&#1054; &#1050;&#1077;&#1081;&#1089;&#1080;&#108=
9;&#1090;&#1077;&#1084;&#1089;</o:Company>
  <o:Lines>62</o:Lines>
  <o:Paragraphs>17</o:Paragraphs>
  <o:CharactersWithSpaces>8776</o:CharactersWithSpaces>
  <o:Version>12.00</o:Version>
 </o:DocumentProperties>
</xml><![endif]-->
<link rel=3DthemeData href=3D"file4923.files/themedata.thmx">
<link rel=3DcolorSchemeMapping href=3D"file4923.files/colorschememapping.xm=
l">
<!--[if gte mso 9]><xml>
 <w:WordDocument>
  <w:SpellingState>Clean</w:SpellingState>
  <w:GrammarState>Clean</w:GrammarState>
  <w:TrackMoves>false</w:TrackMoves>
  <w:TrackFormatting/>
  <w:PunctuationKerning/>
  <w:ValidateAgainstSchemas/>
  <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>
  <w:IgnoreMixedContent>false</w:IgnoreMixedContent>
  <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>
  <w:DoNotPromoteQF/>
  <w:LidThemeOther>RU</w:LidThemeOther>
  <w:LidThemeAsian>X-NONE</w:LidThemeAsian>
  <w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript>
  <w:Compatibility>
   <w:BreakWrappedTables/>
   <w:SnapToGridInCell/>
   <w:WrapTextWithPunct/>
   <w:UseAsianBreakRules/>
   <w:DontGrowAutofit/>
   <w:SplitPgBreakAndParaMark/>
   <w:DontVertAlignCellWithSp/>
   <w:DontBreakConstrainedForcedTables/>
   <w:DontVertAlignInTxbx/>
   <w:Word11KerningPairs/>
   <w:CachedColBalance/>
  </w:Compatibility>
  <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
  <m:mathPr>
   <m:mathFont m:val=3D"Cambria Math"/>
   <m:brkBin m:val=3D"before"/>
   <m:brkBinSub m:val=3D"&#45;-"/>
   <m:smallFrac m:val=3D"off"/>
   <m:dispDef/>
   <m:lMargin m:val=3D"0"/>
   <m:rMargin m:val=3D"0"/>
   <m:defJc m:val=3D"centerGroup"/>
   <m:wrapIndent m:val=3D"1440"/>
   <m:intLim m:val=3D"subSup"/>
   <m:naryLim m:val=3D"undOvr"/>
  </m:mathPr></w:WordDocument>
</xml><![endif]--><!--[if gte mso 9]><xml>
 <w:LatentStyles DefLockedState=3D"false" DefUnhideWhenUsed=3D"true"
  DefSemiHidden=3D"true" DefQFormat=3D"false" DefPriority=3D"99"
  LatentStyleCount=3D"267">
  <w:LsdException Locked=3D"false" Priority=3D"0" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Normal"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"heading 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" QFormat=3D"true" Name=3D"=
heading 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" QFormat=3D"true" Name=3D"=
heading 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" QFormat=3D"true" Name=3D"=
heading 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" QFormat=3D"true" Name=3D"=
heading 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" QFormat=3D"true" Name=3D"=
heading 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" QFormat=3D"true" Name=3D"=
heading 7"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" QFormat=3D"true" Name=3D"=
heading 8"/>
  <w:LsdException Locked=3D"false" Priority=3D"9" QFormat=3D"true" Name=3D"=
heading 9"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 7"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 8"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" Name=3D"toc 9"/>
  <w:LsdException Locked=3D"false" Priority=3D"35" QFormat=3D"true" Name=3D=
"caption"/>
  <w:LsdException Locked=3D"false" Priority=3D"10" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Title"/>
  <w:LsdException Locked=3D"false" Priority=3D"1" Name=3D"Default Paragraph=
 Font"/>
  <w:LsdException Locked=3D"false" Priority=3D"11" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Subtitle"/>
  <w:LsdException Locked=3D"false" Priority=3D"22" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Strong"/>
  <w:LsdException Locked=3D"false" Priority=3D"20" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Emphasis"/>
  <w:LsdException Locked=3D"false" Priority=3D"59" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Table Grid"/>
  <w:LsdException Locked=3D"false" UnhideWhenUsed=3D"false" Name=3D"Placeho=
lder Text"/>
  <w:LsdException Locked=3D"false" Priority=3D"1" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"No Spacing"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Shading"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light List"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Grid"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 1"/>
  <w:LsdException Locked=3D"')

insert #F2 (File_ID, Orders, Body) values(115,2, 'false" Priority=3D"68" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Dark List"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Shading"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful List"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Grid"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Shading Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light List Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Grid Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 1 Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 2 Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 1 Accent 1"/>
  <w:LsdException Locked=3D"false" UnhideWhenUsed=3D"false" Name=3D"Revisio=
n"/>
  <w:LsdException Locked=3D"false" Priority=3D"34" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"List Paragraph"/>
  <w:LsdException Locked=3D"false" Priority=3D"29" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Quote"/>
  <w:LsdException Locked=3D"false" Priority=3D"30" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Intense Quote"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 2 Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 1 Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 2 Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 3 Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Dark List Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Shading Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful List Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Grid Accent 1"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Shading Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light List Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Grid Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 1 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 2 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 1 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 2 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 1 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 2 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 3 Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Dark List Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Shading Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful List Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Grid Accent 2"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Shading Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light List Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Grid Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 1 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 2 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 1 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 2 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 1 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 2 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 3 Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Dark List Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Shading Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful List Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Grid Accent 3"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Shading Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light List Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Grid Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 1 Accent 4"/>
  <w:Lsd')

insert #F2 (File_ID, Orders, Body) values(115,3, 'Exception Locked=3D"false" Priority=3D"64" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 2 Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 1 Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 2 Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 1 Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 2 Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 3 Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Dark List Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Shading Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful List Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Grid Accent 4"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Shading Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light List Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Grid Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 1 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 2 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 1 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 2 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 1 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 2 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 3 Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Dark List Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Shading Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful List Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Grid Accent 5"/>
  <w:LsdException Locked=3D"false" Priority=3D"60" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Shading Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"61" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light List Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"62" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Light Grid Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"63" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 1 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"64" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Shading 2 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"65" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 1 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"66" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium List 2 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"67" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 1 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"68" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 2 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"69" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Medium Grid 3 Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"70" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Dark List Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"71" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Shading Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"72" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful List Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"73" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" Name=3D"Colorful Grid Accent 6"/>
  <w:LsdException Locked=3D"false" Priority=3D"19" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Subtle Emphasis"/>
  <w:LsdException Locked=3D"false" Priority=3D"21" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Intense Emphasis"/>
  <w:LsdException Locked=3D"false" Priority=3D"31" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Subtle Reference"/>
  <w:LsdException Locked=3D"false" Priority=3D"32" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Intense Reference"/>
  <w:LsdException Locked=3D"false" Priority=3D"33" SemiHidden=3D"false"
   UnhideWhenUsed=3D"false" QFormat=3D"true" Name=3D"Book Title"/>
  <w:LsdException Locked=3D"false" Priority=3D"37" Name=3D"Bibliography"/>
  <w:LsdException Locked=3D"false" Priority=3D"39" QFormat=3D"true" Name=3D=
"TOC Heading"/>
 </w:LatentStyles>
</xml><![endif]-->
<style>
<!--
 /* Font Definitions */
 @font-face
	{font-family:Wingdings;
	panose-1:5 0 0 0 0 0 0 0 0 0;
	mso-font-charset:2;
	mso-generic-font-family:auto;
	mso-font-pitch:variable;
	mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
	{font-family:"Cambria Math";
	panose-1:2 4 5 3 5 4 6 3 2 4;
	mso-font-charset:204;
	mso-generic-font-family:roman;
	mso-font-pitch:variable;
	mso-font-signature:-1610611985 1107304683 0 0 415 0;}
 /* Style Definitions */
 p.MsoNormal, li.MsoNormal, div.MsoNormal
	{mso-style-unhide:no;
	mso-style-qformat:yes;
	mso-style-parent:"";
	margin:0cm;
	margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:12.0pt;
	font-family:"Times New Roman","serif";
	mso-fareast-font-family:"Times New Roman";}
span.SpellE
	{mso-style-name:"";
	mso-spl-e:yes;}
span.GramE
	{mso-style-name:"";
	mso-gram-e:yes;}
.MsoChpDefault
	{mso-style-type:export-only;
	mso-default-props:yes;
	mso-ascii-font-family:Calibri;
	mso-ascii-theme-font:minor-latin;
	mso-fareast-font-family:Calibri;
	mso-fareast-theme-font:minor-latin;
	mso-hansi-font-family:Calibri;
	mso-hansi-theme-font:minor-latin;
	mso-bidi-font-family:"Times New Roman";
	mso-bidi-theme-font:minor-bidi;
	mso-fareast-language:EN-US;}
.MsoPapDefault
	{mso-style-type:export-only;
	margin-bottom:10.0pt;
	line-height:115%;}
@page WordSection1
	{size:595.3pt')

insert #F2 (File_ID, Orders, Body) values(115,4, ' 841.9pt;
	margin:2.0cm 42.5pt 2.0cm 3.0cm;
	mso-header-margin:35.4pt;
	mso-footer-margin:35.4pt;
	mso-paper-source:0;}
div.WordSection1
	{page:WordSection1;}
 /* List Definitions */
 @list l0
	{mso-list-id:1615401855;
	mso-list-type:hybrid;
	mso-list-template-ids:1609475116 68747265 68747267 68747269 68747265 68747=
267 68747269 68747265 68747267 68747269;}
@list l0:level1
	{mso-level-number-format:bullet;
	mso-level-text:\F0B7;
	mso-level-tab-stop:none;
	mso-level-number-position:left;
	margin-left:54.0pt;
	text-indent:-18.0pt;
	font-family:Symbol;}
ol
	{margin-bottom:0cm;}
ul
	{margin-bottom:0cm;}
-->
</style>
<!--[if gte mso 10]>
<style>
 /* Style Definitions */
 table.MsoNormalTable
	{mso-style-name:"\041E\0431\044B\0447\043D\0430\044F \0442\0430\0431\043B\=
0438\0446\0430";
	mso-tstyle-rowband-size:0;
	mso-tstyle-colband-size:0;
	mso-style-noshow:yes;
	mso-style-priority:99;
	mso-style-qformat:yes;
	mso-style-parent:"";
	mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
	mso-para-margin-top:0cm;
	mso-para-margin-right:0cm;
	mso-para-margin-bottom:10.0pt;
	mso-para-margin-left:0cm;
	line-height:115%;
	mso-pagination:widow-orphan;
	font-size:11.0pt;
	font-family:"Calibri","sans-serif";
	mso-ascii-font-family:Calibri;
	mso-ascii-theme-font:minor-latin;
	mso-hansi-font-family:Calibri;
	mso-hansi-theme-font:minor-latin;
	mso-bidi-font-family:"Times New Roman";
	mso-bidi-theme-font:minor-bidi;
	mso-fareast-language:EN-US;}
</style>
<![endif]--><!--[if gte mso 9]><xml>
 <o:shapedefaults v:ext=3D"edit" spidmax=3D"2050"/>
</xml><![endif]--><!--[if gte mso 9]><xml>
 <o:shapelayout v:ext=3D"edit">
  <o:idmap v:ext=3D"edit" data=3D"1"/>
 </o:shapelayout></xml><![endif]-->
</head>

<body lang=3DRU style=3D''tab-interval:35.4pt''>

<div class=3DWordSection1>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1044;=
&#1083;&#1103;
&#1072;&#1074;&#1090;&#1086;&#1084;&#1072;&#1090;&#1080;&#1095;&#1077;&#108=
9;&#1082;&#1086;&#1075;&#1086;
&#1088;&#1072;&#1089;&#1095;&#1077;&#1090;&#1072; &#1089;&#1091;&#1084;&#10=
84;
&#1092;&#1086;&#1088;&#1084;&#1099; 14 (0503074)
&#1087;&#1088;&#1077;&#1076;&#1074;&#1072;&#1088;&#1080;&#1090;&#1077;&#108=
3;&#1100;&#1085;&#1086;
&#1085;&#1077;&#1086;&#1073;&#1093;&#1086;&#1076;&#1080;&#1084;&#1086; &#10=
87;&#1088;&#1086;&#1074;&#1077;&#1088;&#1080;&#1090;&#1100;
&#1085;&#1072;&#1089;&#1090;&#1088;&#1086;&#1081;&#1082;&#1091;
&#1089;&#1083;&#1077;&#1076;&#1091;&#1102;&#1097;&#1080;&#1093;
&#1089;&#1087;&#1088;&#1072;&#1074;&#1086;&#1095;&#1085;&#1080;&#1082;&#108=
6;&#1074;:</p>

<p class=3DMsoNormal style=3D''margin-left:54.0pt;text-indent:-18.0pt;mso-li=
st:l0 level1 lfo1;
tab-stops:95.65pt''><![if !supportLists]><span style=3D''font-family:Symbol;
mso-fareast-font-family:Symbol;mso-bidi-font-family:Symbol''><span
style=3D''mso-list:Ignore''>&middot;<span style=3D''font:7.0pt "Times New Roma=
n"''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span></span></span><![endif]>&#1074; &#1079;&#1072;&#1076;&#1072;&#1095;&=
#1077;
&laquo;&#1047;&#1072;&#1088;&#1087;&#1083;&#1072;&#1090;&#1072;-&#1050;&#10=
57;&raquo;
&#1074;
&#1089;&#1087;&#1088;&#1072;&#1074;&#1086;&#1095;&#1085;&#1080;&#1082;&#107=
7;
&laquo;&#1042;&#1080;&#1076;&#1099; &#1085;&#1072;&#1095;&#1080;&#1089;&#10=
83;&#1077;&#1085;&#1080;&#1081;&raquo;
&#1085;&#1077;&#1086;&#1073;&#1093;&#1086;&#1076;&#1080;&#1084;&#1086;
&#1087;&#1088;&#1086;&#1074;&#1077;&#1088;&#1080;&#1090;&#1100;
&#1085;&#1072;&#1089;&#1090;&#1088;&#1086;&#1081;&#1082;&#1091;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1072;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;;</p>

<p class=3DMsoNormal style=3D''margin-left:54.0pt;text-indent:-18.0pt;mso-li=
st:l0 level1 lfo1;
tab-stops:95.65pt''><![if !supportLists]><span style=3D''font-family:Symbol;
mso-fareast-font-family:Symbol;mso-bidi-font-family:Symbol''><span
style=3D''mso-list:Ignore''>&middot;<span style=3D''font:7.0pt "Times New Roma=
n"''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span></span></span><![endif]><span class=3DGramE>&#1074;
&#1079;&#1072;&#1076;&#1072;&#1095;&#1077;
&laquo;&#1047;&#1072;&#1088;&#1087;&#1083;&#1072;&#1090;&#1072;-&#1050;&#10=
57;&raquo;
&#1080;&#1083;&#1080;
&laquo;&#1050;&#1072;&#1076;&#1088;&#1099;-&#1050;&#1057;&raquo; &#1074;
&#1089;&#1087;&#1088;&#1072;&#1074;&#1086;&#1095;&#1085;&#1080;&#1082;&#107=
7;
&laquo;&#1064;&#1090;&#1072;&#1090;&#1085;&#1086;&#1077;
&#1088;&#1072;&#1089;&#1087;&#1080;&#1089;&#1072;&#1085;&#1080;&#1077;&raqu=
o;
&#1085;&#1077;&#1086;&#1073;&#1093;&#1086;&#1076;&#1080;&#1084;&#1086;
&#1087;&#1088;&#1086;&#1074;&#1077;&#1088;&#1080;&#1090;&#1100; &#1074;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1072;&#1093;
&laquo;&#1080;&#1089;&#1090;&#1086;&#1088;&#1080;&#1080;&raquo;
&#1088;&#1077;&#1082;&#1074;&#1080;&#1079;&#1080;&#1090;&#1099;
&laquo;&#1058;&#1080;&#1087;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;&raquo;, &la=
quo;&#1050;&#1072;&#1090;&#1077;&#1075;&#1086;&#1088;&#1080;&#1103;
<span class=3DSpellE>&#1075;&#1086;&#1089;</span>.
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;&raquo; &#10=
80;
&laquo;&#1043;&#1088;&#1091;&#1087;&#1087;&#1072; <span class=3DSpellE>&#10=
75;&#1086;&#1089;</span>.
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;&raquo;.</sp=
an></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1057;=
&#1091;&#1084;&#1084;&#1099;
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103; &#10=
89;
&#1085;&#1072;&#1095;&#1072;&#1083;&#1086; &#1075;&#1086;&#1076;&#1072;
&#1087;&#1086; &#1084;&#1077;&#1089;&#1103;&#1094;, &#1103;&#1074;&#1083;&#=
1103;&#1102;&#1097;&#1080;&#1081;&#1089;&#1103;
&#1087;&#1086;&#1089;&#1083;&#1077;&#1076;&#1085;&#1080;&#1084; &#1074;
&#1086;&#1090;&#1095;&#1105;&#1090;&#1085;&#1086;&#1084; <span class=3DGram=
E>&#1087;&#1077;&#1088;&#1080;&#1086;&#1076;&#1077;</span>
<b style=3D''mso-bidi-font-weight:normal''>&#1087;&#1086; &#1050;&#1041;&#105=
0;
&#1089; &#1042;&#1056; (&#1074;&#1080;&#1076;
&#1088;&#1072;&#1089;&#1093;&#1086;&#1076;&#1072;) =3D &#8216;012&#8217;</b=
>.</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>011</b>'' --&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1074;&#1086;&#1079;&#1085;&#1072;&#1075;&#1088;&#1072;&#1078;&#1076;&#107=
7;&#1085;&#1080;&#1077;
(&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1089;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;,
&#1079;&#1072;&#1088;&#1072;&#1073;&#1086;&#1090;&#1085;&#1072;&#1103;
&#1087;&#1083;&#1072;&#1090;&#1072; &#1089;&#1091;&#1076;&#1077;&#1081;)</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1089;=
&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&laquo;&#1043;&#1086;&#1089;&#1091;&#1076;&#1072')

insert #F2 (File_ID, Orders, Body) values(115,5, ';&#1088;&#1089;&#1090;&#107=
4;&#1077;&#1085;&#1085;&#1072;&#1103;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1100;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089; &#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>1.&#1076;&#1086;&#1083;&#1078;&#1085;&#10=
86;&#1089;&#1090;&#1085;&#1086;&#1081;
&#1086;&#1082;&#1083;&#1072;&#1076;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>2.&#1086;&#1082;&#1083;&#1072;&#1076;
&#1079;&#1072; &#1082;&#1083;&#1072;&#1089;&#1089;&#1085;&#1099;&#1081;
&#1095;&#1080;&#1085;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>3.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1074;&#1099;&#1089;&#1083;&#1091;&#1075;&#1091;
&#1083;&#1077;&#1090; &#1085;&#1072;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>4.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1086;&#1089;&#1086;&#1073;&#1099;&#1077;
&#1091;&#1089;&#1083;&#1086;&#1074;&#1080;&#1103;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>5.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1088;&#1072;&#1073;&#1086;&#1090;&#1091; &#1089;&#1086;
&#1089;&#1074;&#1077;&#1076;&#1077;&#1085;&#1080;&#1103;&#1084;&#1080;,
&#1089;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#1103;&#1102;&#1097;&#108=
0;&#1084;&#1080;
<span class=3DSpellE>&#1075;&#1086;&#1089;</span>.
&#1090;&#1072;&#1081;&#1085;&#1091;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>6.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1091;&#1095;&#1077;&#1085;&#1091;&#1102;
&#1089;&#1090;&#1077;&#1087;&#1077;&#1085;<span class=3DGramE>&#1100;(</spa=
n>&#1079;&#1074;&#1072;&#1085;&#1080;&#1077;)</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>7.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1087;&#1086;&#1095;&#1077;&#1090;&#1085;&#1086;&#1077;
&#1079;&#1074;&#1072;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>8.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1089;&#1083;&#1086;&#1078;&#1085;&#1086;&#1089;&#1090;&#11=
00;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>9.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072;
&#1085;&#1072;&#1087;&#1088;&#1103;&#1078;&#1077;&#1085;&#1085;&#1086;&#108=
9;&#1090;&#1100;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>10.&#1085;&#1072;&#1076;&#1073;&#1072;&#1=
074;&#1082;&#1072;
&#1079;&#1072; &#1074;&#1099;&#1089;&#1086;&#1082;&#1080;&#1077; &#1076;&#1=
086;&#1089;&#1090;&#1080;&#1078;&#1077;&#1085;&#1080;&#1103;
&#1074; &#1090;&#1088;&#1091;&#1076;&#1077; &#1080;
&#1089;&#1087;&#1077;&#1094;<span class=3DGramE>.&#1088;</span>&#1077;&#107=
8;&#1080;&#1084;
&#1088;&#1072;&#1073;&#1086;&#1090;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>012</b>'' -- &#1077;&#1078;&#1077;&#1084;&#1077;&#1089;&#1103;&#1095=
;&#1085;&#1086;&#1077;
(&#1077;&#1078;&#1077;&#1082;&#1074;&#1072;&#1088;&#1090;&#1072;&#1083;&#11=
00;&#1085;&#1086;&#1077;)
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077; &#1087;&#1086;&#10=
86;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1089;=
&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&laquo;&#1043;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#107=
4;&#1077;&#1085;&#1085;&#1072;&#1103;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1100;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089; &#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')

insert #F2 (File_ID, Orders, Body) values(115,6, '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>11.&#1077;&#1078;&#1077;&#1084;&#1077;&#1=
089;&#1103;&#1095;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>12.&#1087;&#1088;&#1077;&#1084;&#1080;&#1=
080;
&#1079;&#1072;
&#1074;&#1099;&#1087;&#1086;&#1083;&#1085;&#1077;&#1085;&#1080;&#1077;
&#1086;&#1089;&#1086;&#1073;&#1086; &#1074;&#1072;&#1078;&#1085;&#1099;&#10=
93;
&#1080; &#1089;&#1083;&#1086;&#1078;&#1085;&#1099;&#1093;
&#1079;&#1072;&#1076;&#1072;&#1085;&#1080;&#1081;<span style=3D''mso-tab-cou=
nt:
2''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=
&nbsp;&nbsp;&nbsp;&nbsp; </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>013</b>'' -- &#1077;&#1078;&#1077;&#1084;&#1077;&#1089;&#1103;&#1095=
;&#1085;&#1086;&#1077;
(&#1077;&#1078;&#1077;&#1082;&#1074;&#1072;&#1088;&#1090;&#1072;&#1083;&#11=
00;&#1085;&#1086;&#1077;)
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077; &#1087;&#1086;&#10=
86;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1089;=
&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&laquo;&#1043;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#107=
4;&#1077;&#1085;&#1085;&#1072;&#1103;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1100;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077; &#1088;&#1072;&#1074;&#=
1085;&#1086;&#1084;&#1091;
&laquo;212&raquo; &#1087;&#1086;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#1084; &#1089;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>13.&#1084;&#1072;&#1090;&#1077;&#1088;&#1=
080;&#1072;&#1083;&#1100;&#1085;&#1072;&#1103;
&#1087;&#1086;&#1084;&#1086;&#1097;&#1100;,
&#1074;&#1099;&#1087;&#1083;&#1072;&#1095;&#1080;&#1074;&#1072;&#1077;&#108=
4;&#1072;&#1103;
&#1079;&#1072; &#1089;&#1095;&#1105;&#1090; &#1060;&#1054;&#1058;
&#1043;&#1057;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>14.&#1077;&#1076;&#1080;&#1085;&#1086;&#1=
074;&#1088;&#1077;&#1084;&#1077;&#1085;&#1085;&#1072;&#1103;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1072; &#1087;&#1088;&#1080;
&#1087;&#1088;&#1077;&#1076;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#107=
7;&#1085;&#1080;&#1080;
&#1077;&#1078;&#1077;&#1075;&#1086;&#1076;&#1085;&#1086;&#1075;&#1086;
&#1086;&#1087;&#1083;&#1072;&#1095;&#1080;&#1074;&#1072;&#1077;&#1084;&#108=
6;&#1075;&#1086;
&#1086;&#1090;&#1087;&#1091;&#1089;&#1082;&#1072;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>15.&#1076;&#1088;&#1091;&#1075;&#1080;&#1=
077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099; &#1074;
&#1095;&#1072;&#1089;&#1090;&#1080; &#1074;&#1099;&#1087;&#1083;&#1072;&#10=
90;
&#1087;&#1086; &#1080;&#1090;&#1086;&#1075;&#1072;&#1084; &#1088;&#1072;&#1=
073;&#1086;&#1090;&#1099;<span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp; </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:2''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>021</b>'' --&#1086;&#1082;&#1083;&#1072;&#1076;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1075;&#1086;
&#1089;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1103;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1089;=
&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&laquo;&#1044;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1100; &#10=
75;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#1077;&#=
1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1; &#1089;&#1083;&#1091;&#1078;&#1073;&#1099;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo; &#1087;=
&#1086;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#1084; &#1089;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>1.&#1076;&#1086;&#1083;&#1078;&#1085;&#10=
86;&#1089;&#1090;&#1085;&#1086;&#1081;
&#1086;&#1082;&#1083;&#1072;&#1076;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>2.&#1086;&#1082;&#1083;&#1072;&#1076;
&#1079;&#1072; &#1082;&#1')

insert #F2 (File_ID, Orders, Body) values(115,7, '083;&#1072;&#1089;&#1089;&#1085;&#1099;&#1081;
&#1095;&#1080;&#1085;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>022</b>'' -- &#1086;&#1082;&#1083;&#1072;&#1076; &#1087;&#1086;
&#1079;&#1072;&#1085;&#1080;&#1084;&#1072;&#1077;&#1084;&#1086;&#1081;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1089;=
&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&laquo;&#1044;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1100; &#10=
75;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#1077;&#=
1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1; &#1089;&#1083;&#1091;&#1078;&#1073;&#1099;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo; &#1087;=
&#1086;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#1084; &#1089;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>1.&#1076;&#1086;&#1083;&#1078;&#1085;&#10=
86;&#1089;&#1090;&#1085;&#1086;&#1081;
&#1086;&#1082;&#1083;&#1072;&#1076;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp; </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>023</b>'' -- &#1076;&#1086;&#1087;&#1086;&#1083;&#1085;&#1080;&#1090=
;&#1077;&#1083;&#1100;&#1085;&#1099;&#1077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1089;=
&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&laquo;&#1044;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1100; &#10=
75;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#1077;&#=
1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1; &#1089;&#1083;&#1091;&#1078;&#1073;&#1099;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo; &#1087;=
&#1086;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#1084; &#1089;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>3.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1074;&#1099;&#1089;&#1083;&#1091;&#1075;&#1091;
&#1083;&#1077;&#1090; &#1085;&#1072;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>4.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1086;&#1089;&#1086;&#1073;&#1099;&#1077;
&#1091;&#1089;&#1083;&#1086;&#1074;&#1080;&#1103;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>5.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1088;&#1072;&#1073;&#1086;&#1090;&#1091; &#1089;&#1086;
&#1089;&#1074;&#1077;&#1076;&#1077;&#1085;&#1080;&#1103;&#1084;&#1080;,
&#1089;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#1103;&#1102;&#1097;&#108=
0;&#1084;&#1080;
<span class=3DSpellE>&#1075;&#1086;&#1089;</span>.
&#1090;&#1072;&#1081;&#1085;&#1091;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>10.&#1085;&#1072;&#1076;&#1073;&#1072;&#1=
074;&#1082;&#1072;
&#1079;&#1072; &#1074;&#1099;&#1089;&#1086;&#1082;&#1080;&#1077;
&#1076;&#1086;&#1089;&#1090;&#1080;&#1078;&#1077;&#1085;&#1080;&#1103; &#10=
74;
&#1090;&#1088;&#1091;&#1076;&#1077; &#1080; &#1089;&#1087;&#1077;&#1094;<sp=
an
class=3DGramE>.&#1088;</span>&#1077;&#1078;&#1080;&#1084;
&#1088;&#1072;&#1073;&#1086;&#1090;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>11.&#1077;&#1078;&#1077;&#1084;&#1077;&#1=
089;&#1103;&#1095;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>12.&#1087;&#1088;&#1077;&#1084;&#1080;&#1=
080;
&#1079;&#1072;
&#1074;&#1099;&#1087;&#1086;&#1083;&#1085;&#1077;&#1085;&#1080;&#1077;
&#1086;&#1089;&#1086;&#1073;&#1086; &#1074;&#1072;&#1078;&#1085;&#1099;&#10=
93;
&#1080; &#1089;&#1083;&#1086;&#1078;&#1085;&#1099;&#1093; &#1079;&#1072;&#1=
076;&#1072;&#1085;&#1080;&#1081;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nb')

insert #F2 (File_ID, Orders, Body) values(115,8, 'sp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>13.&#1084;&#1072;&#1090;&#1077;&#1088;&#1=
080;&#1072;&#1083;&#1100;&#1085;&#1072;&#1103;
&#1087;&#1086;&#1084;&#1086;&#1097;&#1100;,
&#1074;&#1099;&#1087;&#1083;&#1072;&#1095;&#1080;&#1074;&#1072;&#1077;&#108=
4;&#1072;&#1103;
&#1079;&#1072; &#1089;&#1095;&#1105;&#1090; &#1060;&#1054;&#1058;
&#1043;&#1057;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>14.&#1077;&#1076;&#1080;&#1085;&#1086;&#1=
074;&#1088;&#1077;&#1084;&#1077;&#1085;&#1085;&#1072;&#1103;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1072; &#1087;&#1088;&#1080;
&#1087;&#1088;&#1077;&#1076;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#107=
7;&#1085;&#1080;&#1080;
&#1077;&#1078;&#1077;&#1075;&#1086;&#1076;&#1085;&#1086;&#1075;&#1086;
&#1086;&#1087;&#1083;&#1072;&#1095;&#1080;&#1074;&#1072;&#1077;&#1084;&#108=
6;&#1075;&#1086;
&#1086;&#1090;&#1087;&#1091;&#1089;&#1082;&#1072;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>024</b>'' -- &#1077;&#1078;&#1077;&#1084;&#1077;&#1089;&#1103;&#1095=
;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1089;=
&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&laquo;&#1044;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1100; &#10=
75;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#1077;&#=
1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1; &#1089;&#1083;&#1091;&#1078;&#1073;&#1099;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo; &#1087;=
&#1086;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#1084; &#1089;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>11.&#1077;&#1078;&#1077;&#1084;&#1077;&#1=
089;&#1103;&#1095;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>025</b>'' -- &#1076;&#1088;&#1091;&#1075;&#1080;&#1077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099;<span class=3DGramE> ,</sp=
an>
&#1087;&#1088;&#1077;&#1076;&#1091;&#1089;&#1084;&#1086;&#1090;&#1088;&#107=
7;&#1085;&#1085;&#1099;&#1077;
&#1076;&#1077;&#1081;&#1089;&#1090;&#1074;&#1091;&#1102;&#1097;&#1080;&#108=
4;
&#1079;&#1072;&#1082;&#1086;&#1085;&#1086;&#1076;&#1072;&#1090;&#1077;&#108=
3;&#1100;&#1089;&#1090;&#1074;&#1086;&#1084;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1089;=
&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072; &#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#10=
89;&#1090;&#1080;
&laquo;&#1044;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1100; &#10=
75;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#1077;&#=
1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1; &#1089;&#1083;&#1091;&#1078;&#1073;&#1099;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo; &#1087;=
&#1086;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#1084; &#1089;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>6.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1091;&#1095;&#1077;&#1085;&#1091;&#1102;
&#1089;&#1090;&#1077;&#1087;&#1077;&#1085;<span class=3DGramE>&#1100;(</spa=
n>&#1079;&#1074;&#1072;&#1085;&#1080;&#1077;)</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>7.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1087;&#1086;&#1095;&#1077;&#1090;&#1085;&#1086;&#1077;
&#1079;&#1074;&#1072;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>8.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1089;&#1083;&#1086;&#1078;&#1085;&#1086;&#1089;&#1090;&#11=
00;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>9.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1085;&#1072;&#1087;&#1088;&#1103;&#1078;&#1077;&#1085;&#10=
85;&#1086;&#1089;&#1090;&#1100;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>15.&#1076;&#1088;&#1091;&#1075;&#1080;&#1=
077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099; &#1074;
&#1095;&#1072;&#1089;&#1090;&#1080; &#1074;&#1099;&#1087;&#1083;&#1072;&#10=
90;
&#1087;&#1086; &#1080;&#10')

insert #F2 (File_ID, Orders, Body) values(115,9, '90;&#1086;&#1075;&#1072;&#1084; &#1088;&#1072;&#1=
073;&#1086;&#1090;&#1099;<span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>031</b>'' -- &#1077;&#1076;&#1080;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1074;&#1086;&#1079;&#1085;&#1072;&#1075;&#1088;&#1072;&#1078;&#1076;&#107=
7;&#1085;&#1080;&#1077;
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&laquo;&#1054;&#1090;&#1076;&#1077;&#1083;&#1100;&#1085;&#1099;&#1077;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#107=
7;&#1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099; &#1089;
&#1045;&#1076;&#1080;&#1085;&#1099;&#1084;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1099;&#1084;
&#1074;&#1086;&#1079;&#1085;&#1072;&#1075;&#1088;&#1072;&#1078;&#1076;&#107=
7;&#1085;&#1080;&#1077;&#1084;
&#1080;&#1083;&#1080; &#1086;&#1089;&#1086;&#1073;&#1099;&#1084;
&#1087;&#1086;&#1088;&#1103;&#1076;&#1082;&#1086;&#1084;
&#1086;&#1087;&#1083;&#1072;&#1090;&#1099;
&#1090;&#1088;&#1091;&#1076;&#1072;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077; &#1088;&#1072;&#1074;&#=
1085;&#1086;&#1084;&#1091;
&laquo;212&raquo; &#1087;&#1086;
&#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#1084; &#1089;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>1.&#1076;&#1086;&#1083;&#1078;&#1085;&#10=
86;&#1089;&#1090;&#1085;&#1086;&#1081;
&#1086;&#1082;&#1083;&#1072;&#1076;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>2.&#1086;&#1082;&#1083;&#1072;&#1076;
&#1079;&#1072; &#1082;&#1083;&#1072;&#1089;&#1089;&#1085;&#1099;&#1081;
&#1095;&#1080;&#1085;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>3.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1074;&#1099;&#1089;&#1083;&#1091;&#1075;&#1091;
&#1083;&#1077;&#1090; &#1085;&#1072;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>4.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1086;&#1089;&#1086;&#1073;&#1099;&#1077;
&#1091;&#1089;&#1083;&#1086;&#1074;&#1080;&#1103;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>5.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1088;&#1072;&#1073;&#1086;&#1090;&#1091; &#1089;&#1086;
&#1089;&#1074;&#1077;&#1076;&#1077;&#1085;&#1080;&#1103;&#1084;&#1080;,
&#1089;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#1103;&#1102;&#1097;&#108=
0;&#1084;&#1080;
<span class=3DSpellE>&#1075;&#1086;&#1089;</span>.
&#1090;&#1072;&#1081;&#1085;&#1091;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>6.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1091;&#1095;&#1077;&#1085;&#1091;&#1102;
&#1089;&#1090;&#1077;&#1087;&#1077;&#1085;<span class=3DGramE>&#1100;(</spa=
n>&#1079;&#1074;&#1072;&#1085;&#1080;&#1077;)</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>7.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1087;&#1086;&#1095;&#1077;&#1090;&#1085;&#1086;&#1077;
&#1079;&#1074;&#1072;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>8.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1089;&#1083;&#1086;&#1078;&#1085;&#1086;&#1089;&#1090;&#11=
00;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>9.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072;
&#1085;&#1072;&#1087;&#1088;&#1103;&#1078;&#1077;&#1085;&#1085;&#1086;&#108=
9;&#1090;&#1100;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>10.&#1085;&#1072;&#1076;&#1073;&#1072;&#1=
074;&#1082;&#1072;
&#1079;&#1072; &#1074;&#1099;&#1089;&#1086;&#1082;&#1080;&#1077;
&#1076;&#1086;&#1089;&#1090;&#1080;&#1078;&#1077;&#1085;&#1080;&#1103; &#10=
74;
&#1090;&#1088;&#1091;&#1076;&#1077; &#1080; &#1089;&#1087;&#1077;&#1094;<sp=
an
class=3DGramE>.&#1088;</span>&#1077;&#1078;&#1080;&#1084;
&#1088;&#1072;&#1073;&#1086;&#1090;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =')

insert #F2 (File_ID, Orders, Body) values(115,10, '3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>032</b>'' -- &#1077;&#1078;&#1077;&#1084;&#1077;&#1089;&#1103;&#1095=
;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077; &#1080;
&#1087;&#1088;&#1077;&#1084;&#1080;&#1080; &#1089;&#1086;&#1073;&#1080;&#10=
88;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &laquo;&#10=
54;&#1090;&#1076;&#1077;&#1083;&#1100;&#1085;&#1099;&#1077;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#107=
7;&#1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099; &#1089;
&#1045;&#1076;&#1080;&#1085;&#1099;&#1084;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1099;&#1084;
&#1074;&#1086;&#1079;&#1085;&#1072;&#1075;&#1088;&#1072;&#1078;&#1076;&#107=
7;&#1085;&#1080;&#1077;&#1084;
&#1080;&#1083;&#1080; &#1086;&#1089;&#1086;&#1073;&#1099;&#1084;
&#1087;&#1086;&#1088;&#1103;&#1076;&#1082;&#1086;&#1084;
&#1086;&#1087;&#1083;&#1072;&#1090;&#1099; &#1090;&#1088;&#1091;&#1076;&#10=
72;&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089; &#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>11.&#1077;&#1078;&#1077;&#1084;&#1077;&#1=
089;&#1103;&#1095;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>12.&#1087;&#1088;&#1077;&#1084;&#1080;&#1=
080;
&#1079;&#1072;
&#1074;&#1099;&#1087;&#1086;&#1083;&#1085;&#1077;&#1085;&#1080;&#1077;
&#1086;&#1089;&#1086;&#1073;&#1086; &#1074;&#1072;&#1078;&#1085;&#1099;&#10=
93;
&#1080; &#1089;&#1083;&#1086;&#1078;&#1085;&#1099;&#1093;
&#1079;&#1072;&#1076;&#1072;&#1085;&#1080;&#1081;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>033</b>'' -- &#1076;&#1088;&#1091;&#1075;&#1080;&#1077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099;<span class=3DGramE> ,</sp=
an>
&#1087;&#1088;&#1077;&#1076;&#1091;&#1089;&#1084;&#1086;&#1090;&#1088;&#107=
7;&#1085;&#1085;&#1099;&#1077;
&#1076;&#1077;&#1081;&#1089;&#1090;&#1074;&#1091;&#1102;&#1097;&#1080;&#108=
4;
&#1079;&#1072;&#1082;&#1086;&#1085;&#1086;&#1076;&#1072;&#1090;&#1077;&#108=
3;&#1100;&#1089;&#1090;&#1074;&#1086;&#1084;
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &laquo;&#10=
54;&#1090;&#1076;&#1077;&#1083;&#1100;&#1085;&#1099;&#1077;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#107=
7;&#1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099; &#1089;
&#1045;&#1076;&#1080;&#1085;&#1099;&#1084;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1099;&#1084;
&#1074;&#1086;&#1079;&#1085;&#1072;&#1075;&#1088;&#1072;&#1078;&#1076;&#107=
7;&#1085;&#1080;&#1077;&#1084;
&#1080;&#1083;&#1080; &#1086;&#1089;&#1086;&#1073;&#1099;&#1084;
&#1087;&#1086;&#1088;&#1103;&#1076;&#1082;&#1086;&#1084;
&#1086;&#1087;&#1083;&#1072;&#1090;&#1099;
&#1090;&#1088;&#1091;&#1076;&#1072;&raquo;, &#1085;&#1072;&#1095;&#1080;&#1=
089;&#1083;&#1077;&#1085;&#1085;&#1099;&#1077;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089; &#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>13.&#1084;&#1072;&#1090;&#1077;&#1088;&#1=
080;&#1072;&#1083;&#1100;&#1085;&#1072;&#1103;
&#1087;&#1086;&#1084;&#1086;&#1097;&#1100;,
&#1074;&#1099;&#1087;&#1083;&#1072;&#1095;&#1080;&#1074;&#1072;&#1077;&#108=
4;&#1072;&#1103;
&#1079;&#1072; &#1089;&#1095;&#1105;&#1090; &#1060;&#1054;&#1058; &#1043;&#=
1057;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>14.&#1077;&#1076;&#1080;&#1085;&#1086;&#1=
074;&#1088;&#1077;&#1084;&#1077;&#1085;&#1085;&#1072;&#1103;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1072; &#1087;&#1088;&#1080;
&#1087;&#1088;&#1077;&#1076;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#107=
7;&#1085;&#1080;&#1080;
&#1077;&#1078;&#1077;&#1075;&#1086;&#1076;&#1085;&#1086;&#1075;&#1086;
&#1086;&#1087;&#1083;&#1072;&#1095;&#1080;&#1074;&#1072;&#1077;&#1084;&#108=
6;&#1075;&#1086;
&#1086;&#1090;&#1087;&#1091;&#1089;&#1082;&#1072;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>15.&#1076;&#1088;&#1091;&#1075;&#1080;&#1=
077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099; &#1074;
&#1095;&#1072;&#1089;&#1090;&#1080; &#1074;&#1099;&#1087;&#1083;&#1072;&#10=
90;
&#1087;&#1086; &#1080;&#1090;&#1086;&#1075;&#1072;&#1084; &#1088;&#1072;&#1=
073;&#1086;&#1090;&#1099;<span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>041</b>'' -- &#1086;&#1082;&#1083;&#1')

insert #F2 (File_ID, Orders, Body) values(115,11, '072;&#1076;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1075;&#1086;
&#1089;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1103; &#10=
89;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &laquo;&#10=
44;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1080;&#1085;&#1086;&#1075;&#1086; &#1074;&#1080;&#1076;&#1072;
&#1092;&#1077;&#1076;&#1077;&#1088;&#1072;&#1083;&#1100;&#1085;&#1086;&#108=
1;
&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#107=
7;&#1085;&#1085;&#1086;&#1081;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;
(&#1074;&#1086;&#1080;&#1085;&#1089;&#1082;&#1080;&#1077;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &#1080;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1087;&#1088;&#1072;&#1074;&#1086;&#1086;&#1093;&#1088;&#1072;&#1085;&#108=
0;&#1090;&#1077;&#1083;&#1100;&#1085;&#1086;&#1081;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;)&raquo;, &#1085;&#1072;&#1095;&#=
1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#1077;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089; &#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>1.&#1076;&#1086;&#1083;&#1078;&#1085;&#10=
86;&#1089;&#1090;&#1085;&#1086;&#1081;
&#1086;&#1082;&#1083;&#1072;&#1076;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>2.&#1086;&#1082;&#1083;&#1072;&#1076;
&#1079;&#1072; &#1082;&#1083;&#1072;&#1089;&#1089;&#1085;&#1099;&#1081;
&#1095;&#1080;&#1085;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>042</b>'' -- &#1076;&#1086;&#1087;&#1086;&#1083;&#1085;&#1080;&#1090=
;&#1077;&#1083;&#1100;&#1085;&#1099;&#1077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099;<span
style=3D''mso-spacerun:yes''>&nbsp; </span>&#1089;&#1086;&#1073;&#1080;&#1088=
;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &laquo;&#10=
44;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1080;&#1085;&#1086;&#1075;&#1086; &#1074;&#1080;&#1076;&#1072;
&#1092;&#1077;&#1076;&#1077;&#1088;&#1072;&#1083;&#1100;&#1085;&#1086;&#108=
1;
&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#107=
7;&#1085;&#1085;&#1086;&#1081;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;
(&#1074;&#1086;&#1080;&#1085;&#1089;&#1082;&#1080;&#1077;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &#1080; &#1=
076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1087;&#1088;&#1072;&#1074;&#1086;&#1086;&#1093;&#1088;&#1072;&#1085;&#108=
0;&#1090;&#1077;&#1083;&#1100;&#1085;&#1086;&#1081;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;)&raquo;, &#1085;&#1072;&#1095;&#=
1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#1077;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089; &#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>3.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1074;&#1099;&#1089;&#1083;&#1091;&#1075;&#1091;
&#1083;&#1077;&#1090; &#1085;&#1072;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>4.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1086;&#1089;&#1086;&#1073;&#1099;&#1077;
&#1091;&#1089;&#1083;&#1086;&#1074;&#1080;&#1103;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>5.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1088;&#1072;&#1073;&#1086;&#1090;&#1091; &#1089;&#1086;
&#1089;&#1074;&#1077;&#1076;&#1077;&#1085;&#1080;&#1103;&#1084;&#1080;,
&#1089;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#1103;&#1102;&#1097;&#108=
0;&#1084;&#1080;
<span class=3DSpellE>&#1075;&#1086;&#1089;</span>.
&#1090;&#1072;&#1081;&#1085;&#1091;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>6.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1091;&#1095;&#1077;&#1085;&#1091;&#1102;
&#1089;&#1090;&#1077;&#1087;&#1077;&#1085;<span class=3DGramE>&#1100;(</spa=
n>&#1079;&#1074;&#1072;&#1085;&#1080;&#1077;)</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>7.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1087;&#1086;&#1095;&#1077;&#1090;&#1085;&#1086;&#1077;
&#1079;&#1074;&#1072;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>8.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#10')

insert #F2 (File_ID, Orders, Body) values(115,12, '72; &#1089;&#1083;&#1086;&#1078;&#1085;&#1086;&#1089;&#1090;&#11=
00;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>9.&#1085;&#1072;&#1076;&#1073;&#1072;&#10=
74;&#1082;&#1072;
&#1079;&#1072; &#1085;&#1072;&#1087;&#1088;&#1103;&#1078;&#1077;&#1085;&#10=
85;&#1086;&#1089;&#1090;&#1100;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>10.&#1085;&#1072;&#1076;&#1073;&#1072;&#1=
074;&#1082;&#1072;
&#1079;&#1072; &#1074;&#1099;&#1089;&#1086;&#1082;&#1080;&#1077;
&#1076;&#1086;&#1089;&#1090;&#1080;&#1078;&#1077;&#1085;&#1080;&#1103; &#10=
74;
&#1090;&#1088;&#1091;&#1076;&#1077; &#1080; &#1089;&#1087;&#1077;&#1094;<sp=
an
class=3DGramE>.&#1088;</span>&#1077;&#1078;&#1080;&#1084;
&#1088;&#1072;&#1073;&#1086;&#1090;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>11.&#1077;&#1078;&#1077;&#1084;&#1077;&#1=
089;&#1103;&#1095;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>12.&#1087;&#1088;&#1077;&#1084;&#1080;&#1=
080;
&#1079;&#1072;
&#1074;&#1099;&#1087;&#1086;&#1083;&#1085;&#1077;&#1085;&#1080;&#1077;
&#1086;&#1089;&#1086;&#1073;&#1086; &#1074;&#1072;&#1078;&#1085;&#1099;&#10=
93;
&#1080; &#1089;&#1083;&#1086;&#1078;&#1085;&#1099;&#1093;
&#1079;&#1072;&#1076;&#1072;&#1085;&#1080;&#1081;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>13.&#1084;&#1072;&#1090;&#1077;&#1088;&#1=
080;&#1072;&#1083;&#1100;&#1085;&#1072;&#1103;
&#1087;&#1086;&#1084;&#1086;&#1097;&#1100;,
&#1074;&#1099;&#1087;&#1083;&#1072;&#1095;&#1080;&#1074;&#1072;&#1077;&#108=
4;&#1072;&#1103;
&#1079;&#1072; &#1089;&#1095;&#1105;&#1090; &#1060;&#1054;&#1058;
&#1043;&#1057;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>14.&#1077;&#1076;&#1080;&#1085;&#1086;&#1=
074;&#1088;&#1077;&#1084;&#1077;&#1085;&#1085;&#1072;&#1103;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1072; &#1087;&#1088;&#1080;
&#1087;&#1088;&#1077;&#1076;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#107=
7;&#1085;&#1080;&#1080;
&#1077;&#1078;&#1077;&#1075;&#1086;&#1076;&#1085;&#1086;&#1075;&#1086;
&#1086;&#1087;&#1083;&#1072;&#1095;&#1080;&#1074;&#1072;&#1077;&#1084;&#108=
6;&#1075;&#1086;
&#1086;&#1090;&#1087;&#1091;&#1089;&#1082;&#1072;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>15.&#1076;&#1088;&#1091;&#1075;&#1080;&#1=
077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099; &#1074;
&#1095;&#1072;&#1089;&#1090;&#1080; &#1074;&#1099;&#1087;&#1083;&#1072;&#10=
90;
&#1087;&#1086; &#1080;&#1090;&#1086;&#1075;&#1072;&#1084; &#1088;&#1072;&#1=
073;&#1086;&#1090;&#1099;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>043</b>'' -- &#1077;&#1078;&#1077;&#1084;&#1077;&#1089;&#1103;&#1095=
;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077; &#1089;&#10=
86;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &laquo;&#10=
44;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1080;&#1085;&#1086;&#1075;&#1086; &#1074;&#1080;&#1076;&#1072;
&#1092;&#1077;&#1076;&#1077;&#1088;&#1072;&#1083;&#1100;&#1085;&#1086;&#108=
1;
&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#107=
7;&#1085;&#1085;&#1086;&#1081;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;
(&#1074;&#1086;&#1080;&#1085;&#1089;&#1082;&#1080;&#1077;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &#1080;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1087;&#1088;&#1072;&#1074;&#1086;&#1086;&#1093;&#1088;&#1072;&#1085;&#108=
0;&#1090;&#1077;&#1083;&#1100;&#1085;&#1086;&#1081;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;)&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089; &#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;: </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span>11.&#1077;&#1078;&#1077;&#1084;&#1077;&#1=
089;&#1103;&#1095;&#1085;&#1086;&#1077;
&#1076;&#1077;&#1085;&#1077;&#1078;&#1085;&#1086;&#1077;
&#1087;&#1086;&#1086;&#1097;&#1088;&#1077;&#1085;&#1080;&#1077;</p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
style=3D''mso-tab-count:1''>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>050</b>'' -- &#1047;&#1072;&#1088;&#1072;&#1073;&#1086;&#1090;&#1085=
;&#1072;&#1103;
&#1087;&#1083;&#1072;&#1090;&#1072; &#1083;&#1080;&#1094;,
&#1079;&#1072;&#1084;&#1077;&#1097;&#1072;&#1102;&#1097;&#1080;&#1093; <span
class=3DGramE>&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#108=
0;,
&#1085;&#1077;
&#1103;&#1074;&#1083;&#1103;&#1102;&#1097;&#1080;&#1077;&#1089;&#1103;
')

insert #F2 (File_ID, Orders, Body) values(115,13, '&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1103;&#1084;&#108=
0;
&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#107=
7;&#1085;&#1085;&#1086;&#1081;
&#1075;&#1088;&#1072;&#1078;&#1076;&#1072;&#1085;&#1089;&#1082;&#1086;&#108=
1;
&#1089;&#1083;&#1091;&#1078;&#1073;&#1099;
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;</spa=
n>
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &#1089;
&laquo;&#1087;&#1091;&#1089;&#1090;&#1099;&#1084;&raquo;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1086;&#1084;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089;&#1086; &#1074;&#1089;&#1077;&#1084;&#1080;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1072;&#1084;&#1080;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;, &#1082;&#1088;&#1086;&#1084;&#1077;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1072;
&laquo;&#1085;&#1077;&#1090;&raquo;. </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><span
class=3DGramE>&#1055;&#1086; &#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D=
 ''<b
style=3D''mso-bidi-font-weight:normal''>060</b>'' -- &#1047;&#1072;&#1088;&#10=
72;&#1073;&#1086;&#1090;&#1085;&#1072;&#1103;
&#1087;&#1083;&#1072;&#1090;&#1072; &#1088;&#1072;&#1073;&#1086;&#1090;&#10=
85;&#1080;&#1082;&#1086;&#1074;
&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#1074;&#107=
7;&#1085;&#1085;&#1086;&#1075;&#1086;
&#1086;&#1088;&#1075;&#1072;&#1085;&#1072;,
&#1087;&#1077;&#1088;&#1077;&#1074;&#1077;&#1076;&#1077;&#1085;&#1085;&#109=
9;&#1093;
&#1085;&#1072; &#1085;&#1086;&#1074;&#1099;&#1077;
&#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1099;
&#1086;&#1087;&#1083;&#1072;&#1090;&#1099; &#1090;&#1088;&#1091;&#1076;&#10=
72;
3) &#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1076;&#1083;&#1103;
&#1090;&#1080;&#1087;&#1072;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080; &laquo;&#10=
44;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1045;&#1076;&#1080;&#1085;&#1086;&#1081;
&#1090;&#1072;&#1088;&#1080;&#1092;&#1085;&#1086;&#1081;
&#1089;&#1077;&#1090;&#1082;&#1080;
&#1088;&#1072;&#1073;&#1086;&#1090;&#1085;&#1080;&#1082;&#1086;&#1074;
&#1073;&#1102;&#1076;&#1078;&#1077;&#1090;&#1085;&#1086;&#1081;
&#1089;&#1092;&#1077;&#1088;&#1099;
(&#1087;&#1077;&#1088;&#1089;&#1086;&#1085;&#1072;&#1083; &#1087;&#1086;
&#1086;&#1073;&#1089;&#1083;&#1091;&#1078;&#1080;&#1074;&#1072;&#1085;&#108=
0;&#1102;
&#1079;&#1076;&#1072;&#1085;&#1080;&#1081;,
&#1074;&#1086;&#1076;&#1080;&#1090;&#1077;&#1083;&#1080; &#1080;
&#1076;&#1088;.)&raquo;,
&#1085;&#1072;&#1095;&#1080;&#1089;&#1083;&#1077;&#1085;&#1085;&#1099;&#107=
7;
&#1087;&#1086; &#1069;&#1050;&#1056; &#1085;&#1077;
&#1088;&#1072;&#1074;&#1085;&#1086;&#1084;&#1091; &laquo;212&raquo;
&#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1094;&#1080;&#1103;&#10=
84;
&#1089;&#1086; &#1074;&#1089;&#1077;&#1084;&#1080;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1072;&#1084;&#1080;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;, &#1082;&#1088;&#1086;&#1084;&#1077;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1072;
&laquo;&#1085;&#1077;&#1090;&raquo;. </span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>080</b>'' -- &#1055;&#1088;&#1086;&#1095;&#1080;&#1077;
&#1074;&#1099;&#1087;&#1083;&#1072;&#1090;&#1099;<span
style=3D''mso-spacerun:yes''>&nbsp;
</span>&#1088;&#1072;&#1073;&#1086;&#1090;&#1085;&#1080;&#1082;&#1072;&#108=
4;<span
style=3D''mso-spacerun:yes''>&nbsp;&nbsp;
</span>&#1075;&#1086;&#1089;&#1091;&#1076;&#1072;&#1088;&#1089;&#1090;&#107=
4;&#1077;&#1085;&#1085;&#1086;&#1075;&#1086;
&#1086;&#1088;&#1075;&#1072;&#1085;&#1072; &#1087;&#1086; 212
&#1069;&#1050;&#1056; &#1087;&#1086; &#1086;&#1087;&#1077;&#1088;&#1072;&#1=
094;&#1080;&#1103;&#1084;
&#1089;&#1086; &#1074;&#1089;&#1077;&#1084;&#1080;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1072;&#1084;&#1080;
&laquo;&#1055;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082; &#1076;&#1083;&#11=
03;
14-&#1073;&#1102;&#1076;&#1078;.&raquo;, &#1082;&#1088;&#1086;&#1084;&#1077;
&#1087;&#1088;&#1080;&#1079;&#1085;&#1072;&#1082;&#1072;
&laquo;&#1085;&#1077;&#1090;&raquo; &#1087;&#1083;&#1102;&#1089;
&#1089;&#1091;&#1084;&#1084;&#1099; &#1087;&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1072;&#1084; ''<b style=3D''mso-bidi-fon=
t-weight:
normal''>081</b>'' + ''<b style=3D''mso-bidi-font-weight:normal''>082</b>''. </p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>081</b>'' &#8211; &#1089;&#1091;&#1084;&#1084;&#1072; &#1087;&#1086;
&#1087;&#1088;&#1086;&#1074;&#1086;&#1076;&#1082;&#1072;&#1084;:</p>

<p class=3DMsoNormal style=3D''text-indent:18.0pt;mso-layout-grid-align:none;
text-autospace:none''><span style=3D''font-size:10.0pt;font-family:"Courier N=
ew";
color:red;mso-no-proof:yes''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:35.4pt;mso-layout-grid-align:none;
text-autospace:none''>&#1044;&#1090;.<span style=3D''font-size:10.0pt;font-fa=
mily:
"Courier New";color:red;mso-no-proof:yes''>''2.106.04''</span>, &#1050;&#1090;=
.<span
style=3D''font-size:10.0pt;font-family:"Courier New";color:red;mso-no-proof:=
yes''>''2.302.02''<o:p></o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:35.4pt;mso-layout-grid-align:none;
text-autospace:none''>&#1044;&#1090;.<span style=3D''font-size:10.0pt;font-fa=
mily:
"Courier New";color:red;mso-no-proof:yes''>''106.14,106.24,106.34,106.44''</sp=
an>,
&#1050;&#1090;.<span style=3D''font-size:10.0pt;font-family:"Courier New";
color:red;mso-no-proof:yes''>''1.302.12''</span><span style=3D''font-size:10.0p=
t;
font-family:"Courier New";color:gray;mso-no-proof:yes''><o:p></o:p></span></=
p>

<p class=3DMsoNormal style=3D''text-indent:35.4pt;mso-layout-grid-align:none;
text-autospace:none''>&#1044;&#1090;.<span style=3D''font-size:10.0pt;font-fa=
mily:
"Courier New";color:red;mso-no-proof:yes''>''401.01,401.20''</span>, &#1050;&#=
1090;.<span
style=3D''font-size:10.0pt;font-family:"Courier New";color:red;mso-no-proof:=
yes''>''302.07,302.09,302.06,302.25,302.26,302.34''<o:p></o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:35.4pt;mso-layout-grid-align:none;
text-autospace:none''><span style=3D''font-size:10.0pt;font-family')

insert #F2 (File_ID, Orders, Body) values(115,14, ':"Courier N=
ew";
color:gray;mso-no-proof:yes''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>083</b>'' &#8211; &#1089;&#1091;&#1084;&#1084;&#1072; &#1087;&#1086;
&#1087;&#1088;&#1086;&#1074;&#1086;&#1076;&#1082;&#1072;&#1084;:</p>

<p class=3DMsoNormal style=3D''text-indent:35.4pt;mso-layout-grid-align:none;
text-autospace:none''><span style=3D''font-size:10.0pt;font-family:"Courier N=
ew";
color:gray;mso-no-proof:yes''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:35.4pt;mso-layout-grid-align:none;
text-autospace:none''>&#1044;&#1090;.<span style=3D''font-size:10.0pt;font-fa=
mily:
"Courier New";color:red;mso-no-proof:yes''>''208.02,208.12''</span>, &#1050;&#=
1090;.<span
style=3D''font-size:10.0pt;font-family:"Courier New";color:red;mso-no-proof:=
yes''>''201.04,201.34,304.05,201.01,201.11,201.21''</span><span
style=3D''font-size:10.0pt;font-family:"Courier New";color:gray;mso-no-proof=
:yes''><o:p></o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:35.4pt;mso-layout-grid-align:none;
text-autospace:none''>&#1047;&#1072;
&#1084;&#1080;&#1085;&#1091;&#1089;&#1086;&#1084;: &#1044;&#1090;.<span
style=3D''font-size:10.0pt;font-family:"Courier New";color:red;mso-no-proof:=
yes''>''201.34,201.04''</span>,
&#1050;&#1090;.<span style=3D''font-size:10.0pt;font-family:"Courier New";
color:red;mso-no-proof:yes''>''208.02,208.12''<o:p></o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:35.4pt;mso-layout-grid-align:none;
text-autospace:none''><span style=3D''font-size:10.0pt;font-family:"Courier N=
ew";
color:gray;mso-no-proof:yes''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>092</b>'' &#8211; &#1089;&#1091;&#1084;&#1084;&#1072; &#1087;&#1086;
&#1087;&#1088;&#1086;&#1074;&#1086;&#1076;&#1082;&#1072;&#1084;:</p>

<p class=3DMsoNormal style=3D''mso-layout-grid-align:none;text-autospace:non=
e''><span
style=3D''font-size:10.0pt;font-family:"Courier New";color:red;mso-no-proof:=
yes''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:18.0pt;mso-layout-grid-align:none;
text-autospace:none''>&#1044;&#1090;.<span style=3D''font-size:10.0pt;font-fa=
mily:
"Courier New";color:red;mso-no-proof:yes''>''208.05,208.09,208.22,208.26''</sp=
an>,
&#1050;&#1090;.<span style=3D''font-size:10.0pt;font-family:"Courier New";
color:red;mso-no-proof:yes''>''201.04,201.34,304.05,201.01,201.11,201.21''<o:p=
></o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:18.0pt;mso-layout-grid-align:none;
text-autospace:none''>&#1047;&#1072; &#1084;&#1080;&#1085;&#1091;&#1089;&#10=
86;&#1084;:
&#1044;&#1090;.<span style=3D''font-size:10.0pt;font-family:"Courier New";
color:red;mso-no-proof:yes''>''201.34,201.04''</span>, &#1050;&#1090;.<span
style=3D''font-size:10.0pt;font-family:"Courier New";color:red;mso-no-proof:=
yes''>''208.05,208.09,208.22,208.26''<o:p></o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:18.0pt;mso-layout-grid-align:none;
text-autospace:none''><span style=3D''font-size:10.0pt;font-family:"Courier N=
ew";
color:gray;mso-no-proof:yes''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>094</b>'' &#8211; &#1089;&#1091;&#1084;&#1084;&#1072; &#1087;&#1086;
&#1087;&#1088;&#1086;&#1074;&#1086;&#1076;&#1082;&#1072;&#1084;:</p>

<p class=3DMsoNormal style=3D''text-indent:18.0pt;mso-layout-grid-align:none;
text-autospace:none''><span style=3D''font-size:10.0pt;font-family:"Courier N=
ew";
color:gray;mso-no-proof:yes''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''text-indent:18.0pt;mso-layout-grid-align:none;
text-autospace:none''>&#1044;&#1090;.<span style=3D''font-size:10.0pt;font-fa=
mily:
"Courier New";color:red;mso-no-proof:yes''>''401.01,401.20''</span>, &#1050;&#=
1090;.<span
style=3D''font-size:10.0pt;font-family:"Courier New";color:red;mso-no-proof:=
yes''>''105.03,105.23,105.33,104.05,104.15,104.25,104.35,104.45''</span><span
style=3D''font-size:10.0pt;font-family:"Courier New";mso-no-proof:yes''> <span
style=3D''color:gray''><o:p></o:p></span></span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1086;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1077; =3D ''<b style=3D''mso-bidi-font-w=
eight:
normal''>450</b>''<span style=3D''mso-spacerun:yes''>&nbsp; </span>-
&#1082;&#1086;&#1083;&#1080;&#1095;&#1077;&#1089;&#1090;&#1074;&#1086;,
&#1082;&#1072;&#1082; &#1086;&#1089;&#1090;&#1072;&#1090;&#1086;&#1082;
&#1087;&#1086; &#1089;&#1095;&#1105;&#1090;&#1091;: <span style=3D''font-siz=
e:
10.0pt;font-family:"Courier New";color:red;mso-no-proof:yes''>''101.05,101.15=
,101.25,101.35,101.15''</span></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''><o:p>&n=
bsp;</o:p></p>

<p class=3DMsoNormal style=3D''margin-left:18.0pt;tab-stops:95.65pt''>&#1055;=
&#1088;&#1086;&#1095;&#1080;&#1077;
&#1089;&#1090;&#1088;&#1086;&#1082;&#1080;
&#1089;&#1086;&#1073;&#1080;&#1088;&#1072;&#1102;&#1090;&#1089;&#1103; &#10=
74;
&#1089;&#1086;&#1086;&#1090;&#1074;&#1077;&#1090;&#1089;&#1090;&#1074;&#108=
0;&#1077;
&#1089;<span style=3D''mso-spacerun:yes''>&nbsp;
</span>&#1091;&#1089;&#1090;&#1072;&#1085;&#1086;&#1074;&#1083;&#1077;&#108=
5;&#1085;&#1099;&#1084;&#1080;
&#1088;&#1077;&#1082;&#1074;&#1080;&#1079;&#1080;&#1090;&#1072;&#1084;&#108=
0;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;
&#1096;&#1090;&#1072;&#1090;&#1085;&#1086;&#1075;&#1086;
&#1088;&#1072;&#1089;&#1087;&#1080;&#1089;&#1072;&#1085;&#1080;&#1103;
&#1085;&#1072; &#1082;&#1086;&#1085;&#1077;&#1094; &#1086;&#1090;&#1095;&#1=
105;&#1090;&#1085;&#1086;&#1075;&#1086;
&#1087;&#1077;&#1088;&#1080;&#1086;&#1076;&#1072;: &laquo;&#1058;&#1080;&#1=
087;
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;&raquo;,
&laquo;&#1050;&#1072;&#1090;&#1077;&#1075;&#1086;&#1088;&#1080;&#1103; <span
class=3DSpellE>&#1075;&#1086;&#1089;</span>.
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;&raquo; &#10=
80;
&laquo;&#1043;&#1088;&#1091;&#1087;&#1087;&#1072; <span class=3DSpellE>&#10=
75;&#1086;&#1089;</span>.
&#1076;&#1086;&#1083;&#1078;&#1085;&#1086;&#1089;&#1090;&#1080;&raquo;.</p>

<p class=3DMsoNormal><o:p>&nbsp;</o:p></p>

</div>

</body>

</html>

------=_NextPart_01CBD26A.F54A6190
Content-Location: file:///C:/90708BCB/file4923.files/themedata.thmx
Content-Transfer-Encoding: base64
Content-Type: application/vnd.ms-officetheme

UEsDBBQABgAIAAAAIQCCirwT+gAAABwCAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbKyRy2rDMBBF
94X+g9C22HK6KKXYzqJJd30s0g8Y5LEtao+ENAnJ33fsuFC6CC10IxBizpl7Va6P46AOGJPzVOlV
XmiFZH3jqKv0++4pu9cqMVADgyes9AmTXtfXV+XuFDApmaZU6Z45PBiTbI8jpNwHJHlpfRyB5Ro7
E8B+QIfmtijujPXESJzxxNB1+SoLRNegeoPILzCKx7Cg8Pv5DCSAmAtYq8czYVqi0hDC4CywRDAH
an7oM9+2zmLj7X4UaT6DF9jNBDO/XGD1P+ov5wZb2A+stkfp4lx/xCH9LdtSay6Tc/7Uu5AuGC6X
t7Rh5r+tPwEAAP//AwBQSwMEFAAGAAgAAAAhA')

insert #F2 (File_ID, Orders, Body) values(115,15, 'KXWp+fAAAAANgEAAAsAAABfcmVscy8ucmVsc4SP
z2rDMAyH74W9g9F9UdLDGCV2L6WQQy+jfQDhKH9oIhvbG+vbT8cGCrsIhKTv96k9/q6L+eGU5yAW
mqoGw+JDP8to4XY9v3+CyYWkpyUIW3hwhqN727VfvFDRozzNMRulSLYwlRIPiNlPvFKuQmTRyRDS
SkXbNGIkf6eRcV/XH5ieGeA2TNP1FlLXN2Cuj6jJ/7PDMMyeT8F/ryzlRQRuN5RMaeRioagv41O9
kKhlqtQe0LW4+db9AQAA//8DAFBLAwQUAAYACAAAACEAa3mWFoMAAACKAAAAHAAAAHRoZW1lL3Ro
ZW1lL3RoZW1lTWFuYWdlci54bWwMzE0KwyAQQOF9oXeQ2TdjuyhFYrLLrrv2AEOcGkHHoNKf29fl
44M3zt8U1ZtLDVksnAcNimXNLoi38Hwspxuo2kgcxSxs4ccV5ul4GMm0jRPfSchzUX0j1ZCFrbXd
INa1K9Uh7yzdXrkkaj2LR1fo0/cp4kXrKyYKAjj9AQAA//8DAFBLAwQUAAYACAAAACEAoLwYxrUG
AACDGwAAFgAAAHRoZW1lL3RoZW1lL3RoZW1lMS54bWzsWc9uG0UYvyPxDqO9t7ETO42jOFXs2A20
aaPYLepxvB7vTjO7s5oZJ/WtSo9IIERBHKgEXDggIFKLuLTv4D5DoAiK1Ffgm5ldeyfekKSNoILm
EHtnf9//P/PNeOXy3YihXSIk5XHdK18seYjEPu/TOKh7N7vtC0sekgrHfcx4TOreiEjv8uq776zg
ZRWSiCCgj+UyrnuhUsny3Jz0YRnLizwhMbwbcBFhBY8imOsLvAd8IzY3XyotzkWYxh6KcQRsx9+M
fxo/GR+gG4MB9Ym3mvFvMRASK6kXfCY6mjvJiL5+tj8+GD8dPx4fPLsH35/C58eGtr9T1hRyJJtM
oF3M6h6I7vO9LrmrPMSwVPCi7pXMnze3ujKHl1Mipo6hzdG1zV9KlxL0d+aNTBH0JkLL7Urt0vqE
vwEwNYtrtVrNVnnCzwCw74PlVpc8z0p7qdzIeOZA9uss72apWqq4+Bz/hRmda41Go1pLdbFMDch+
rczgl0qLlbV5B29AFl+dwVcaa83mooM3IItfnMG3L9UWKy7egEJG450ZtA5ou51yn0AGnG0UwpcA
vlRK4VMUZMMk27SIAY/VaXMvwne4aAOBJmRY0RipUUIG2IdEb+KoJyjWAvEywbk3dsmXM0taNpK+
oImqe+8nGIpmyu/lk+9fPnmEDvcfH+7/fHj//uH+j5aRQ7WB4yBP9eLbT/58eA/98eirFw8+K8bL
PP7XHz785emnxUAop6k6zz8/+O3xwfMvPvr9uwcF8DWBe3l4l0ZEoutkD23zCAwzXnE1Jz1xNopu
iGmeYi0OJI6xllLAv6VCB319hFkaHUePBnE9eEtAOykCXhnecRTuhGKoaIHkq2HkADc5Zw0uCr1w
VcvKubk7jINi4WKYx21jvFsku4ljJ76tYQJ9NUtLx/BmSBw1txiOFQ5ITBTS7/gOIQXW3abU8esm
9QWXfKDQbYoamBa6pEt7TjZNiTZoBHEZFdkM8XZ8s3kLNTgrsnqd7LpIqArMCpTvEua48QoeKhwV
seziiOUdfg2rsEjJzkj4eVxLKoh0QBhHrT6RsojmhgB7c0G/iqGDFYZ9k40iFykU3SnieQ1znkeu
851miKOkCNuhcZjHvid3IEUx2uKqCL7J3QrRzxAHHB8b7luUOOE+uRvcpIGj0jRB9Juh0LGE1u10
4IjGf9eOGYV+bHPg/NoxNMDnXz4syKw3tRGvwZ5UVAkbR9rvcbijTbfJRZ+++T13HQ/jLQJpPrvx
vG25b1uu959vucfV82kb7bS3QtvVc4Mdks3IHJ16Yh5QxjpqxMg1aYZmCftGvw2Lmo85UJLJiSoJ
4Wva5x1cILChQYKrD6gKOyFOYOAue5pJIFPWgUQJl3DwM8uFvDUehnZlj41VfaCw/UFitcn7dnlB
L2fnhgkbs/sE5rCaCVrQDE4rbOFSyhTMfhVhZa3UqaWVjWqm9TnSJiZDTGdNg8WJN2EgQTDGgJcX
4UivRcNBBTPS1363e3EWFhOF8wyRDHGfpDHSds/GqGyClOWKuTmA3CmIkT4EnuC1nLSaZvsa0k4T
pLy4yjHisui9TpSyDJ5GSdfxkXJkcb44WYz26l6tOl/1kI+TujeAMy58jRKIutQzIGYB3CX5Sti0
P7GYTZVPo1nLDHOLoAzXGNbvMwY7fSARUq1jGdrUMK/SFGCxlmT1n6+CW8/LAJvpr6DFwhIkw7+m
BfjRDS0ZDIiv8sHOrWjf2ce0lfKhIqIT9vdQjw3FNobw61QFe/pUwlWF6Qj6Ae7ZtLfNK7c5p0WX
v90yOLuOWRLitN3qEs0q2cJNHU90ME859cC2Qt2NcWc3xZT8OZmST+P/mSl6P4Gbg4W+joAPN78C
I12vdY8LFXLoQklI/baAQcL0DsgWuKuF15BUcP9sPgXZ1Z+25iwPU9ZwAFTbNECCwn6kQkHIFrQl
k30nMCune5dlyVJGJqNy6srEqt0ju4R1dQ9c1Hu7h0JIddNN0jZgcEfzz31OK6gX6CEnX29OD5ns
vbYG/unJxxYzGOX2YTPQZP6fqFiwq1p6Q57tvXlD9IvpmFXJqgKE5baCWlr2r6jCGbda27FmLJ6v
ZspBFGcthsXJQJTA/Q/S/2D/o8Jn9pcMvaF2+Tb0VgQ/RGhmkDaQ1Rfs4IF0g7SLPRic7KJNJs3K
ujYdnbTXss36nCfdidwjztaanSbeZ3T2ZDhzxTm1eJ7OTj3s+NquHetqiOzREoWlQXawMYExv4Ll
f6XivTsQ6HW47x8yJU0ywW9OAsPo2TF1AMVvJRrS1b8AAAD//wMAUEsDBBQABgAIAAAAIQAN0ZCf
tgAAABsBAAAnAAAAdGhlbWUvdGhlbWUvX3JlbHMvdGhlbWVNYW5hZ2VyLnhtbC5yZWxzhI9NCsIw
FIT3gncIb2/TuhCRJt2I0K3UA4TkNQ02PyRR7O0NriwILodhvplpu5edyRNjMt4xaKoaCDrplXGa
wW247I5AUhZOidk7ZLBggo5vN+0VZ5FLKE0mJFIoLjGYcg4nSpOc0IpU+YCuOKOPVuQio6ZByLvQ
SPd1faDxmwF8xSS9YhB71QAZllCa/7P9OBqJZy8fFl3+UUFz2YUFKKLGzOAjm6pMBMpburrE3wAA
AP//AwBQSwECLQAUAAYACAAAACEAgoq8E/oAAAAcAgAAEwAAAAAAAAAAAAAAAAAAAAAAW0NvbnRl
bnRfVHlwZXNdLnhtbFBLAQItABQABgAIAAAAIQCl1qfnwAAAADYBAAALAAAAAAAAAAAAAAAAACsB
AABfcmVscy8ucmVsc1BLAQItABQABgAIAAAAIQBreZYWgwAAAIoAAAAcAAAAAAAAAAAAAAAAABQC
AAB0aGVtZS90aGVtZS90aGVtZU1hbmFnZXIueG1sUEsBAi0AFAAGAAgAAAAhAKC8GMa1BgAAgxsA
ABYAAAAAAAAAAAAAAAAA0QIAAHRoZW1lL3RoZW1lL3RoZW1lMS54bWxQSwECLQAUAAYACAAAACEA
DdGQn7YAAAAbAQAAJwAAAAAAAAAAAAAAAAC6CQAAdGhlbWUvdGhlbWUvX3JlbHMvdGhlbWVNYW5h
Z2VyLnhtbC5yZWxzUEsFBgAAAAAFAAUAXQEAALUKAAAAAA==

------=_NextPart_01CBD26A.F54A6190
Content-Location: file:///C:/90708BCB/file4923.files/colorschememapping.xml
Content-Transfer-Encoding: quoted-printable
Content-Type: text/xml

<?xml version=3D"1.0" encoding=3D"UTF-8" standalone=3D"yes"?>
<a:clrMap xmlns:a=3D"http://schemas.openxmlformats.org/drawingml/2006/main"=
 bg1=3D"lt1" tx1=3D"dk1" bg2=3D"lt2" tx2=3D"dk2" accent1=3D"accent1" accent=
2=3D"accent2" accent3=3D"accent3" accent4=3D"accent4" accent5=3D"accent5" a=
ccent6=3D"accent6" hlink=3D"hlink" folHlink=3D"folHlink"/>
------=_NextPart_01CBD26A.F54A6190
Content-Location: file:///C:/90708BCB/file4923.files/filelist.xml
Content-Transfer-Encoding: quoted-printable
Content-Type: text/xml; charset="utf-8"

<xml xmlns:o=3D"urn:schemas-microsoft-com:office:office">
 <o:MainFile HRef=3D"../file4923.htm"/>
 <o:File HRef=3D"themedata.thmx"/>
 <o:File HRef=3D"colorschememapping.xml"/>
 <o:File HRef=3D"filelist.xml"/>
</xml>
------=_NextPart_01CBD26A.F54A6190--
')

IF (SELECT COUNT(*) FROM #F2) <> 15
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F2',0)
END
ELSE
	exec dbo.RO_IMPORT_FORM_HINT @iLINK_FORM
drop table #F1
drop table #F2


GO

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL DROP TABLE #tabInfo
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog
DROP TABLE #tabStop

COMMIT TRANSACTION -- Фиксация транзакции.
GO


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (июл  3 2014 11:51:41:937AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0503074 (Отчет о расходах и числ работников гос. органов субъектов РФ (квартальная))
-- Дата ввода : 20110101
-- Дата окончания действия :
-- Версия : 2014-07-03 11:51:41.937
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = '0503074' AND [START_DATE] = '20110101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-07-03 11:51:41.937',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '0503074',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '0503074'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20110101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SMETA'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Отчет о расходах и числ работников гос. органов субъектов РФ (квартальная)',@vcNEW_FORM_CODE,@dNEW_START_DATE,2,1,1,1,18186,'RA_EXPORT_FORM_0503074#RA_IMPORT_FORM_0503074',0,0,'19000101',NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'svodprint_14_ask()','Sv_0503074G_20101231.bas','','KirRepMakerMultiSheet.xls','Sv_0503074G_20101231.xlt','',NULL,'RA_EXPORT_FORM_0503074#RA_IMPORT_FORM_0503074',0,NULL,NULL,'FORM14_EDIT#26#1','014       ','',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Таблица', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Утверждено',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Фактически',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Таблица', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Численность', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Утверждено',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Фактически',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Среднесписочная численность',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Численность', @iLINK_FORM,2, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Справка1', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Фактически',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Справка1', @iLINK_FORM,3, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Справка2', @iLINK_FORM,4
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,100,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'На отчетную дату',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В среднем',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Справка2', @iLINK_FORM,4, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (3,1,1,1)
INSERT #R VALUES (2,1,0,1)
INSERT #R VALUES (4,1,1,1)
INSERT #R VALUES (5,1,1,1)
INSERT #R VALUES (6,1,1,1)
INSERT #R VALUES (7,1,1,1)
INSERT #R VALUES (8,1,1,1)
INSERT #R VALUES (9,1,1,1)
INSERT #R VALUES (10,1,1,1)
INSERT #R VALUES (11,1,1,1)
INSERT #R VALUES (12,1,1,1)
INSERT #R VALUES (13,1,1,1)
INSERT #R VALUES (14,1,1,1)
INSERT #R VALUES (15,1,1,1)
INSERT #R VALUES (16,1,1,1)
INSERT #R VALUES (17,1,1,1)
INSERT #R VALUES (18,1,1,1)
INSERT #R VALUES (19,1,1,1)
INSERT #R VALUES (20,1,1,1)
INSERT #R VALUES (21,1,1,1)
INSERT #R VALUES (22,1,2,1)
INSERT #R VALUES (23,1,1,1)
INSERT #R VALUES (24,1,1,1)
INSERT #R VALUES (25,1,1,1)
INSERT #R VALUES (26,1,1,1)
INSERT #R VALUES (27,1,1,1)
INSERT #R VALUES (28,1,1,1)
INSERT #R VALUES (29,1,1,1)
INSERT #R VALUES (30,1,1,1)
INSERT #R VALUES (31,1,1,1)
INSERT #R VALUES (32,1,1,1)
INSERT #R VALUES (33,1,3,1)
INSERT #R VALUES (1,2,1,1)
INSERT #R VALUES (2,2,1,1)
INSERT #R VALUES (3,2,1,1)
INSERT #R VALUES (4,2,2,1)
INSERT #R VALUES (5,2,1,1)
INSERT #R VALUES (6,2,1,1)
INSERT #R VALUES (7,2,1,1)
INSERT #R VALUES (8,2,1,1)
INSERT #R VALUES (9,2,1,1)
INSERT #R VALUES (10,2,1,1)
INSERT #R VALUES (11,2,1,1)
INSERT #R VALUES (12,2,1,1)
INSERT #R VALUES (13,2,1,1)
INSERT #R VALUES (14,2,1,1)
INSERT #R VALUES (15,2,1,1)
INSERT #R VALUES (16,2,1,1)
INSERT #R VALUES (17,2,1,1)
INSERT #R VALUES (18,2,1,1)
INSERT #R VALUES (19,2,1,1)
INSERT #R VALUES (20,2,1,1)
INSERT #R VALUES (21,2,1,1)
INSERT #R VALUES (22,2,1,1)
INSERT #R VALUES (23,2,1,1)
INSERT #R VALUES (24,2,1,1)
INSERT #R VALUES (25,2,1,1)
INSERT #R VALUES (26,2,3,1)
INSERT #R VALUES (1,3,1,1)
INSERT #R VALUES (2,3,20,1)
INSERT #R VALUES (3,3,5,1)
INSERT #R VALUES (4,3,2,1)
INSERT #R VALUES (5,3,3,1)
INSERT #R VALUES (6,3,4,1)
INSERT #R VALUES (7,3,9,1)
INSERT #R VALUES (8,3,6,1)
INSERT #R VALUES (9,3,7,1)
INSERT #R VALUES (10,3,8,1)
INSERT #R VALUES (11,3,14,1)
INSERT #R VALUES (12,3,10,1)
INSERT #R VALUES (13,3,11,1)
INSERT #R VALUES (14,3,12,1)
INSERT #R VALUES (15,3,13,1)
INSERT #R VALUES (16,3,19,1)
INSERT #R VALUES (17,3,15,1)
INSERT #R VALUES (18,3,16,1)
INSERT #R VALUES (19,3,17,1)
INSERT #R VALUES (20,3,18,1)
INSERT #R VALUES (1,4,1,1)
INSERT #R VALUES (2,4,2,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 80
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,2,1,'Заработная плата лиц, замещающих государственные должности, всего  (сумма строк 011+012+013)                                                                                                                                                              ')
INSERT #F VALUES (1,3,1,'в т.ч.:денежное вознаграждение (денежное содержание, заработная плата судей)                                                                                                                                                                              ')
INSERT #F VALUES (1,4,1,'ежемесячное (ежеквартальное) денежное поощрение                                                                                                                                                                                                           ')
INSERT #F VALUES (1,5,1,'другие выплаты , предусмотренные действующим законодательством                                                                                                                                                                                            ')
INSERT #F VALUES (1,6,1,'Заработная плата  лиц, замещающих должности государственной гражданской службы, всего (сумма строк 021+023+025)                                                                                                                                           ')
INSERT #F VALUES (1,7,1,'в т.ч.:оклад денежного содержания                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,8,1,'из него  оклад по занимаемой должности                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,9,1,'дополнительные выплаты                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,10,1,'из них:  ежемесячное денежное поощрение                                                                                                                                                                                                                   ')
INSERT #F VALUES (1,11,1,'другие выплаты , предусмотренные действующим законодательством                                                                                                                                                                                            ')
INSERT #F VALUES (1,12,1,'Заработная плата лиц, замещающих отдельные должности государственной гражданской службы, 1) всего                               (сумма строк 031+032+033)                                                                                                 ')
INSERT #F VALUES (1,13,1,'в том числе: единое денежное вознаграждение                                                                                                                                                                                                               ')
INSERT #F VALUES (1,14,1,'ежемесячное денежное поощрение и премии                                                                                                                                                                                                                   ')
INSERT #F VALUES (1,15,1,'другие выплаты , предусмотренные действующим законодательством                                                                                                                                                                                            ')
INSERT #F VALUES (1,16,1,'Заработная плата лиц, замещающих  должности  иного вида федеральной государственной службы, 2) всего                     (сумма строк 041+042)                                                                                                            ')
INSERT #F VALUES (1,17,1,'в том числе: оклад денежного содержания                                                                                                                                                                                                                   ')
INSERT #F VALUES (1,18,1,'дополнительные выплаты                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,19,1,'из них ежемесячное денежное поощрение                                                                                                                                                                                                                     ')
INSERT #F VALUES (1,20,1,'Заработная плата лиц, замещающих должности, не являющиеся должностями государственной гражданской службы                                                                                                                                                  ')
INSERT #F VALUES (1,21,1,'Заработная плата работников государственного органа, переведенных на новые системы оплаты труда 3)                                                                                                                                                        ')
INSERT #F VALUES (1,22,1,'Итого расходов на заработную плату работников государственного органа (сумма строк 010+020+030+040+050+060)                                                                                                                                               ')
INSERT #F VALUES (1,23,1,'Прочие выплаты  работникам   государственного органа                                                                                                                                                                                                      ')
INSERT #F VALUES (1,24,1,'из них: компенсации работникам за использование личных легковых автомобилей для служебных целей                                                                                                                                                           ')
INSERT #F VALUES (1,25,1,'суточные при служебных командировках - всего  (сумма строк 083+084)                                                                                                                                                                                       ')
INSERT #F VALUES (1,26,1,'в том числе: на территории Российской Федерации                                                                                                                                                                                                           ')
INSERT #F VALUES (1,27,1,'на территории иностранных государств                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,28,1,'Другие расходы  на содержание   государственного органа                                                                                                                                                                                                   ')
INSERT #F VALUES (1,29,1,'в том числе: на служебные командировки (оплата проезда и проживания) - всего (сумма строк 092+093)                                                                                                                                                        ')
INSERT #F VALUES (1,30,1,'из них: на территории Российской Федерации                                                                                                                                                                                                                ')
INSERT #F VALUES (1,31,1,'на территории иностранных государств                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,32,1,'на содержание служебных легковых автомобилей                                                                                                                                                                                                              ')
INSERT #F VALUES (1,33,1,'Итого расходов  на содержание  государственного органа (сумма строк 070+080+090)                                                                                                                                                                          ')
INSERT #F VALUES (1,2,2,'010                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,3,2,'011                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,4,2,'012                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,5,2,'013                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,6,2,'020                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,7,2,'021                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,8,2,'022                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,9,2,'023                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,10,2,'024                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,11,2,'025                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,12,2,'030                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,13,2,'031                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,14,2,'032                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,15,2,'033                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,16,2,'040                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,17,2,'041                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,18,2,'042                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,19,2,'043                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,20,2,'050                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,21,2,'060                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,22,2,'070                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,23,2,'080                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,24,2,'081                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,25,2,'082                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,26,2,'083                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,27,2,'084                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,28,2,'090                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,29,2,'091                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,30,2,'092                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,31,2,'093                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,32,2,'094                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,33,2,'100                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,3,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,4,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,7,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,8,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,9,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,11,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,12,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,13,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,14,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,15,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,17,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,18,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,19,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,20,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,21,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,24,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,25,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,26,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,27,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,29,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,30,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,31,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,32,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,33,3,'ИТОГ_Ф14("070+080+090")')
INSERT #F VALUES (1,2,4,'14_УСТАНОВКА()+14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,3,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,4,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,6,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,8,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,9,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,10,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,11,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,12,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,13,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,14,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,15,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,17,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,18,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,19,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,20,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,21,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,22,4,'ИТОГ_Ф14("010+020+030+040+050+060")')
INSERT #F VALUES (1,23,4,'14_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,24,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,25,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,26,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,27,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,28,4,'14_ФАКТ_РАСХОД(К.СТР.) ')
INSERT #F VALUES (1,29,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,30,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,31,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,32,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,33,4,'ИТОГ_Ф14("070+080+090")')
INSERT #F VALUES (2,1,1,'Государственные  должности                                                                                                                                                                                                                                ')
INSERT #F VALUES (2,2,1,'Должности государственной гражданской службы                                                                                                                                                                                                              ')
INSERT #F VALUES (2,3,1,'Отдельные должности государственной гражданской   службы 2)                                                                                                                                                                                               ')
INSERT #F VALUES (2,4,1,'Итого  должностей государственной гражданской службы (сумма строк 210+220)                                                                                                                                                                                ')
INSERT #F VALUES (2,5,1,'в том числе по категориям: руководители  (сумма строк 241+242+243)                                                                                                                                                                                        ')
INSERT #F VALUES (2,6,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (2,7,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,8,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,9,1,'помощники (советники) (сумма строк 251+252+253)                                                                                                                                                                                                           ')
INSERT #F VALUES (2,10,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (2,11,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,12,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,13,1,'специалисты  (сумма строк 261+262+263+264)                                                                                                                                                                                                                ')
INSERT #F VALUES (2,14,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (2,15,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,16,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,17,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,18,1,'Обеспечивающие специалисты (сумма строк 271+272+273+274)                                                                                                                                                                                                  ')
INSERT #F VALUES (2,19,1,'из них по группам: главные                                                                                                                                                                                                                                ')
INSERT #F VALUES (2,20,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,21,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,22,1,'младшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,23,1,'Должности иного вида федеральной государственной службы 3)                                                                                                                                                                                                ')
INSERT #F VALUES (2,24,1,'Должности, не являющиеся должностями государственной гражданской службы                                                                                                                                                                                   ')
INSERT #F VALUES (2,25,1,'Должности работников государственного органа, переведенных на новые системы оплаты труда 4)                                                                                                                                                               ')
INSERT #F VALUES (2,26,1,'Всего должностей работнриков (сумма строк 200+230+280+290+300)                                                                                                                                                                                            ')
INSERT #F VALUES (2,1,2,'200                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,2,2,'210                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,3,2,'220                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,4,2,'230                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,5,2,'240                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,6,2,'241                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,7,2,'242                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,8,2,'243                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,9,2,'250                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,10,2,'251                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,11,2,'252                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,12,2,'253                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,13,2,'260                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,14,2,'261                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,15,2,'262                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,16,2,'263                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,17,2,'264                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,18,2,'270                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,19,2,'271                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,20,2,'272                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,21,2,'273                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,22,2,'274                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,23,2,'280                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,24,2,'290                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,25,2,'300                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,26,2,'310                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,1,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,2,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,3,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,4,3,'ИТОГ_Ф14("210+220")')
INSERT #F VALUES (2,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,7,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,9,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,12,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,13,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,14,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,15,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,16,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,17,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,18,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,19,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,20,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,21,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,22,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,23,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,24,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,25,3,'14_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,26,3,'ИТОГ_Ф14("200+230+280+290+300")')
INSERT #F VALUES (2,1,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,2,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,3,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,4,4,'ИТОГ_Ф14("210+220")')
INSERT #F VALUES (2,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,9,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,10,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,12,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,13,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,14,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,15,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,16,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,17,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,18,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,19,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,20,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,21,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,22,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,23,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,24,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,25,4,'14_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,26,4,'ИТОГ_Ф14("200+230+280+290+300")')
INSERT #F VALUES (2,1,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,2,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,3,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,4,5,'ИТОГ_Ф14("210+220")')
INSERT #F VALUES (2,5,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,7,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,9,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,10,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,12,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,13,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,14,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,15,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,16,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,17,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,18,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,19,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,20,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,21,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,22,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,23,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,24,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,25,5,'14_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,26,5,'ИТОГ_Ф14("200+230+280+290+300KBK")')
INSERT #F VALUES (3,1,1,'Количество государственных органов                                                                                                                                                                                                                        ')
INSERT #F VALUES (3,2,1,'Расходы на выплату денежного содержания, учтенного в строках 020 и 030 всего  (сумма строк 410+420+430+440)                                                                                                                                               ')
INSERT #F VALUES (3,3,1,'в том числе по категориям: руководители  (сумма строк 411+412+413)                                                                                                                                                                                        ')
INSERT #F VALUES (3,4,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,5,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,6,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,7,1,'помощники (советники) сумма строк (421+422+423)                                                                                                                                                                                                           ')
INSERT #F VALUES (3,8,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,9,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,10,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,11,1,'специалисты  (сумма строк 431+432+433+434)                                                                                                                                                                                                                ')
INSERT #F VALUES (3,12,1,'из них по группам: высшие                                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,13,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,14,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,15,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,16,1,'обеспечивающие специалисты (сумма строк 441+442+443+444)                                                                                                                                                                                                  ')
INSERT #F VALUES (3,17,1,'из них по группам: главные                                                                                                                                                                                                                                ')
INSERT #F VALUES (3,18,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,19,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,20,1,'младшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,1,2,'320                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,2,2,'400                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,3,2,'410                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,4,2,'411                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,5,2,'412                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,6,2,'413                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,7,2,'420                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,8,2,'421                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,9,2,'422                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,10,2,'423                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,11,2,'430                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,12,2,'431                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,13,2,'432                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,14,2,'433                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,15,2,'434                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,16,2,'440                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,17,2,'441                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,18,2,'442                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,19,2,'443                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,20,2,'444                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,3,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,4,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,7,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,8,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,9,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,11,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,12,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,13,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,14,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,15,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,16,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,17,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,18,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,19,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,20,3,'ЗАПРЕТ()')
INSERT #F VALUES (4,1,1,'Служебные легковые автомобили, состоящие на балансе государственного органа                                                                                                                                                                               ')
INSERT #F VALUES (4,2,1,'Служебные легковые автомобили, арендованные у других организаций по договорам найма                                                                                                                                                                       ')
INSERT #F VALUES (4,1,2,'450                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,2,2,'460                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,1,3,'ЗАПРЕТ()')
INSERT #F VALUES (4,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (4,1,4,'ЗАПРЕТ()')
INSERT #F VALUES (4,2,4,'ЗАПРЕТ()')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 322
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,4,7,0,0,0,'070-(010+020+030+040+050+060) =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(2,NULL,0,NULL,7,1,0,0,0,'100-(070+080+090) =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(3,NULL,0,NULL,8,7,0,0,0,'230-(210+220) =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(4,NULL,0,NULL,9,1,0,0,0,'240-(241+242+243) =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(5,NULL,0,NULL,10,1,0,0,0,'250-(251+252+253) =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(6,NULL,0,NULL,13,7,0,0,0,'310-(200+230+280+290+300) =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(7,NULL,0,NULL,19,7,0,0,0,'070Гр3>=070Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(8,NULL,0,NULL,20,7,0,0,0,'080Гр3>=080Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(9,NULL,0,NULL,21,7,0,0,0,'100Гр3>=100Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(10,NULL,0,NULL,23,7,0,0,0,'200Гр3>=200Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(11,NULL,0,NULL,24,7,0,0,0,'210Гр3>=210Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(12,NULL,0,NULL,25,7,0,0,0,'220Гр3>=220Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(13,NULL,0,NULL,26,7,0,0,0,'230Гр3>=230Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(14,NULL,0,NULL,51,3,0,0,0,'090Гр3>=090Гр4 =  0',0,0,1,'20111024','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(15,NULL,0,NULL,53,7,0,0,0,'280Гр3>=280Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(16,NULL,0,NULL,54,7,0,0,0,'290Гр3>=290Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(17,NULL,0,NULL,55,7,0,0,0,'300Гр3>=300Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(18,NULL,0,NULL,56,7,0,0,0,'310Гр3>=310Гр4 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(19,NULL,0,NULL,58,3,0,0,0,'100>=070 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(20,NULL,0,NULL,59,3,0,0,0,'Укажите расходы по строке 010 или 200 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(21,NULL,0,NULL,60,3,0,0,0,'Укажите расходы по строке 020 или 210 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(22,NULL,0,NULL,61,3,0,0,0,'Укажите данные по строке 030 или 220 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(23,NULL,0,NULL,62,3,0,0,0,'Укажите данные по строке 040 или 280 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(24,NULL,0,NULL,63,3,0,0,0,'Укажите данные по строке 050 или 290 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(25,NULL,0,NULL,64,3,0,0,0,'Укажите данные по строке 060 или 300 =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(26,NULL,0,NULL,86,7,0,0,0,'Средняя заработная плата лиц, замещающих  государственные должности =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(27,NULL,0,NULL,87,7,0,0,0,'Средняя заработная плата лиц, замещающие должности государственной гражданской службы =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(28,NULL,0,NULL,88,7,0,0,0,'Сред. заработн. плата лиц, замещающих отдельные должности гос. гражд. службы =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(29,NULL,0,NULL,89,7,0,0,0,'Сред. заработн. плата лиц, замещающих  должности иного вида фед. гос. службы =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(30,NULL,0,NULL,90,7,0,0,0,'Сред. заработн. плата работников государственного органа, замещающих  должности, не являющиеся  должн. гос. гражд. службы =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(31,NULL,0,NULL,91,7,0,0,0,'Сред. заработн. плата работников гос. органа, оплата труда которых производится на основе ETC =  0',0,0,1,'20090116','','','','0503074','20110101','','=',9,'','')
INSERT #A VALUES(32,NULL,0,NULL,92,3,0,0,0,'Укажите данные по строке 320 или 310 =  0',0,0,1,'20111024','','','','0503074','20110101','','=',9,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 32
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%070%=%010%+%020%+%030%+%040%+%050%+%060%'',''4'')','070-(010+020+030+040+050+060)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%100%=%070%+%080%+%090%'',''*'')','100-(070+080+090)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%230%=%210%+%220%'' ,''*'')','230-(210+220)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%240%=%241%+%242%+%243%'' ,''*'')','240-(241+242+243)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%250%=%251%+%252%+%253%'' ,''*'')','250-(251+252+253)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%310%=%200%+%230%+%280%+%290%+%300%'' ,''*'')','310-(200+230+280+290+300)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%070Гр3%>=%070Гр4% '','''')','070Гр3>=070Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%080Гр3%>=%080Гр4%'','''')','080Гр3>=080Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%100Гр3%>=%100Гр4%'','''')','100Гр3>=100Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%200Гр3%>=%200Гр4%'','''')','200Гр3>=200Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%210Гр3%>=%210Гр4%'','''')','210Гр3>=210Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%220Гр3%>=%220Гр4%'','''')','220Гр3>=220Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%230Гр3%>=%230Гр4%'','''')','230Гр3>=230Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%090Гр3%>=%090Гр4%'','''')','090Гр3>=090Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%280Гр3%>=%280Гр4%'','''')','280Гр3>=280Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%290Гр3%>=%290Гр4%'','''')','290Гр3>=290Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%300Гр3%>=%300Гр4%'','''')','300Гр3>=300Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%310Гр3%>=%310Гр4%'','''')','310Гр3>=310Гр4','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%100%>=%070%'',''*'')','100>=070','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %010Гр4%=0 AND %200Гр5%=0 OR %010Гр4%>0 AND %200Гр5%>0 then 1 else 0 end'',''*#Укажите расходы по строке 010 или 200'')','Укажите расходы по строке 010 или 200','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %020Гр4%=0 AND %210Гр5%=0 OR %020Гр4%>0 AND %210Гр5%>0 then 1 else 0 end'',''*#Укажите расходы по строке 020 или 210'')','Укажите расходы по строке 020 или 210','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %030Гр4%=0 AND %220Гр5%=0 OR %030Гр4%>0 AND %220Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 030 или 220'')','Укажите данные по строке 030 или 220','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %040Гр4%=0 AND %280Гр5%=0 OR %040Гр4%>0 AND %280Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 040 или 280'')','Укажите данные по строке 040 или 280','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %050Гр4%=0 AND %290Гр5%=0 OR %050Гр4%>0 AND %290Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 050 или 290'')','Укажите данные по строке 050 или 290','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %060Гр4%=0 AND %300Гр5%=0 OR %060Гр4%>0 AND %300Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 060 или 300'')','Укажите данные по строке 060 или 300','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещ. гос. долж.=%%010Гр4%/%200Гр5%/%MONTH%'','''')','Средняя заработная плата лиц, замещающих  государственные должности','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(26,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещ. долж. гос. гражданской службы=%%020Гр4%/%210Гр5%/%MONTH%'','''')','Средняя заработная плата лиц, замещающие должности государственной гражданской службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(27,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещающих отдельные должности =%%030Гр4%/%220Гр5%/%MONTH%'','''')','Сред. заработн. плата лиц, замещающих отдельные должности гос. гражд. службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(28,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещающих  должности иного вида фед. гос. службы=%%040Гр4%/%280Гр5%/%MONTH%'','''')','Сред. заработн. плата лиц, замещающих  должности иного вида фед. гос. службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(29,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата работников государственного органа, замещающих  должности, не являющиеся  должн. гос. гражд. службы=%%050Гр4%/%290Гр5%/%MONTH%'','''')','Сред. заработн. плата работников государственного органа, замещающих  должности, не являющиеся  должн. гос. гражд. службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(30,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата работников гос. органа, оплата труда которых производится на основе ETC=%%060Гр4%/%300Гр5%/%MONTH%'','''')','Сред. заработн. плата работников гос. органа, оплата труда которых производится на основе ETC','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(31,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %320Гр3%=0 AND %310Гр3%=0 OR %320Гр3%>0 AND %310Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 310 или 320'')','Укажите данные по строке 320 или 310','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(32,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 64
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '8         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'8','14-ые формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '999999    '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'999999','формы отчетности',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-07-03 11:51:41.937',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-07-03 11:51:41.937'
	BEGIN
		SELECT @vcMessage = 'Форма 0503074 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0503074 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-07-03 11:51:41.937. Обновление отклонено.'
	END

	 IF OBJECT_ID('tempdb..#tabUpdateMessages') IS NOT NULL
	 BEGIN
		 INSERT #tabUpdateMessages([TXT]) VALUES (@vcMessage)
	 END
	 SELECT @vcMessage
END
GO

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL DROP TABLE #tabInfo
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog
DROP TABLE #tabStop

COMMIT TRANSACTION -- Фиксация транзакции.
GO


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (июл  3 2014 11:51:58:460AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0503075 (Отчет о расходах и численности работников органов местного самоуправл.)
-- Дата ввода : 20110101
-- Дата окончания действия :
-- Версия : 2014-07-03 11:51:58.460
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = '0503075' AND [START_DATE] = '20110101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-07-03 11:51:58.460',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '0503075',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '0503075'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20110101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SMETA'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Отчет о расходах и численности работников органов местного самоуправл.',@vcNEW_FORM_CODE,@dNEW_START_DATE,2,1,1,1,18186,'RA_EXPORT_FORM_0503074#RA_IMPORT_FORM_0503074',0,0,'19000101',NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'svodprint_14_ask()','Sv_0503075g_20101231.bas','','KirRepMakerMultiSheet.xls','SV_0503075_20110101.XLT','',NULL,'RA_EXPORT_FORM_0503074#RA_IMPORT_FORM_0503074',0,NULL,NULL,'FORM14_EDIT#26#1','014mo     ','',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Таблица', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Утверждено',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Фактически',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Таблица', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Численность', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Утверждено',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Фактически',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Среднесписочная численность',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Численность', @iLINK_FORM,2, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Справка1', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Фактически',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Справка1', @iLINK_FORM,3, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Справка2', @iLINK_FORM,4
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,100,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'На отчетную дату',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В среднем',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Справка2', @iLINK_FORM,4, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (18,1,1,1)
INSERT #R VALUES (22,1,1,1)
INSERT #R VALUES (1,1,0,1)
INSERT #R VALUES (2,1,1,1)
INSERT #R VALUES (4,1,1,1)
INSERT #R VALUES (5,1,1,1)
INSERT #R VALUES (6,1,1,1)
INSERT #R VALUES (7,1,1,1)
INSERT #R VALUES (8,1,1,1)
INSERT #R VALUES (9,1,1,1)
INSERT #R VALUES (10,1,1,1)
INSERT #R VALUES (11,1,1,1)
INSERT #R VALUES (13,1,2,1)
INSERT #R VALUES (14,1,1,1)
INSERT #R VALUES (17,1,1,1)
INSERT #R VALUES (19,1,1,1)
INSERT #R VALUES (20,1,1,1)
INSERT #R VALUES (21,1,1,1)
INSERT #R VALUES (23,1,1,1)
INSERT #R VALUES (24,1,1,1)
INSERT #R VALUES (25,1,1,1)
INSERT #R VALUES (26,1,3,1)
INSERT #R VALUES (2,2,1,1)
INSERT #R VALUES (3,2,1,1)
INSERT #R VALUES (4,2,1,1)
INSERT #R VALUES (5,2,1,1)
INSERT #R VALUES (6,2,1,1)
INSERT #R VALUES (7,2,1,1)
INSERT #R VALUES (8,2,1,1)
INSERT #R VALUES (9,2,1,1)
INSERT #R VALUES (10,2,1,1)
INSERT #R VALUES (11,2,2,1)
INSERT #R VALUES (1,3,1,1)
INSERT #R VALUES (2,3,20,1)
INSERT #R VALUES (3,3,5,1)
INSERT #R VALUES (4,3,2,1)
INSERT #R VALUES (5,3,3,1)
INSERT #R VALUES (6,3,4,1)
INSERT #R VALUES (7,3,9,1)
INSERT #R VALUES (1,4,1,1)
INSERT #R VALUES (2,4,2,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 41
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,1,1,'Заработная плата лиц, замещающих муниципальные должности, всего (сумма строк 011+012)                                                                                                                                                                     ')
INSERT #F VALUES (1,2,1,'в т.ч.:денежное вознаграждение (денежное содержание)                                                                                                                                                                                                      ')
INSERT #F VALUES (1,4,1,'другие выплаты , предусмотренные действующим законодательством                                                                                                                                                                                            ')
INSERT #F VALUES (1,5,1,'Заработная плата  лиц, замещающих должности муниципальной  службы, всего (сумма строк 021+022+024)                                                                                                                                                        ')
INSERT #F VALUES (1,6,1,'в т.ч.:должностной оклад                                                                                                                                                                                                                                  ')
INSERT #F VALUES (1,7,1,'дополнительные выплаты                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,8,1,'из них:  ежемесячное денежное поощрение                                                                                                                                                                                                                   ')
INSERT #F VALUES (1,9,1,'другие выплаты , предусмотренные действующим законодательством                                                                                                                                                                                            ')
INSERT #F VALUES (1,10,1,'Заработная плата лиц, замещающих должности, не являющиеся должностями муниципальной службы                                                                                                                                                                ')
INSERT #F VALUES (1,11,1,'Заработная плата работников органа местного самоуправления, избирательной комиссии муниципального образования, переведенных на новые системы оплаты труда 1)                                                                                              ')
INSERT #F VALUES (1,13,1,'Итого расходов на заработнрую плату работников органа местного самоуправления, избирательной комиссии муниципального образования (сумма строк 010+0520+030+040)                                                                                           ')
INSERT #F VALUES (1,14,1,'Прочие выплаты  работникам  органа местного самоуправления, избирательной комиссии  муниципального образования                                                                                                                                            ')
INSERT #F VALUES (1,17,1,'из них: компенсации работникам за использование  личных   легковых   автомобилей для служебных целей                                                                                                                                                      ')
INSERT #F VALUES (1,18,1,'суточные при служебных командировках, всего (сумма строк 063+064)                                                                                                                                                                                         ')
INSERT #F VALUES (1,19,1,'в том числе: на территории Российской Федерации                                                                                                                                                                                                           ')
INSERT #F VALUES (1,20,1,'на территории иностранных государств                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,21,1,'Другие расходы  на содержание органа местного самоуправления, избирательной комиссии муниципального образования                                                                                                                                           ')
INSERT #F VALUES (1,22,1,'из них: на служебные командировки (оплата проезда и проживания), всего (сумма строк 072+073)                                                                                                                                                              ')
INSERT #F VALUES (1,23,1,'в том числе: на территории Российской Федерации                                                                                                                                                                                                           ')
INSERT #F VALUES (1,24,1,'на территории иностранных государств                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,25,1,'на содержание служебных легковых автомобилей                                                                                                                                                                                                              ')
INSERT #F VALUES (1,26,1,'ВСЕГО расходов  на содержание  органа местного самоуправления, избирательной комиссии  муниципального образования (сумма строк 050+060+0701)                                                                                                              ')
INSERT #F VALUES (1,1,2,'010                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,2,2,'011                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,4,2,'012                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,5,2,'020                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,6,2,'021                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,7,2,'022                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,8,2,'023                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,9,2,'024                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,10,2,'030                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,11,2,'040                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,13,2,'050                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,14,2,'060')
INSERT #F VALUES (1,17,2,'061                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,18,2,'062                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,19,2,'063                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,20,2,'064                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,21,2,'070')
INSERT #F VALUES (1,22,2,'071                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,23,2,'072                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,24,2,'073                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,25,2,'074                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,26,2,'080                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (1,1,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,4,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,7,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,8,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,9,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,11,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,17,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,18,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,19,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,20,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,22,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,23,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,24,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,25,3,'ЗАПРЕТ()')
INSERT #F VALUES (1,26,3,'ИТОГ_Ф14("050+060+070")')
INSERT #F VALUES (1,1,4,'14МО_УСТАНОВКА()+14МО_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,4,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,5,4,'14МО_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,6,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,8,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,9,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,10,4,'14МО_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,11,4,'14МО_ФАКТ_РАСХОД(К.СТР.)')
INSERT #F VALUES (1,13,4,'ИТОГ_Ф14("010+020+030+040")')
INSERT #F VALUES (1,14,4,'14МО_ФАКТ_РАСХОД(К.СТР.)                                                                                                                                                                                                                                  ')
INSERT #F VALUES (1,17,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,18,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,19,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,20,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,21,4,'14МО_ФАКТ_РАСХОД(К.СТР.)                                                                                                                                                                                                                                  ')
INSERT #F VALUES (1,22,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,23,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,24,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,25,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,26,4,'ИТОГ_Ф14("050+060+070KBK")')
INSERT #F VALUES (2,2,1,'Муниципальные должности                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,3,1,'Должности  муниципальной службы, всего (сумма строк 220+230+240+250+260)                                                                                                                                                                                  ')
INSERT #F VALUES (2,4,1,'в том числе по группам должностей: высшие                                                                                                                                                                                                                 ')
INSERT #F VALUES (2,5,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,6,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,7,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,8,1,'младшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,9,1,'Должности, не являющиеся должностями муниципальной службы                                                                                                                                                                                                 ')
INSERT #F VALUES (2,10,1,'Должности работников, переведенных на новые системы оплаты труда 2)                                                                                                                                                                                       ')
INSERT #F VALUES (2,11,1,'Всего должностей работников органа местного самоуправления, избирательной комиссии муниципального образования, (сумма строк 200+210+270+280)                                                                                                              ')
INSERT #F VALUES (2,2,2,'200                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,3,2,'210                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,4,2,'220                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,5,2,'230                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,6,2,'240                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,7,2,'250                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,8,2,'260                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,9,2,'270                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,10,2,'280                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,11,2,'290                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,2,3,'14МО_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,3,3,'14МО_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,4,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,7,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,3,'ЗАПРЕТ()')
INSERT #F VALUES (2,9,3,'14МО_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,10,3,'14МО_ШТАТ(К.СТР.)')
INSERT #F VALUES (2,11,3,'ИТОГ_Ф14("200+210+270+280")')
INSERT #F VALUES (2,2,4,'14МО_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,3,4,'14МО_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,4,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,9,4,'14МО_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,10,4,'14МО_ФАКТ_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,11,4,'ИТОГ_Ф14("200+210+270+280")')
INSERT #F VALUES (2,2,5,'14МО_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,3,5,'14МО_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,4,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,5,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,7,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,9,5,'14МО_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,10,5,'14МО_СРЕД_ЧИСЛО(К.СТР.)')
INSERT #F VALUES (2,11,5,'ИТОГ_Ф14("200+210+270+280KBK")')
INSERT #F VALUES (3,1,1,'Количество органов местного самоуправления, избирательных комиссий муниципальных образований')
INSERT #F VALUES (3,2,1,'Денежное содержание  муниципальных  служащих (стр. 020 - 024), всего (сумма строк 410+420+430+440+450)                                                                                                                                                    ')
INSERT #F VALUES (3,3,1,'в том числе по группам должностей: высшие                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,4,1,'главные                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,5,1,'ведущие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,6,1,'старшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,7,1,'младшие                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (3,1,2,'300')
INSERT #F VALUES (3,2,2,'400                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,3,2,'410                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,4,2,'420                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,5,2,'430                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,6,2,'440                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,7,2,'450                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,3,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,4,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,7,3,'ЗАПРЕТ()')
INSERT #F VALUES (4,1,1,'Служебные легковые автомобили, состоящие на балансе органа местного самоуправления, избирательных комиссий муниципальных образований                                                                                                                      ')
INSERT #F VALUES (4,2,1,'Служебные легковые автомобили, арендованные у других организаций по договорам найма                                                                                                                                                                       ')
INSERT #F VALUES (4,1,2,'460                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,2,2,'470                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (4,1,3,'ЗАПРЕТ()')
INSERT #F VALUES (4,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (4,1,4,'ЗАПРЕТ()')
INSERT #F VALUES (4,2,4,'ЗАПРЕТ()')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 163
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'050(4)=010(4)+020(4)+030(4)+040(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(2,NULL,0,NULL,2,7,0,0,0,'050(3)>=050(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(3,NULL,0,NULL,3,7,0,0,0,'070(3) >=  070(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(4,NULL,0,NULL,4,7,0,0,0,'080(3) >=  080(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(5,NULL,0,NULL,5,7,0,0,0,'290 = 200+210+270+280 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(6,NULL,0,NULL,6,7,0,0,0,'200(3) >=  200(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(7,NULL,0,NULL,7,7,0,0,0,'210(3) >=  210(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(8,NULL,0,NULL,8,7,0,0,0,'270(3) >=  270(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(9,NULL,0,NULL,9,7,0,0,0,'280(3) >=  280(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(10,NULL,0,NULL,10,7,0,0,0,'290(3) >=  290(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(11,NULL,0,NULL,15,7,0,0,0,'080 = 050 + 060 + 070 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(12,NULL,0,NULL,19,7,0,0,0,'060(3)>=060(4) =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(13,NULL,0,NULL,27,3,0,0,0,'Укажите расходы по строке 010 или 200 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(14,NULL,0,NULL,28,3,0,0,0,'Укажите расходы по строке 020 или 210 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(15,NULL,0,NULL,29,3,0,0,0,'Укажите данные по строке 030 или 270 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(16,NULL,0,NULL,30,3,0,0,0,'Укажите данные по строке 040 или 280 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(17,NULL,0,NULL,31,3,0,0,0,'Укажите данные по строке 050 или 290 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(18,NULL,0,NULL,39,3,0,0,0,'Укажите данные по строке 200Гр5 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(19,NULL,0,NULL,40,3,0,0,0,'Укажите данные по строке 270Гр5 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(20,NULL,0,NULL,41,3,0,0,0,'Укажите данные по строке 280Гр5 =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(21,NULL,0,NULL,42,7,0,0,0,'Сред. заработн. плата лиц, замещающих муниципальные должности =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(22,NULL,0,NULL,43,7,0,0,0,'Сред. заработн. плата лиц, замещающих должности муниципальной  службы =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(23,NULL,0,NULL,44,7,0,0,0,'Сред. заработн. плата работников органа мест. самоуправ., не являющ.  должн. муниц. службы =  0',0,0,1,'20090116','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(24,NULL,0,NULL,45,7,0,0,0,'Заработная плата работников ОМС, избирательной комиссии муниц.образования, переведенных на новые системы оплаты труда =  0',0,0,1,'20110210','','','','0503075','20110101','','=',9,'','')
INSERT #A VALUES(25,NULL,0,NULL,46,3,0,0,0,'Укажите данные по строке 290 или 300 =  0',0,0,1,'20130731','','','','0503075','20110101','','=',9,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 25
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%050%=%010%+%020%+%030%+%040%'',''4'')','050(4)=010(4)+020(4)+030(4)+040(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%050Гр3%>=%050Гр4%'','''')','050(3)>=050(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%070Гр3%>=%070Гр4%'','''')','070(3) >=  070(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%080Гр3%>=%080Гр4%'','''')','080(3) >=  080(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%290%=%200%+%210%+%270%+%280%'',''*'')','290 = 200+210+270+280','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%200Гр3%>=%200Гр4%'','''')','200(3) >=  200(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%210Гр3%>=%210Гр4%'','''')','210(3) >=  210(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%270Гр3%>=%270Гр4%'','''')','270(3) >=  270(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%280Гр3%>=%280Гр4%'','''')','280(3) >=  280(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%290Гр3%>=%290Гр4%'','''')','290(3) >=  290(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%080%=%050%+%060%+%070%'',''*'')','080 = 050 + 060 + 070','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%060Гр3%>=%060Гр4%'','''')','060(3)>=060(4)','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %010Гр4%=0 AND %200Гр5%=0 OR %010Гр4%>0 AND %200Гр5%>0 then 1 else 0 end'',''*#Укажите расходы по строке 010 или 200'')','Укажите расходы по строке 010 или 200','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %020Гр4%=0 AND %210Гр5%=0 OR %020Гр4%>0 AND %210Гр5%>0 then 1 else 0 end'',''*#Укажите расходы по строке 020 или 210'')','Укажите расходы по строке 020 или 210','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %030Гр4%=0 AND %270Гр5%=0 OR %030Гр4%>0 AND %270Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 030 или 270'')','Укажите данные по строке 030 или 270','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %040Гр4%=0 AND %280Гр5%=0 OR %040Гр4%>0 AND %280Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 040 или 280'')','Укажите данные по строке 040 или 280','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %050Гр4%=0 AND %290Гр5%=0 OR %050Гр4%>0 AND %290Гр5%>0 then 1 else 0 end'',''*#Укажите данные по строке 050 или 290'')','Укажите данные по строке 050 или 290','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when (%200Гр3%=0 and %200Гр4%=0) or (%200Гр3%>0 and %200Гр5%>0) or (%200Гр4%>0 and %200Гр5%>0) then 1 else 0 end'',''*#Укажите данные по строке 200Гр5'')','Укажите данные по строке 200Гр5','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when (%270Гр3%=0 and %270Гр4%=0) or (%270Гр3%>0 and %270Гр5%>0) or (%270Гр4%>0 and %270Гр5%>0) then 1 else 0 end'',''*#Укажите данные по строке 270Гр5'')','Укажите данные по строке 270Гр5','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when (%280Гр3%=0 and %280Гр4%=0) or (%280Гр3%>0 and %280Гр5%>0) or (%280Гр4%>0 and %280Гр5%>0) then 1 else 0 end'',''*#Укажите данные по строке 280Гр5'')','Укажите данные по строке 280Гр5','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещающих муниципальные должности=%%010Гр4%/%200Гр5%/%MONTH%'','''')','Сред. заработн. плата лиц, замещающих муниципальные должности','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата лиц, замещающих должности муниципальной  службы=%%020Гр4%/%210Гр5%/%MONTH%'','''')','Сред. заработн. плата лиц, замещающих должности муниципальной  службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Сред. заработн. плата работников органа мест. самоуправ., не являющ.  должн. муниц. службы=%%030Гр4%/%270Гр5%/%MONTH%'','''')','Сред. заработн. плата работников органа мест. самоуправ., не являющ.  должн. муниц. службы','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''%INFO=Средняя заработная плата работников ОМС, избирательной комиссии муниц.образования, переведенных на новые системы оплаты труда=%%040Гр4%/%280Гр5%/%MONTH%'','''')','Заработная плата работников ОМС, избирательной комиссии муниц.образования, переведенных на новые системы оплаты труда','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,1,2,'+',NULL,NULL,NULL,NULL,0,0,'rn_f14ks(''1= case when %290Гр3%=0 AND %300Гр3%=0 OR %290Гр3%>0 AND %300Гр3%>0 then 1 else 0 end'',''*#Укажите данные по строке 290 или 300'')','Укажите данные по строке 290 или 300','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 50
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '8         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'8','14-ые формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '999999    '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'999999','формы отчетности',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-07-03 11:51:58.460',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-07-03 11:51:58.460'
	BEGIN
		SELECT @vcMessage = 'Форма 0503075 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0503075 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-07-03 11:51:58.460. Обновление отклонено.'
	END

	 IF OBJECT_ID('tempdb..#tabUpdateMessages') IS NOT NULL
	 BEGIN
		 INSERT #tabUpdateMessages([TXT]) VALUES (@vcMessage)
	 END
	 SELECT @vcMessage
END
GO

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL DROP TABLE #tabInfo
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog
DROP TABLE #tabStop

COMMIT TRANSACTION -- Фиксация транзакции.
GO


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (июл  4 2014 11:11:39:253AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 4fss (Расчетная ведомость по средствам ФСС РФ)
-- Дата ввода : 20140101
-- Дата окончания действия :
-- Версия : 2014-07-04 11:11:39.253
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = '4fss' AND [START_DATE] = '20140101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-07-04 11:11:39.253',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '4fss',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '4fss'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20140101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SALARY'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Расчетная ведомость по средствам ФСС РФ',@vcNEW_FORM_CODE,@dNEW_START_DATE,2,0,0,1,2291,'i_report_export_nalog',0,0,'19000101',NULL,''
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'sa_print_4FSS_110214()','4FSS_110214.bas','','KirRepMakerMultiSheet.XLS','4FSS_110214.xlt','',NULL,'i_report_export_nalog',0,NULL,NULL,NULL,'          ','REPORTS_ATR_NOM_OBR',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р0. Титул', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование',@iLINK_TABLE,0,1,0,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала года',@iLINK_TABLE,1,0,3,1,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р0. Титул', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.1 Расчёты по обяз. страхованию', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование',@iLINK_TABLE,0,1,0,0,250,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Сумма',@iLINK_TABLE,0,0,3,2,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Номер платеж. поручения',@iLINK_TABLE,0,1,4,0,254,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.1 Расчёты по обяз. страхованию', @iLINK_FORM,2, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.2. Расходы на цели обязат. соц. страх', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование статей',@iLINK_TABLE,0,1,0,0,0,0,'','','',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Число случаев / количество получателей',@iLINK_TABLE,0,0,2,1,0,1,NULL,NULL,NULL,'999999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Количество дней, выплат, пособий',@iLINK_TABLE,0,0,3,2,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Расходы. Всего',@iLINK_TABLE,0,0,4,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Расходы. в т.ч. выплаты за счет средств федерального бюджета',@iLINK_TABLE,0,0,5,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.2. Расходы на цели обязат. соц. страх', @iLINK_FORM,3, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.3. Расчет базы для взносов ФСС', @iLINK_FORM,4
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование',@iLINK_TABLE,1,1,1,0,250,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строк',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В т.ч. сумма за 1 мес отч. квартала',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В т.ч. сумма за 2 мес отч. квартала',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. сумма за 3 мес отч. квартала',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.3. Расчет базы для взносов ФСС', @iLINK_FORM,4, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.3.1. Сведения, для применения пониженного', @iLINK_FORM,5
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,4,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Фамилия имя отчество',@iLINK_TABLE,1,1,2,0,100,1,'KU_PERSON_FIO','COL2','CODE',NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Дата справки',@iLINK_TABLE,1,1,3,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Срок действия',@iLINK_TABLE,1,1,4,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. сумма за 1 мес отч. квартала',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'В т.ч. сумма за 2 мес отч. квартала',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'В т.ч. сумма за 3 мес отч. квартала',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.3.1. Сведения, для применения пониженного', @iLINK_FORM,5, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.SA_4FSS_28022011_PREPARE_INV @Lsf',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4. Условия применения пониж. тарифа таб.1', @iLINK_FORM,6
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В т.ч. сумма за 1 мес отч. квартала',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В т.ч. сумма за 2 мес отч. квартала',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. сумма за 3 мес отч. квартала',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4. Условия применения пониж. тарифа таб.1', @iLINK_FORM,6, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4.1 Условия применения пониж. тарифа таб.2', @iLINK_FORM,7
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В т.ч. сумма за 1 мес отч. квартала',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В т.ч. сумма за 2 мес отч. квартала',@iLINK_TABLE,1,0,5,5,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. сумма за 3 мес отч. квартала',@iLINK_TABLE,1,0,6,6,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4.1 Условия применения пониж. тарифа таб.2', @iLINK_FORM,7, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4.2. Расчёт условий для орг. инф. техн.', @iLINK_FORM,8
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'По итогам  9-ти месяцев года, предшествующего текущему расчетному пери',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'По итогам текущего отчетного (расчетного) периода',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Дата записи в реестре аккредитованных организаций',@iLINK_TABLE,1,1,5,5,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'№ записи в реестре аккредитованных организаций',@iLINK_TABLE,1,1,6,6,50,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4.2. Расчёт условий для орг. инф. техн.', @iLINK_FORM,8, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4.3. Расчёт условий для орг. и и.п. - упро', @iLINK_FORM,9
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'С начала отчетного (расчетного) периода',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4.3. Расчёт условий для орг. и и.п. - упро', @iLINK_FORM,9, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4.4. Расчёт условий для некомерч. орг.', @iLINK_FORM,10
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'По итогам года, предшествующего текущему расчетному периоду',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'По итогам текущего расчетного периода',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4.4. Расчёт условий для некомерч. орг.', @iLINK_FORM,10, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.4.5.Свед., для прим. пониж. тарифа п14 ч1', @iLINK_FORM,11
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'№ патента',@iLINK_TABLE,1,1,2,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Вид предпринимательской деятельности, установленный законом субъекта Российской Федерации',@iLINK_TABLE,1,1,3,0,254,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Сведения из патента - дата начала действия',@iLINK_TABLE,1,1,4,0,10,1,NULL,NULL,NULL,'99.99.9999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Сведения из патента - дата окончания действия',@iLINK_TABLE,1,1,5,0,10,1,NULL,NULL,NULL,'99.99.9999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Всего с начала расчетного периода',@iLINK_TABLE,0,0,6,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'В т.ч. за последние три месяца о.п. - 1 месяц',@iLINK_TABLE,1,0,7,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'В т.ч. за последние три месяца о.п. - 2 месяц',@iLINK_TABLE,1,0,8,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'В т.ч. за последние три месяца о.п. - 3 месяц',@iLINK_TABLE,1,0,9,0,2,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.4.5.Свед., для прим. пониж. тарифа п14 ч1', @iLINK_FORM,11, @iLINK_CODE_COL,1,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1.Табл.5. Выпл. за счёт средств Федерал. бюджета', @iLINK_FORM,12
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование статей',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего число получателей',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Всего количество дней, выплат, пособий',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Всего расходы (сумма)',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. Чернобыльская АЭС число получателей',@iLINK_TABLE,1,0,6,6,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'В т.ч. Чернобыльская АЭС количество дней, выплат, пособий',@iLINK_TABLE,1,0,7,7,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'В т.ч. Чернобыльская АЭС расходы (сумма)',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'В т.ч. ПО "Маяк" число получателей',@iLINK_TABLE,1,0,9,9,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'В т.ч. ПО "Маяк" количество дней, выплат, пособий',@iLINK_TABLE,1,0,10,10,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'В т.ч. ПО "Маяк" расходы (сумма)',@iLINK_TABLE,1,0,11,11,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'В т.ч. Семипалатинский полигон число получателей',@iLINK_TABLE,1,0,12,12,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'В т.ч. Семипалатинский полигон количество дней, выплат, пособий',@iLINK_TABLE,1,0,13,13,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'В т.ч. Семипалатинский полигон расходы (сумма)',@iLINK_TABLE,1,0,14,14,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 15,'В т.ч. подразделения особого риска число получателей',@iLINK_TABLE,1,0,15,15,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 16,'В т.ч. подразделения особого риска количество дней, выплат, пособий',@iLINK_TABLE,1,0,16,16,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 17,'В т.ч. подразделения особого риска расходы (сумма)',@iLINK_TABLE,1,0,17,17,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 18,'В т.ч. доп.выпл. по № 255-ФЗ число получателей',@iLINK_TABLE,1,0,18,18,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 19,'В т.ч. доп.выпл. по № 255-ФЗ количество дней, выплат, пособий',@iLINK_TABLE,1,0,19,19,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 20,'В т.ч. доп.выпл. по № 255-ФЗ расходы (сумма)',@iLINK_TABLE,1,0,20,20,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1.Табл.5. Выпл. за счёт средств Федерал. бюджета', @iLINK_FORM,12, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.Табл.6. Несчастные случаи - база', @iLINK_FORM,13
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Выплаты, на которые начисляются стр. взносы, всего',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'в.т.ч. выплаты инвалидам, на которые начисляются стр. взносы',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Выплаты , на которые не начисляются стр. взносы',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Размер страхового тарифа',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Скидка к страховому тарифу',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Дата установления надбавки к стр. тарифу',@iLINK_TABLE,1,1,8,9,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'% надбавки к стр. тарифу',@iLINK_TABLE,1,0,9,9,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Размер тарифа с учётом скидки (надбавки)',@iLINK_TABLE,1,0,10,10,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.Табл.6. Несчастные случаи - база', @iLINK_FORM,13, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.Табл.7. Несчастные случаи - расчёт', @iLINK_FORM,14
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Сумма (руб.коп.)',@iLINK_TABLE,1,0,3,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Номер платеж. поручения',@iLINK_TABLE,1,1,4,0,50,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.Табл.7. Несчастные случаи - расчёт', @iLINK_FORM,14, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.Табл.8. Расходы по страхованию от несч. случ.', @iLINK_FORM,15
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование статей',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Количество дней',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Сумма (руб., коп.)',@iLINK_TABLE,1,0,4,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.Табл.8. Расходы по страхованию от несч. случ.', @iLINK_FORM,15, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.Табл.9. Численность пострадавших по стр. случ.', @iLINK_FORM,16
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Численность пострадавших человек',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.Табл.9. Численность пострадавших по стр. случ.', @iLINK_FORM,16, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.Табл.10. Свед. о рез. провед. спец. оценке усл.', @iLINK_FORM,17
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Общее количество рабочих мест страхователя',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Кол. раб. мест, в отн. усл.труд. на которых провед. спец.оценка у.т. - на начало года',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Кол. раб. мест, на которых провед. спец.оценка. Вред и опасн классы  - 3 класс',@iLINK_TABLE,1,0,6,6,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Кол. раб. мест, на которых провед. спец. оценка. Вред и опасн классы  - 4 класс',@iLINK_TABLE,1,0,7,7,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Общ. число. раб., на вред. и (или) опас. производст. подлежащих медосмот',@iLINK_TABLE,1,0,8,8,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Кол. раб., на вред. и (или) опас. производ. прошедших медосмотр на нач',@iLINK_TABLE,1,0,9,9,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.Табл.10. Свед. о рез. провед. спец. оценке усл.', @iLINK_FORM,17, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (1,1,1,1)
INSERT #R VALUES (2,1,3,1)
INSERT #R VALUES (3,1,4,1)
INSERT #R VALUES (4,1,4,1)
INSERT #R VALUES (1,2,1,1)
INSERT #R VALUES (2,2,2,1)
INSERT #R VALUES (3,2,34,1)
INSERT #R VALUES (4,2,4,1)
INSERT #R VALUES (5,2,33,1)
INSERT #R VALUES (6,2,6,1)
INSERT #R VALUES (7,2,7,1)
INSERT #R VALUES (8,2,8,1)
INSERT #R VALUES (9,2,34,1)
INSERT #R VALUES (10,2,10,1)
INSERT #R VALUES (11,2,33,1)
INSERT #R VALUES (12,2,12,1)
INSERT #R VALUES (13,2,13,1)
INSERT #R VALUES (14,2,14,1)
INSERT #R VALUES (15,2,34,1)
INSERT #R VALUES (16,2,16,1)
INSERT #R VALUES (17,2,33,1)
INSERT #R VALUES (18,2,18,1)
INSERT #R VALUES (19,2,19,1)
INSERT #R VALUES (20,2,20,1)
INSERT #R VALUES (21,2,34,1)
INSERT #R VALUES (22,2,22,1)
INSERT #R VALUES (23,2,33,1)
INSERT #R VALUES (24,2,24,1)
INSERT #R VALUES (25,2,25,1)
INSERT #R VALUES (26,2,26,1)
INSERT #R VALUES (27,2,34,1)
INSERT #R VALUES (28,2,28,1)
INSERT #R VALUES (29,2,33,1)
INSERT #R VALUES (30,2,30,1)
INSERT #R VALUES (31,2,31,1)
INSERT #R VALUES (32,2,32,1)
INSERT #R VALUES (33,2,55,1)
INSERT #R VALUES (34,2,34,1)
INSERT #R VALUES (35,2,35,1)
INSERT #R VALUES (36,2,36,1)
INSERT #R VALUES (37,2,37,1)
INSERT #R VALUES (38,2,38,1)
INSERT #R VALUES (39,2,39,1)
INSERT #R VALUES (40,2,53,1)
INSERT #R VALUES (41,2,41,1)
INSERT #R VALUES (42,2,52,1)
INSERT #R VALUES (43,2,43,1)
INSERT #R VALUES (44,2,44,1)
INSERT #R VALUES (45,2,45,1)
INSERT #R VALUES (46,2,53,1)
INSERT #R VALUES (47,2,47,1)
INSERT #R VALUES (48,2,52,1)
INSERT #R VALUES (49,2,49,1)
INSERT #R VALUES (50,2,50,1)
INSERT #R VALUES (1,3,2,1)
INSERT #R VALUES (2,3,1,1)
INSERT #R VALUES (3,3,2,1)
INSERT #R VALUES (4,3,1,1)
INSERT #R VALUES (5,3,3,1)
INSERT #R VALUES (6,3,2,1)
INSERT #R VALUES (7,3,1,1)
INSERT #R VALUES (8,3,2,1)
INSERT #R VALUES (9,3,1,1)
INSERT #R VALUES (10,3,1,1)
INSERT #R VALUES (11,3,1,1)
INSERT #R VALUES (12,3,4,1)
INSERT #R VALUES (1,4,1,1)
INSERT #R VALUES (2,4,2,1)
INSERT #R VALUES (3,4,3,1)
INSERT #R VALUES (4,4,4,1)
INSERT #R VALUES (5,4,5,1)
INSERT #R VALUES (6,4,6,1)
INSERT #R VALUES (7,4,7,1)
INSERT #R VALUES (8,4,8,1)
INSERT #R VALUES (1,6,1,1)
INSERT #R VALUES (2,6,2,1)
INSERT #R VALUES (3,6,4,1)
INSERT #R VALUES (1,7,1,1)
INSERT #R VALUES (2,7,2,1)
INSERT #R VALUES (3,7,4,1)
INSERT #R VALUES (4,7,5,1)
INSERT #R VALUES (5,7,6,1)
INSERT #R VALUES (6,7,7,1)
INSERT #R VALUES (1,8,1,1)
INSERT #R VALUES (2,8,3,1)
INSERT #R VALUES (3,8,4,1)
INSERT #R VALUES (4,8,5,1)
INSERT #R VALUES (5,8,6,1)
INSERT #R VALUES (1,9,1,1)
INSERT #R VALUES (2,9,2,1)
INSERT #R VALUES (3,9,3,1)
INSERT #R VALUES (1,10,1,1)
INSERT #R VALUES (2,10,2,1)
INSERT #R VALUES (3,10,3,1)
INSERT #R VALUES (4,10,4,1)
INSERT #R VALUES (5,10,5,1)
INSERT #R VALUES (1,12,1,1)
INSERT #R VALUES (2,12,3,1)
INSERT #R VALUES (3,12,4,1)
INSERT #R VALUES (4,12,5,1)
INSERT #R VALUES (5,12,6,1)
INSERT #R VALUES (6,12,7,1)
INSERT #R VALUES (7,12,8,1)
INSERT #R VALUES (1,13,1,1)
INSERT #R VALUES (2,13,3,1)
INSERT #R VALUES (3,13,4,1)
INSERT #R VALUES (4,13,5,1)
INSERT #R VALUES (5,13,6,1)
INSERT #R VALUES (1,14,1,1)
INSERT #R VALUES (2,14,3,1)
INSERT #R VALUES (3,14,4,1)
INSERT #R VALUES (4,14,5,1)
INSERT #R VALUES (5,14,6,1)
INSERT #R VALUES (6,14,7,1)
INSERT #R VALUES (7,14,8,1)
INSERT #R VALUES (8,14,9,1)
INSERT #R VALUES (9,14,10,1)
INSERT #R VALUES (10,14,11,1)
INSERT #R VALUES (11,14,12,1)
INSERT #R VALUES (12,14,13,1)
INSERT #R VALUES (13,14,14,1)
INSERT #R VALUES (14,14,15,1)
INSERT #R VALUES (15,14,16,1)
INSERT #R VALUES (16,14,17,1)
INSERT #R VALUES (17,14,18,1)
INSERT #R VALUES (18,14,19,1)
INSERT #R VALUES (19,14,20,1)
INSERT #R VALUES (20,14,21,1)
INSERT #R VALUES (21,14,22,1)
INSERT #R VALUES (22,14,23,1)
INSERT #R VALUES (23,14,24,1)
INSERT #R VALUES (24,14,25,1)
INSERT #R VALUES (25,14,26,1)
INSERT #R VALUES (26,14,27,1)
INSERT #R VALUES (27,14,28,1)
INSERT #R VALUES (28,14,29,1)
INSERT #R VALUES (29,14,30,1)
INSERT #R VALUES (30,14,31,1)
INSERT #R VALUES (31,14,32,1)
INSERT #R VALUES (1,15,1,1)
INSERT #R VALUES (2,15,3,1)
INSERT #R VALUES (3,15,4,1)
INSERT #R VALUES (4,15,5,1)
INSERT #R VALUES (5,15,6,1)
INSERT #R VALUES (6,15,7,1)
INSERT #R VALUES (7,15,8,1)
INSERT #R VALUES (8,15,9,1)
INSERT #R VALUES (9,15,10,1)
INSERT #R VALUES (10,15,11,1)
INSERT #R VALUES (1,16,1,1)
INSERT #R VALUES (2,16,3,1)
INSERT #R VALUES (3,16,4,1)
INSERT #R VALUES (4,16,5,1)
INSERT #R VALUES (5,16,6,1)
INSERT #R VALUES (1,17,1,1)
INSERT #R VALUES (2,17,2,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 156
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,1,1,'Численность работников                                                                                                                                                                                                                                        ')
INSERT #F VALUES (1,2,1,'из них: женщин                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,3,1,'работающих инвалидов                                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,4,1,'работающих, занятых на работах с вредными и (или) опасными производственными факторами                                                                                                                                                                    ')
INSERT #F VALUES (1,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (1,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,4,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,1,3,'4ФСС_09022012_УСТАНОВКА() + 4ФСС_РАЗДЕЛ1(К.СТР.,6)')
INSERT #F VALUES (1,2,3,'4ФСС_РАЗДЕЛ1(К.СТР.,6)')
INSERT #F VALUES (1,3,3,'4ФСС_РАЗДЕЛ1(К.СТР.,6)')
INSERT #F VALUES (1,4,3,'4ФСС_РАЗДЕЛ1(К.СТР.,6)')
INSERT #F VALUES (2,1,1,'Задолженность за страхователем на начало расчетного периода                                                                                                                                                                                               ')
INSERT #F VALUES (2,2,1,'Начислено страховых взносов                                                                                                                                                                                                                               ')
INSERT #F VALUES (2,3,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,4,1,'за отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,5,1,'1 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,6,1,'2 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,7,1,'3 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,8,1,'Начислено страховых взносов по актам проверок                                                                                                                                                                                                             ')
INSERT #F VALUES (2,9,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,10,1,'за отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,11,1,'1 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,12,1,'2 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,13,1,'3 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,14,1,'Начислено страховых взносов страхователем за прошлые годы                                                                                                                                                                                                 ')
INSERT #F VALUES (2,15,1,'Не принято к зачету расходов территориальным органом Фонда                                                                                                                                                                                                ')
INSERT #F VALUES (2,16,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,17,1,'за отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,18,1,'1 месяц')
INSERT #F VALUES (2,19,1,'2 месяц')
INSERT #F VALUES (2,20,1,'3 месяц')
INSERT #F VALUES (2,21,1,'Получено от территориального органа Фонда на банковский счет в возмещение произведенных расходов                                                                                                                                                          ')
INSERT #F VALUES (2,22,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,23,1,'за отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,24,1,'1 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,25,1,'2 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,26,1,'3 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,27,1,'Возврат сумм излишне перечисленных страховых взносов                                                                                                                                                                                                      ')
INSERT #F VALUES (2,28,1,'Всего (стр. 1 - 7)                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,29,1,'Задолженность за территориальным органом Фонда на конец отчетного (расчетного) периода                                                                                                                                                                    ')
INSERT #F VALUES (2,30,1,'в том числе: за счет превышения расходов                                                                                                                                                                                                                  ')
INSERT #F VALUES (2,31,1,'                       за счет переплаты страховых взносов                                                                                                                                                                                                ')
INSERT #F VALUES (2,32,1,'Задолженность за территориальным органом Фонда на начало расчетного периода                                                                                                                                                                               ')
INSERT #F VALUES (2,33,1,'в том числе: за счет превышения расходов                                                                                                                                                                                                                  ')
INSERT #F VALUES (2,34,1,'                       за счет переплаты страховых взносов                                                                                                                                                                                                ')
INSERT #F VALUES (2,35,1,'Расходы на цели обязательного социального страхования                                                                                                                                                                                                     ')
INSERT #F VALUES (2,36,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,37,1,'за отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,38,1,'1 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,39,1,'2 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,40,1,'3 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,41,1,'Перечислены страховые взносы                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,42,1,'на начало квартала                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,43,1,'За отчетный квартал (месяцы)                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,44,1,'1 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,45,1,'2 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,46,1,'3 месяц                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,47,1,'Списано                                                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,48,1,'Всего (стр. 12, 15, 16, 17)                                                                                                                                                                                                                               ')
INSERT #F VALUES (2,49,1,'Задолженность за страхователем на конец отчетного (расчетного) периода                                                                                                                                                                                    ')
INSERT #F VALUES (2,50,1,'в том числе недоимка                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (2,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,3,2,'2_1                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,4,2,'2_2                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,5,2,'2_3                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,6,2,'2_4                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,7,2,'2_5                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,8,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,9,2,'3_1                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,10,2,'3_2                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,11,2,'3_3                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,12,2,'3_4                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,13,2,'3_5                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,14,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,15,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,16,2,'5_1                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,17,2,'5_2                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,18,2,'5_3')
INSERT #F VALUES (2,19,2,'5_4')
INSERT #F VALUES (2,20,2,'5_5')
INSERT #F VALUES (2,21,2,'6                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,22,2,'6_1                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,23,2,'6_2                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,24,2,'6_3                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,25,2,'6_4                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,26,2,'6_5                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (2,27,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,28,2,'8                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (2,29,2,'9                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (2,30,2,'10                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (2,31,2,'11                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,32,2,'12                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (2,33,2,'13                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (2,34,2,'14                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,35,2,'15                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,36,2,'15_1                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,37,2,'15_2                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,38,2,'15_3                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,39,2,'15_4                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,40,2,'15_5                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,41,2,'16                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,42,2,'16_1                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,43,2,'16_2                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,44,2,'16_3                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (2,45,2,'16_4                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (2,46,2,'16_5                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (2,47,2,'17                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,48,2,'18                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,49,2,'19                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (2,50,2,'20                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (2,1,3,'4ФСС_РАЗДЕЛ1(''0101'',3)')
INSERT #F VALUES (2,3,3,'4ФСС_РАЗДЕЛ1(''0121'',3)')
INSERT #F VALUES (2,5,3,'4ФСС_РАЗДЕЛ1(''0123'',3)')
INSERT #F VALUES (2,6,3,'4ФСС_РАЗДЕЛ1(''0124'',3)')
INSERT #F VALUES (2,7,3,'4ФСС_РАЗДЕЛ1(''0125'',3)')
INSERT #F VALUES (2,18,3,'')
INSERT #F VALUES (2,19,3,'')
INSERT #F VALUES (2,20,3,'')
INSERT #F VALUES (2,22,3,'АДТКТ("_.304.05:_.201.11:_.201.21:_.201.27","_.303.02","ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (2,24,3,'АДТКТ("_.304.05:_.201.11:_.201.21:_.201.27","_.303.02","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,25,3,'АДТКТ("_.304.05:_.201.11:_.201.21:_.201.27","_.303.02","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,26,3,'АДТКТ("_.304.05:_.201.11:_.201.21:_.201.27","_.303.02","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,29,3,'4ФСС_РАЗДЕЛ1(''0109'',3)')
INSERT #F VALUES (2,30,3,'4ФСС_РАЗДЕЛ1(''0109'',3)')
INSERT #F VALUES (2,32,3,'4ФСС_РАЗДЕЛ1(''0112'',3)')
INSERT #F VALUES (2,33,3,'4ФСС_РАЗДЕЛ1(''0112'',3)')
INSERT #F VALUES (2,36,3,'АДТКТ("_.303.02","_.302.13","ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (2,38,3,'АДТКТ("_.303.02","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,39,3,'АДТКТ("_.303.02","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,40,3,'АДТКТ("_.303.02","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,42,3,'АДТКТ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (2,44,3,'АДТКТ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,45,3,'АДТКТ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,46,3,'АДТКТ("_.303.02","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,49,3,'4ФСС_РАЗДЕЛ1(''0119'',3)')
INSERT #F VALUES (2,1,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,3,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,4,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,9,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,10,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,12,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,13,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,14,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,15,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,16,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,17,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,18,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,19,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,20,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,21,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,22,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,23,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,24,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,25,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,26,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,27,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,28,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,29,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,30,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,31,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,32,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,33,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,34,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,35,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,36,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,37,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,38,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,39,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,40,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,41,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,42,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,43,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,44,4,'4ФСС_РАЗДЕЛ_ПП1(''01163'',3)')
INSERT #F VALUES (2,45,4,'4ФСС_РАЗДЕЛ_ПП1(''01164'',3)')
INSERT #F VALUES (2,46,4,'4ФСС_РАЗДЕЛ_ПП1(''01165'',3)')
INSERT #F VALUES (2,47,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,48,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,49,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,50,4,'ЗАПРЕТ()')
INSERT #F VALUES (3,1,1,'По временной нетрудоспособности                                                                                                                                                                                                                               ')
INSERT #F VALUES (3,2,1,'      из них: по внешнему совместительству                                                                                                                                                                                                                    ')
INSERT #F VALUES (3,3,1,'По беременности и родам                                                                                                                                                                                                                                       ')
INSERT #F VALUES (3,4,1,'      из них: по внешнему совместительству                                                                                                                                                                                                                    ')
INSERT #F VALUES (3,5,1,'Единовременное пособие женщинам, вставшим на учет в медицинских учреждениях в ранние сроки беременности                                                                                                                                                   ')
INSERT #F VALUES (3,6,1,'Единовременное пособие при рождении ребенка                                                                                                                                                                                                               ')
INSERT #F VALUES (3,7,1,'Ежемесячное пособие по уходу за ребенком                                                                                                                                                                                                                  ')
INSERT #F VALUES (3,8,1,'          в том числе: по уходу за первым ребенком                                                                                                                                                                                                        ')
INSERT #F VALUES (3,9,1,'          по уходу за вторым и последующими детьми                                                                                                                                                                                                        ')
INSERT #F VALUES (3,10,1,'Оплата 4-х дополнительных выходных дней для ухода за детьми-инвалидами                                                                                                                                                                                    ')
INSERT #F VALUES (3,11,1,'Социальное пособие на погребение                                                                                                                                                                                                                          ')
INSERT #F VALUES (3,12,1,'ИТОГО ( сумма строк 1+ 3+ 5+ 6+ 7+ 10+11)                                                                                                                                                                                                                 ')
INSERT #F VALUES (3,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (3,2,2,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (3,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (3,4,2,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (3,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (3,6,2,'6                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (3,7,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (3,8,2,'8                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (3,9,2,'9                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (3,10,2,'10                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (3,11,2,'11                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (3,12,2,'12                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (3,1,3,'4ФСС_РАЗДЕЛ1(''0201'',7)')
INSERT #F VALUES (3,2,3,'4ФСС_РАЗДЕЛ1(''0202'',7)')
INSERT #F VALUES (3,3,3,'4ФСС_РАЗДЕЛ1(''0203'',7)')
INSERT #F VALUES (3,4,3,'4ФСС_РАЗДЕЛ1(''0204'',7)')
INSERT #F VALUES (3,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,8,3,'4ФСС_РАЗДЕЛ1(''0208'',7)')
INSERT #F VALUES (3,9,3,'4ФСС_РАЗДЕЛ1(''0209'',7)')
INSERT #F VALUES (3,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,11,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,12,3,'ЗАПРЕТ()')
INSERT #F VALUES (3,1,4,'4ФСС_РАЗДЕЛ1(''0201'',6)')
INSERT #F VALUES (3,2,4,'4ФСС_РАЗДЕЛ1(''0202'',6)')
INSERT #F VALUES (3,3,4,'4ФСС_РАЗДЕЛ1(''0203'',6)')
INSERT #F VALUES (3,4,4,'4ФСС_РАЗДЕЛ1(''0204'',6)')
INSERT #F VALUES (3,5,4,'4ФСС_РАЗДЕЛ1(''0205'',6) ')
INSERT #F VALUES (3,6,4,'4ФСС_РАЗДЕЛ1(''0206'',6)  ')
INSERT #F VALUES (3,8,4,'4ФСС_РАЗДЕЛ1(''0208'',6)')
INSERT #F VALUES (3,9,4,'4ФСС_РАЗДЕЛ1(''0209'',6)')
INSERT #F VALUES (3,10,4,'4ФСС_РАЗДЕЛ1(''0210'',6)')
INSERT #F VALUES (3,11,4,'4ФСС_РАЗДЕЛ1(''0211'',6)')
INSERT #F VALUES (3,1,5,'4ФСС_РАЗДЕЛ1(''0201'',3)')
INSERT #F VALUES (3,2,5,'4ФСС_РАЗДЕЛ1(''0202'',3)')
INSERT #F VALUES (3,3,5,'4ФСС_РАЗДЕЛ1(''0203'',3)')
INSERT #F VALUES (3,4,5,'4ФСС_РАЗДЕЛ1(''0204'',3)')
INSERT #F VALUES (3,5,5,'4ФСС_РАЗДЕЛ1(''0205'',3) ')
INSERT #F VALUES (3,6,5,'4ФСС_РАЗДЕЛ1(''0206'',3)  ')
INSERT #F VALUES (3,8,5,'4ФСС_РАЗДЕЛ1(''0208'',3)')
INSERT #F VALUES (3,9,5,'4ФСС_РАЗДЕЛ1(''0209'',3)')
INSERT #F VALUES (3,10,5,'4ФСС_РАЗДЕЛ1(''0210'',3)')
INSERT #F VALUES (3,11,5,'4ФСС_РАЗДЕЛ1(''0211'',3)')
INSERT #F VALUES (3,5,6,'ЗАПРЕТ()')
INSERT #F VALUES (3,6,6,'ЗАПРЕТ()')
INSERT #F VALUES (4,1,1,'Суммы выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со ст.7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                           ')
INSERT #F VALUES (4,2,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии со ст.9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                                 ')
INSERT #F VALUES (4,3,1,'Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную в соответствии со ст. 8 Федерального закона от 24                                                                                                             ')
INSERT #F VALUES (4,4,1,'Итого база для начисления страховых взносов  (строка 1 - строка 2 - строка 3)                                                                                                                                                                             ')
INSERT #F VALUES (4,5,1,'из них: сумма выплат и иных вознаграждений физическим лицам, являющимся инвалидами I, II, III группы                                                                                                                                                      ')
INSERT #F VALUES (4,6,1,'Cумма выплат и иных вознаграждений, производимых физическим лицам в связи с осуществлением фармацевтической деятельности                                                                                                                                  ')
INSERT #F VALUES (4,7,1,'Cумма выплат и иных вознаграждений членам экипажей судов, зарегистрированных в Российском международном реестре судов, за исполнение трудовых обязанностей члена экипажа судна                                                                            ')
INSERT #F VALUES (4,8,1,'Cумма выплат и иных вознаграждений,производимых физическим лицам индивидуальными предпринимателями, применяющими патентную систему налогообложения                                                                                                        ')
INSERT #F VALUES (4,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (4,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,4,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (4,5,2,'5                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (4,6,2,'6                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (4,7,2,'7                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (4,8,2,'8                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (4,1,3,'4ФСС_РАЗДЕЛ1(''030103'',3)')
INSERT #F VALUES (4,2,3,'4ФСС_РАЗДЕЛ1(''030203'',3)')
INSERT #F VALUES (4,3,3,'4ФСС_РАЗДЕЛ1(''030303'',3)')
INSERT #F VALUES (4,5,3,'4ФСС_РАЗДЕЛ1(''030503'',3)')
INSERT #F VALUES (4,6,3,'4ФСС_РАЗДЕЛ1(''030603'',3)')
INSERT #F VALUES (4,7,3,'4ФСС_РАЗДЕЛ1(''030703'',3)')
INSERT #F VALUES (4,8,3,'4ФСС_РАЗДЕЛ1(''030803'',3)')
INSERT #F VALUES (4,1,4,'4ФСС_РАЗДЕЛ1(''030104'',3)')
INSERT #F VALUES (4,2,4,'4ФСС_РАЗДЕЛ1(''030204'',3)')
INSERT #F VALUES (4,3,4,'4ФСС_РАЗДЕЛ1(''030304'',3)')
INSERT #F VALUES (4,5,4,'4ФСС_РАЗДЕЛ1(''030504'',3)')
INSERT #F VALUES (4,6,4,'4ФСС_РАЗДЕЛ1(''030604'',3)')
INSERT #F VALUES (4,7,4,'4ФСС_РАЗДЕЛ1(''030704'',3)')
INSERT #F VALUES (4,8,4,'4ФСС_РАЗДЕЛ1(''030804'',3)')
INSERT #F VALUES (4,1,5,'4ФСС_РАЗДЕЛ1(''030105'',3)')
INSERT #F VALUES (4,2,5,'4ФСС_РАЗДЕЛ1(''030205'',3)')
INSERT #F VALUES (4,3,5,'4ФСС_РАЗДЕЛ1(''030305'',3)')
INSERT #F VALUES (4,5,5,'4ФСС_РАЗДЕЛ1(''030505'',3)')
INSERT #F VALUES (4,6,5,'4ФСС_РАЗДЕЛ1(''030605'',3)')
INSERT #F VALUES (4,7,5,'4ФСС_РАЗДЕЛ1(''030705'',3)')
INSERT #F VALUES (4,8,5,'4ФСС_РАЗДЕЛ1(''030805'',3)')
INSERT #F VALUES (4,1,6,'4ФСС_РАЗДЕЛ1(''030106'',3)')
INSERT #F VALUES (4,2,6,'4ФСС_РАЗДЕЛ1(''030206'',3)')
INSERT #F VALUES (4,3,6,'4ФСС_РАЗДЕЛ1(''030306'',3)')
INSERT #F VALUES (4,5,6,'4ФСС_РАЗДЕЛ1(''030506'',3)')
INSERT #F VALUES (4,6,6,'4ФСС_РАЗДЕЛ1(''030606'',3)')
INSERT #F VALUES (4,7,6,'4ФСС_РАЗДЕЛ1(''030706'',3)')
INSERT #F VALUES (4,8,6,'4ФСС_РАЗДЕЛ1(''030806'',3)')
INSERT #F VALUES (6,1,1,'Численность членов организации, всего (чел.)                                                                                                                                                                                                                  ')
INSERT #F VALUES (6,2,1,'     из них: численность инвалидов и их законных представителей (чел.)                                                                                                                                                                                    ')
INSERT #F VALUES (6,3,1,'Удельный вес, % ( стр.2  / стр.1) х 100                                                                                                                                                                                                                   ')
INSERT #F VALUES (6,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (6,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (6,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (7,1,1,'Среднесписочная численность, всего (чел.)                                                                                                                                                                                                                     ')
INSERT #F VALUES (7,2,1,'  из них: среднесписочная численность инвалидов (чел.)                                                                                                                                                                                                        ')
INSERT #F VALUES (7,3,1,'Удельный вес, % (стр. 5 / стр. 4) х 100                                                                                                                                                                                                                       ')
INSERT #F VALUES (7,4,1,'Фонд оплаты труда,
всего (руб.)                                                                                                                                                                                                                              ')
INSERT #F VALUES (7,5,1,'     из него: заработная плата инвалидов (руб.)                                                                                                                                                                                                               ')
INSERT #F VALUES (7,6,1,'Удельный вес заработной платы инвалидов, % (стр. 8 / стр. 7) х 100                                                                                                                                                                                            ')
INSERT #F VALUES (7,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (7,2,2,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (7,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (7,4,2,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (7,5,2,'5                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (7,6,2,'6                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (8,1,1,' Средняя численность работников/среднесписочная численность работников (чел.)                                                                                                                                                                             ')
INSERT #F VALUES (8,2,1,' Сумма доходов, определяемая в соответствии со статьей 248 Налогового кодекса Российской Федерации, всего (руб.)                                                                                                                                          ')
INSERT #F VALUES (8,3,1,'  из них: сумма доходов, определяемая  исходя из критериев, указанных в пункте 2 части 2.1 или пункте 2 части 2.2 статьи  57 Федерального закона от 24 июля 2009 г. № 212-ФЗ (руб.)                                                                           ')
INSERT #F VALUES (8,4,1,'  доля доходов, определяемая в целях применения  части 5 статьи  58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%)
(стр.3 / стр. 2) х 100                                                                                                               ')
INSERT #F VALUES (8,5,1,'Сведения из реестра аккредитованных организаций, осуществляющих деятельность в области информационных технологий*                                                                                                                                             ')
INSERT #F VALUES (8,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (8,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (8,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (8,4,2,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (8,5,2,'5                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (8,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (8,1,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,2,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,3,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,4,5,'ЗАПРЕТ()')
INSERT #F VALUES (8,1,6,'ЗАПРЕТ()')
INSERT #F VALUES (8,2,6,'ЗАПРЕТ()')
INSERT #F VALUES (8,3,6,'ЗАПРЕТ()')
INSERT #F VALUES (8,4,6,'ЗАПРЕТ()')
INSERT #F VALUES (9,1,1,'Сумма доходов, определяемая в соответствии со статьей 346.15 Налогового кодекса Российской Федерации, всего (руб.)                                                                                                                                            ')
INSERT #F VALUES (9,2,1,'  из них: сумма доходов, определяемая в целях применения части 1.4 статьи 58 Федерального закона от 24 июля 2009 г.                                       № 212-ФЗ (руб.)                                                                                     ')
INSERT #F VALUES (9,3,1,'Доля доходов, определяемая в целях применения части 1.4 статьи 58 Федерального закона от 24 июля 2009 г.                                                              № 212-ФЗ (%)
(стр. 2 / стр. 1) х 100                                                   ')
INSERT #F VALUES (9,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (9,2,2,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (9,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,1,1,'Сумма доходов*, всего (руб.)                                                                                                                                                                                                                                  ')
INSERT #F VALUES (10,2,1,'из них: сумма доходов в виде целевых поступлений на содержание некоммерческих организаций и ведение ими уставной деятельности, поименованной в пункте 11 части 1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                    ')
INSERT #F VALUES (10,3,1,'сумма доходов в виде грантов, получаемых для осуществления деятельности, поименованной в пункте 11 части 1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                          ')
INSERT #F VALUES (10,4,1,'сумма доходов от осуществления видов экономической деятельности, указанных в подпунктах р - ф, я.4 - я.6 пункта 8 части 1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (руб.)                                                                    ')
INSERT #F VALUES (10,5,1,'Доля доходов, определяемая в целях применения части 5.1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%)
((с. 2 + с. 3 + с.4) / с. 1) х 100                                                                                                     ')
INSERT #F VALUES (10,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,2,2,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,4,2,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,5,2,'5                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,1,1,'Пособие по временной нетрудоспособности                                                                                                                                                                                                                   ')
INSERT #F VALUES (12,2,1,'Пособие по беременности и родам                                                                                                                                                                                                                           ')
INSERT #F VALUES (12,3,1,'Ежемесячное пособие по уходу за ребенком, всего (стр. 4, 5)                                                                                                                                                                                               ')
INSERT #F VALUES (12,4,1,'в том числе: по уходу за первым ребенком                                                                                                                                                                                                                      ')
INSERT #F VALUES (12,5,1,'по уходу за вторым и 
последующими детьми                                                                                                                                                                                                                ')
INSERT #F VALUES (12,6,1,'Социальное пособие на погребение или возмещение стоимости гарантированного перечня услуг по погребению                                                                                                                                                    ')
INSERT #F VALUES (12,7,1,'ВСЕГО (строки 1 - 3, 6)                                                                                                                                                                                                                                   ')
INSERT #F VALUES (12,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,4,2,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,6,2,'6                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,7,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (12,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (12,7,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,7,10,'ЗАПРЕТ()')
INSERT #F VALUES (12,2,12,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,12,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,12,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,12,'ЗАПРЕТ()')
INSERT #F VALUES (12,6,12,'ЗАПРЕТ()')
INSERT #F VALUES (12,2,13,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,13,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,13,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,13,'ЗАПРЕТ()')
INSERT #F VALUES (12,6,13,'ЗАПРЕТ()')
INSERT #F VALUES (12,7,13,'ЗАПРЕТ()')
INSERT #F VALUES (12,2,14,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,14,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,14,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,14,'ЗАПРЕТ()')
INSERT #F VALUES (12,6,14,'ЗАПРЕТ()')
INSERT #F VALUES (12,7,16,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,18,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,18,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,18,'ЗАПРЕТ()')
INSERT #F VALUES (12,6,18,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,19,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,19,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,19,'ЗАПРЕТ()')
INSERT #F VALUES (12,6,19,'ЗАПРЕТ()')
INSERT #F VALUES (12,7,19,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,20,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,20,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,20,'ЗАПРЕТ()')
INSERT #F VALUES (12,6,20,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,1,'Всего с начала расчетного  периода                                                                                                                                                                                                                        ')
INSERT #F VALUES (13,2,1,'    В том числе за последние три месяца отчетного периода                                                                                                                                                                                                 ')
INSERT #F VALUES (13,3,1,'       В том числе за 1 месяц                                                                                                                                                                                                                             ')
INSERT #F VALUES (13,4,1,'       В том числе за 2 месяц                                                                                                                                                                                                                             ')
INSERT #F VALUES (13,5,1,'       В том числе за 3 месяц                                                                                                                                                                                                                             ')
INSERT #F VALUES (13,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,4,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,1,3,'4ФСС_РАЗДЕЛ1(''060103'',3)')
INSERT #F VALUES (13,3,3,'4ФСС_РАЗДЕЛ1(''060303'',3)')
INSERT #F VALUES (13,4,3,'4ФСС_РАЗДЕЛ1(''060403'',3)')
INSERT #F VALUES (13,5,3,'4ФСС_РАЗДЕЛ1(''060503'',3)')
INSERT #F VALUES (13,1,4,'4ФСС_РАЗДЕЛ1(''060104'',3)')
INSERT #F VALUES (13,3,4,'4ФСС_РАЗДЕЛ1(''060304'',3)')
INSERT #F VALUES (13,4,4,'4ФСС_РАЗДЕЛ1(''060404'',3)')
INSERT #F VALUES (13,5,4,'4ФСС_РАЗДЕЛ1(''060504'',3)')
INSERT #F VALUES (13,1,5,'4ФСС_РАЗДЕЛ1(''060105'',3)')
INSERT #F VALUES (13,3,5,'4ФСС_РАЗДЕЛ1(''060305'',3)')
INSERT #F VALUES (13,4,5,'4ФСС_РАЗДЕЛ1(''060405'',3)')
INSERT #F VALUES (13,5,5,'4ФСС_РАЗДЕЛ1(''060505'',3)')
INSERT #F VALUES (13,1,6,'4ФСС_СПРАВОЧНИК(''tax_rate'')')
INSERT #F VALUES (13,2,6,'ЗАПРЕТ()')
INSERT #F VALUES (13,3,6,'ЗАПРЕТ()')
INSERT #F VALUES (13,4,6,'ЗАПРЕТ()')
INSERT #F VALUES (13,5,6,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,7,'4ФСС_СПРАВОЧНИК(''discount'')')
INSERT #F VALUES (13,2,7,'ЗАПРЕТ()')
INSERT #F VALUES (13,3,7,'ЗАПРЕТ()')
INSERT #F VALUES (13,4,7,'ЗАПРЕТ()')
INSERT #F VALUES (13,5,7,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,8,'4ФСС_СПРАВОЧНИК(''raise_date'')')
INSERT #F VALUES (13,2,8,'ЗАПРЕТ()')
INSERT #F VALUES (13,3,8,'ЗАПРЕТ()')
INSERT #F VALUES (13,4,8,'ЗАПРЕТ()')
INSERT #F VALUES (13,5,8,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,9,'4ФСС_СПРАВОЧНИК(''raise_val'')')
INSERT #F VALUES (13,2,9,'ЗАПРЕТ()')
INSERT #F VALUES (13,3,9,'ЗАПРЕТ()')
INSERT #F VALUES (13,4,9,'ЗАПРЕТ()')
INSERT #F VALUES (13,5,9,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,10,'4ФСС_СПРАВОЧНИК(''tax_total'')')
INSERT #F VALUES (13,2,10,'ЗАПРЕТ()')
INSERT #F VALUES (13,3,10,'ЗАПРЕТ()')
INSERT #F VALUES (13,4,10,'ЗАПРЕТ()')
INSERT #F VALUES (13,5,10,'ЗАПРЕТ()')
INSERT #F VALUES (14,1,1,'Задолженность за страхователем на начало расчетного периода                                                                                                                                                                                               ')
INSERT #F VALUES (14,2,1,'Начислено страховых взносов                                                                                                                                                                                                                               ')
INSERT #F VALUES (14,3,1,'на начало отчетного периода                                                                                                                                                                                                                               ')
INSERT #F VALUES (14,4,1,'за последние три месяца отчетного периода                                                                                                                                                                                                                 ')
INSERT #F VALUES (14,5,1,'          1 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,6,1,'          2 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,7,1,'          3 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,8,1,'Начислено взносов по результатам проверок                                                                                                                                                                                                                 ')
INSERT #F VALUES (14,9,1,'Не принято к зачету расходов территориальным органом Фонда за прошлые расчетные периоды                                                                                                                                                                   ')
INSERT #F VALUES (14,10,1,'Начислено взносов страхователем за прошлые расчетные периоды                                                                                                                                                                                              ')
INSERT #F VALUES (14,11,1,'Получено от территориального органа Фонда на банковский счет                                                                                                                                                                                              ')
INSERT #F VALUES (14,12,1,'Возврат сумм излишне уплаченных (взысканных) страховых взносов                                                                                                                                                                                            ')
INSERT #F VALUES (14,13,1,'Всего  (сумма строк 1+2+3+4+5+6+7)                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,14,1,'Задолженность за территориальным органом Фонда на конец отчетного периода                                                                                                                                                                                 ')
INSERT #F VALUES (14,15,1,'Задолженность за территориальным органом Фонда на начало расчетного периода                                                                                                                                                                               ')
INSERT #F VALUES (14,16,1,'Расходы по обязательному социальному страхованию                                                                                                                                                                                                          ')
INSERT #F VALUES (14,17,1,'на начало отчетного периода                                                                                                                                                                                                                               ')
INSERT #F VALUES (14,18,1,'за последние три месяца отчетного периода                                                                                                                                                                                                                 ')
INSERT #F VALUES (14,19,1,'          1 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,20,1,'          2 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,21,1,'          3 месяц                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,22,1,'Уплачено страховых взносов                                                                                                                                                                                                                                ')
INSERT #F VALUES (14,23,1,'на начало отчетного периода                                                                                                                                                                                                                               ')
INSERT #F VALUES (14,24,1,'за последние три месяца отчетного периода дата, № платежного  поручения                                                                                                                                                                                   ')
INSERT #F VALUES (14,25,1,'          1 месяц                                                                                                                                                                                                                                             ')
INSERT #F VALUES (14,26,1,'          2 месяц                                                                                                                                                                                                                                             ')
INSERT #F VALUES (14,27,1,'          3 месяц                                                                                                                                                                                                                                             ')
INSERT #F VALUES (14,28,1,'Списанная сумма задолженности страхователя                                                                                                                                                                                                                ')
INSERT #F VALUES (14,29,1,'Всего (сумма строк 10+11+12+13                                                                                                                                                                                                                            ')
INSERT #F VALUES (14,30,1,'Задолженность за страхователем на конец отчетного периода                                                                                                                                                                                                 ')
INSERT #F VALUES (14,31,1,'           в том числе недоимка                                                                                                                                                                                                                           ')
INSERT #F VALUES (14,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,3,2,'2_1                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (14,4,2,'2_2                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (14,5,2,'2_3                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (14,6,2,'2_4                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (14,7,2,'2_5                                                                                                                                                                                                                                                       ')
INSERT #F VALUES (14,8,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,9,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,10,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,11,2,'6                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,12,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,13,2,'8                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,14,2,'9                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (14,15,2,'10                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,16,2,'11                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,17,2,'11_1                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,18,2,'11_2                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,19,2,'11_3                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,20,2,'11_4                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,21,2,'11_5                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,22,2,'12                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,23,2,'12_1                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,24,2,'12_2                                                                                                                                                                                                                                                      ')
INSERT #F VALUES (14,25,2,'12_3                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (14,26,2,'12_4                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (14,27,2,'12_5                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (14,28,2,'13                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,29,2,'14                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,30,2,'15                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,31,2,'16                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (14,1,3,'КТСН("_.303.06","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (14,3,3,'4ФСС_РАЗДЕЛ1(''1021'',3)')
INSERT #F VALUES (14,5,3,'4ФСС_РАЗДЕЛ1(''1023'',3)')
INSERT #F VALUES (14,6,3,'4ФСС_РАЗДЕЛ1(''1024'',3)')
INSERT #F VALUES (14,7,3,'4ФСС_РАЗДЕЛ1(''1025'',3)')
INSERT #F VALUES (14,11,3,'АДТКТ("_.304.05:_.201.11:_.201.21:_.201.27","_.303.06")')
INSERT #F VALUES (14,17,3,'АДТКТ("_.303.06","_.302.13,"ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (14,19,3,'АДТКТ("_.303.06","_.302.13,"ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (14,20,3,'АДТКТ("_.303.06","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (14,21,3,'АДТКТ("_.303.06","_.302.13","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (14,23,3,'АДТКТ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА>=''01.01'' И ДАТА<КВАРТАЛ")')
INSERT #F VALUES (14,25,3,'АДТКТ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (14,26,3,'АДТКТ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (14,27,3,'АДТКТ("_.303.06","_.304.05:_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (14,30,3,'КТСК("_.303.06")')
INSERT #F VALUES (14,1,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,3,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,4,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,6,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,7,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,8,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,9,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,10,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,11,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,12,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,13,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,14,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,15,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,16,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,17,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,18,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,19,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,20,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,21,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,22,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,23,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,24,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,25,4,'4ФСС_РАЗДЕЛ_ПП1(''10123'',3)')
INSERT #F VALUES (14,26,4,'4ФСС_РАЗДЕЛ_ПП1(''10124'',3)')
INSERT #F VALUES (14,27,4,'4ФСС_РАЗДЕЛ_ПП1(''10125'',3)')
INSERT #F VALUES (14,28,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,29,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,30,4,'ЗАПРЕТ()')
INSERT #F VALUES (14,31,4,'ЗАПРЕТ()')
INSERT #F VALUES (15,1,1,'Пособия по временной нетрудоспособности в связи
с несчастными случаями на производстве, всего                                                                                                                                                            ')
INSERT #F VALUES (15,2,1,'      из них: по внешнему совместительству                                                                                                                                                                                                                ')
INSERT #F VALUES (15,3,1,'      пострадавшим в другой организации                                                                                                                                                                                                                       ')
INSERT #F VALUES (15,4,1,'Пособия по временной нетрудоспособности в связи
с профессиональными заболеваниями, всего                                                                                                                                                                 ')
INSERT #F VALUES (15,5,1,'      из них: по внешнему совместительству                                                                                                                                                                                                                ')
INSERT #F VALUES (15,6,1,'      пострадавшим в другой организации                                                                                                                                                                                                                       ')
INSERT #F VALUES (15,7,1,'Оплата отпуска для санаторно-курортного лечения застрахованным (сверх ежегодного оплачиваемого отпуска, установленного законодательством Российской Федерации)                                                                                            ')
INSERT #F VALUES (15,8,1,'      из них: пострадавшим в другой организации                                                                                                                                                                                                               ')
INSERT #F VALUES (15,9,1,'Финансирование предупредительных мер по сокращению производственного травматизма и профзаболеваний                                                                                                                                                        ')
INSERT #F VALUES (15,10,1,'Всего расходов (сумма строк 1, 4, 7, 9)                                                                                                                                                                                                                   ')
INSERT #F VALUES (15,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (15,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (15,3,2,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (15,4,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (15,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (15,6,2,'6                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (15,7,2,'7                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (15,8,2,'8                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (15,9,2,'9                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (15,10,2,'10                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (15,1,3,'4ФСС_РАЗДЕЛ1(''1101'',6)')
INSERT #F VALUES (15,2,3,'4ФСС_РАЗДЕЛ1(''1102'',6)')
INSERT #F VALUES (15,4,3,'4ФСС_РАЗДЕЛ1(''1104'',6)')
INSERT #F VALUES (15,5,3,'4ФСС_РАЗДЕЛ1(''1105'',6)')
INSERT #F VALUES (15,7,3,'4ФСС_РАЗДЕЛ1(''1107'',6)')
INSERT #F VALUES (15,9,3,'ЗАПРЕТ()')
INSERT #F VALUES (15,10,3,'ЗАПРЕТ()')
INSERT #F VALUES (15,1,4,'4ФСС_РАЗДЕЛ1(''1101'',3)')
INSERT #F VALUES (15,2,4,'4ФСС_РАЗДЕЛ1(''1102'',3)')
INSERT #F VALUES (15,4,4,'4ФСС_РАЗДЕЛ1(''1104'',3)')
INSERT #F VALUES (15,5,4,'4ФСС_РАЗДЕЛ1(''1105'',3)')
INSERT #F VALUES (15,7,4,'4ФСС_РАЗДЕЛ1(''1107'',3)')
INSERT #F VALUES (16,1,1,'По несчастным случаям                                                                                                                                                                                                                                     ')
INSERT #F VALUES (16,2,1,'      из них: со смертельным исходом                                                                                                                                                                                                                      ')
INSERT #F VALUES (16,3,1,'По профессиональным заболеваниям                                                                                                                                                                                                                          ')
INSERT #F VALUES (16,4,1,'ВСЕГО пострадавших (сумма строк 1, 3)                                                                                                                                                                                                                     ')
INSERT #F VALUES (16,5,1,'в том числе пострадавших (застрахованных) по случаям, закончившимся только временной нетрудоспособностью                                                                                                                                                  ')
INSERT #F VALUES (16,1,2,'1                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (16,2,2,'2                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (16,3,2,'3                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (16,4,2,'4                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (16,5,2,'5                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (17,1,1,'Аттестация рабочих мест по условиям труда                                                                                                                                                                                                                     ')
INSERT #F VALUES (17,2,1,'Проведение обязательных предварительных и периодических медицинских осмотров (обследований) работников                                                                                                                                                        ')
INSERT #F VALUES (17,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (17,2,2,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (17,1,3,'4ФСС_РАЗДЕЛ1(''100103'',3)')
INSERT #F VALUES (17,2,3,'ЗАПРЕТ()')
INSERT #F VALUES (17,1,4,'4ФСС_РАЗДЕЛ1(''100104'',3)')
INSERT #F VALUES (17,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (17,1,6,'4ФСС_РАЗДЕЛ1(''100105'',3)')
INSERT #F VALUES (17,2,6,'ЗАПРЕТ()')
INSERT #F VALUES (17,1,7,'4ФСС_РАЗДЕЛ1(''100106'',3)')
INSERT #F VALUES (17,2,7,'ЗАПРЕТ()')
INSERT #F VALUES (17,1,8,'ЗАПРЕТ()')
INSERT #F VALUES (17,1,9,'ЗАПРЕТ()')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 599
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'т.2стр.2_2гр.3 =  т.2стр.2_3гр.3 +  т.2стр.2_4гр.3 +  т.2стр.2_5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(2,NULL,0,NULL,2,7,0,0,0,'т.2стр.3_2гр.3 =  т.2стр.3_3гр.3 +  т.2стр.3_4гр.3 +  т.2стр.3_5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(3,NULL,0,NULL,3,7,0,0,0,'т.2стр.5_2гр.3 =  т.2стр.5_3гр.3 +  т.2стр.5_4гр.3 +  т.2стр.5_5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(4,NULL,0,NULL,4,7,0,0,0,'т.2стр.6_2гр.3 =  т.2стр.6_3гр.3 +  т.2стр.6_4гр.3 +  т.2стр.6_5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(5,NULL,0,NULL,5,7,0,0,0,'т.2стр.15_2гр.3 =  т.2стр.15_3гр.3 +  т.2стр.15_4гр.3 +  т.2стр.15_5гр.3',1,0,1,'20140409','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(6,NULL,0,NULL,6,7,0,0,0,'т.2стр.16_2гр.3 =  т.2стр.16_3гр.3 +  т.2стр.16_4гр.3 +  т.2стр.16_5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(7,NULL,0,NULL,7,7,0,0,0,'т.2стр.15гр.3 =  т.3стр.12гр.4',0,0,1,'20140409','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(8,NULL,0,NULL,8,7,0,0,0,'т.4стр.4гр.3 =  т.4стр.1гр.3 -  т.4стр.2гр.3 -  т.4стр.3гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(9,NULL,0,NULL,9,7,0,0,0,'т.4стр.4гр.4 =  т.4стр.1гр.4 -  т.4стр.2гр.4 -  т.4стр.3гр.4',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(10,NULL,0,NULL,10,7,0,0,0,'т.4стр.4гр.5 =  т.4стр.1гр.5 -  т.4стр.2гр.5 -  т.4стр.3гр.5',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(11,NULL,0,NULL,11,7,0,0,0,'т.4стр.4гр.6 =  т.4стр.1гр.6 -  т.4стр.2гр.6 -  т.4стр.3гр.6',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(12,NULL,0,NULL,12,7,0,0,0,'т.6стр.1гр.3 =  т.6стр.1гр.6',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(13,NULL,0,NULL,13,7,0,0,0,'т.6стр.2гр.3 =  т.6стр.2гр.6',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(14,NULL,0,NULL,14,7,0,0,0,'т.6стр.3гр.3 =  т.6стр.2гр.3 /  т.6стр.1гр.3 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(15,NULL,0,NULL,15,7,0,0,0,'т.6стр.3гр.4 =  т.6стр.2гр.4 /  т.6стр.1гр.4 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(16,NULL,0,NULL,16,7,0,0,0,'т.6стр.3гр.5 =  т.6стр.2гр.5 /  т.6стр.1гр.5 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(17,NULL,0,NULL,17,7,0,0,0,'т.6стр.3гр.6 =  т.6стр.2гр.6 /  т.6стр.1гр.6 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(18,NULL,0,NULL,18,7,0,0,0,'т.7стр.1гр.3 =  т.7стр.1гр.6',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(19,NULL,0,NULL,19,7,0,0,0,'т.7стр.2гр.3 =  т.7стр.2гр.6',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(20,NULL,0,NULL,20,7,0,0,0,'т.7стр.3гр.3 =  т.7стр.2гр.3 /  т.7стр.1гр.3 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(21,NULL,0,NULL,21,7,0,0,0,'т.7стр.3гр.4 =  т.7стр.2гр.4 /  т.7стр.1гр.4 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(22,NULL,0,NULL,22,7,0,0,0,'т.7стр.3гр.5 =  т.7стр.2гр.5 /  т.7стр.1гр.5 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(23,NULL,0,NULL,23,7,0,0,0,'т.7стр.3гр.6 =  т.7стр.2гр.6 /  т.7стр.1гр.6 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(24,NULL,0,NULL,24,7,0,0,0,'т.7стр.6гр.3 =  т.7стр.5гр.3 /  т.7стр.4гр.3 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(25,NULL,0,NULL,25,7,0,0,0,'т.7стр.6гр.4 =  т.7стр.5гр.4 /  т.7стр.4гр.4 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(26,NULL,0,NULL,26,7,0,0,0,'т.7стр.6гр.5 =  т.7стр.5гр.5 /  т.7стр.4гр.5 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(27,NULL,0,NULL,27,7,0,0,0,'т.7стр.6гр.6 =  т.7стр.5гр.6 /  т.7стр.4гр.6 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(28,NULL,0,NULL,28,7,0,0,0,'т.8стр.4гр.3 =  т.8стр.3гр.3 /  т.8стр.2гр.3 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(29,NULL,0,NULL,29,7,0,0,0,'т.12стр.1гр.5 =  т.3стр.1гр.5',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(30,NULL,0,NULL,30,7,0,0,0,'т.12стр.2гр.5 =  т.3стр.3гр.5',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(31,NULL,0,NULL,31,7,0,0,0,'т.12стр.4гр.5 =  т.3стр.8гр.5',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(32,NULL,0,NULL,32,7,0,0,0,'т.12стр.5гр.5 =  т.3стр.9гр.5',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(33,NULL,0,NULL,33,7,0,0,0,'т.12стр.6гр.5 =  т.3стр.11гр.5',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(34,NULL,0,NULL,34,7,0,0,0,'т.13стр.2гр.3 =  т.13стр.3гр.3 +  т.13стр.4гр.3 +  т.13стр.5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(35,NULL,0,NULL,35,7,0,0,0,'т.13стр.2гр.4 =  т.13стр.3гр.4 +  т.13стр.4гр.4 +  т.13стр.5гр.4',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(36,NULL,0,NULL,36,7,0,0,0,'т.13стр.2гр.5 =  т.13стр.3гр.5 +  т.13стр.4гр.5 +  т.13стр.5гр.5',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(37,NULL,0,NULL,37,7,0,0,0,'т.14стр.2_2гр.3 =  т.14стр.2_3гр.3 +  т.14стр.2_4гр.3 +  т.14стр.2_5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(38,NULL,0,NULL,38,7,0,0,0,'т.14стр.11_2гр.3 =  т.14стр.11_3гр.3 +  т.14стр.11_4гр.3 +  т.14стр.11_5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(39,NULL,0,NULL,39,7,0,0,0,'т.14стр.12_2гр.3 =  т.14стр.12_3гр.3 +  т.14стр.12_4гр.3 +  т.14стр.12_5гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(40,NULL,0,NULL,40,7,0,0,0,'т.15стр.10гр.4 =  т.15стр.1гр.4 +  т.15стр.4гр.4 +  т.15стр.7гр.4 +  т.15стр.9гр.4',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(41,NULL,0,NULL,41,7,0,0,0,'т.16стр.4гр.3 =  т.16стр.1гр.3 +  т.16стр.3гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(42,NULL,0,NULL,42,7,0,0,0,'т.13гр.3 =  -  т.13гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(43,NULL,0,NULL,43,7,0,0,0,'т.13гр.3 =  -  т.13гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(44,NULL,0,NULL,44,7,0,0,0,'т.3стр.7гр.2 =  т.3стр.8гр.2 +  т.3стр.9гр.2',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(45,NULL,0,NULL,45,7,0,0,0,'т.3стр.7гр.3 =  т.3стр.8гр.3 +  т.3стр.9гр.3',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(46,NULL,0,NULL,46,7,0,0,0,'т.3стр.7гр.4 =  т.3стр.8гр.4 +  т.3стр.9гр.4',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(47,NULL,0,NULL,47,7,0,0,0,'т.3стр.7гр.5 =  т.3стр.8гр.5 +  т.3стр.9гр.5',1,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(48,NULL,0,NULL,48,7,0,0,0,'т.1стр.2гр.3 <=  т.1стр.1гр.3',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(49,NULL,0,NULL,49,7,0,0,0,'т.1стр.3гр.3 <=  т.1стр.1гр.3',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(50,NULL,0,NULL,50,7,0,0,0,'т.1стр.4гр.3 <=  т.1стр.1гр.3',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(51,NULL,0,NULL,51,7,0,0,0,'т.3стр.2гр.2 <=  т.3стр.1гр.2',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(52,NULL,0,NULL,52,7,0,0,0,'т.3стр.2гр.3 <=  т.3стр.1гр.3',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(53,NULL,0,NULL,53,7,0,0,0,'т.3стр.2гр.4 <=  т.3стр.1гр.4',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(54,NULL,0,NULL,54,7,0,0,0,'т.3стр.2гр.5 <=  т.3стр.1гр.5',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(55,NULL,0,NULL,55,7,0,0,0,'т.3стр.4гр.3 <=  т.3стр.3гр.3',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(56,NULL,0,NULL,56,7,0,0,0,'т.3стр.4гр.4 <=  т.3стр.3гр.4',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(57,NULL,0,NULL,57,7,0,0,0,'т.3стр.4гр.5 <=  т.3стр.3гр.5',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(58,NULL,0,NULL,58,7,0,0,0,'т.4стр.1гр.3 >=  т.4стр.1гр.4 +  т.4стр.1гр.5 +  т.4стр.1гр.6',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(59,NULL,0,NULL,59,7,0,0,0,'т.4стр.2гр.3 >=  т.4стр.2гр.4 +  т.4стр.2гр.5 +  т.4стр.2гр.6',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(60,NULL,0,NULL,60,7,0,0,0,'т.4стр.3гр.3 >=  т.4стр.3гр.4 +  т.4стр.3гр.5 +  т.4стр.3гр.6',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(61,NULL,0,NULL,61,7,0,0,0,'т.4стр.4гр.3 >=  т.4стр.4гр.4 +  т.4стр.4гр.5 +  т.4стр.4гр.6',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(62,NULL,0,NULL,62,7,0,0,0,'т.4стр.5гр.3 >=  т.4стр.5гр.4 +  т.4стр.5гр.5 +  т.4стр.5гр.6',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(63,NULL,0,NULL,63,7,0,0,0,'т.4стр.5гр.3 <=  т.4стр.4гр.3',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(64,NULL,0,NULL,64,7,0,0,0,'т.4стр.5гр.4 <=  т.4стр.4гр.4',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(65,NULL,0,NULL,65,7,0,0,0,'т.4стр.5гр.5 <=  т.4стр.4гр.5',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(66,NULL,0,NULL,66,7,0,0,0,'т.4стр.5гр.6 <=  т.4стр.4гр.6',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(67,NULL,0,NULL,67,7,0,0,0,'т.13стр.1гр.4 <=  т.13стр.1гр.3',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(68,NULL,0,NULL,68,7,0,0,0,'т.14стр.16гр.3 <=  т.14стр.15гр.3',0,0,1,'20140401','','','','4fss','20140101','','<=',1,'','')
INSERT #A VALUES(69,NULL,0,NULL,69,7,0,0,0,'т.14стр.11гр.3 =  т.15стр.10гр.4',0,0,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(70,NULL,0,NULL,70,7,0,0,0,'т.15стр.1гр.3 >=  т.15стр.2гр.3 +  т.15стр.3гр.3',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(71,NULL,0,NULL,71,7,0,0,0,'т.15стр.1гр.4 >=  т.15стр.2гр.4 +  т.15стр.3гр.4',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(72,NULL,0,NULL,72,7,0,0,0,'т.15стр.4гр.3 >=  т.15стр.5гр.3 +  т.15стр.6гр.3',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(73,NULL,0,NULL,73,7,0,0,0,'т.15стр.4гр.4 >=  т.15стр.5гр.4 +  т.15стр.6гр.4',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(74,NULL,0,NULL,74,7,0,0,0,'т.15стр.7гр.3 >=  т.15стр.8гр.3',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(75,NULL,0,NULL,75,7,0,0,0,'т.15стр.7гр.4 >=  т.15стр.8гр.4',0,0,1,'20140401','','','','4fss','20140101','','>=',1,'','')
INSERT #A VALUES(76,NULL,0,NULL,76,7,0,0,0,'т.8стр.4гр.4 =  т.8стр.3гр.4 /  т.8стр.2гр.4 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(77,NULL,0,NULL,77,7,0,0,0,'т.9стр.3гр.3 =  т.9стр.2гр.3 /  т.9стр.1гр.3 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(78,NULL,0,NULL,78,7,0,0,0,'т.10стр.5гр.3 =  т.10стр.4гр.3 +  т.10стр.3гр.3 +  т.10стр.2гр.3 /  т.10стр.1гр.3 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(79,NULL,0,NULL,79,7,0,0,0,'т.10стр.5гр.4 =  т.10стр.4гр.4 +  т.10стр.3гр.4 +  т.10стр.2гр.4 /  т.10стр.1гр.4 *  100',1,0,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(80,NULL,0,NULL,80,7,0,0,0,'т.3стр.12гр.4 =  т.3стр.1гр.4 +  т.3стр.3гр.4 +  т.3стр.5гр.4 +  т.3стр.6гр.4 +  т.3стр.7гр.4 +  т.3стр.10гр.4 +  т.3стр.11гр.4',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(81,NULL,0,NULL,81,7,0,0,0,'т.3стр.12гр.5 =  т.3стр.1гр.5 +  т.3стр.3гр.5 +  т.3стр.5гр.5 +  т.3стр.6гр.5 +  т.3стр.7гр.5 +  т.3стр.10гр.5 +  т.3стр.11гр.5',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(82,NULL,0,NULL,82,7,0,0,0,'т.12стр.3гр.5 =  т.12стр.4гр.5 +  т.12стр.5гр.5',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(83,NULL,0,NULL,83,7,0,0,0,'т.14стр.2гр.3 =  т.14стр.2_1гр.3 +  т.14стр.2_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(84,NULL,0,NULL,84,7,0,0,0,'т.14стр.11гр.3 =  т.14стр.11_1гр.3 +  т.14стр.11_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(85,NULL,0,NULL,85,7,0,0,0,'т.14стр.12гр.3 =  т.14стр.12_1гр.3 +  т.14стр.12_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(86,NULL,0,NULL,86,7,0,0,0,'т.14гр.3 =  т.14гр.3 -  т.14гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(87,NULL,0,NULL,87,7,0,0,0,'т.14гр.3 =  т.14гр.3 -  т.14гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(88,NULL,0,NULL,88,7,0,0,0,'т.2стр.2гр.3 =  т.2стр.2_1гр.3 +  т.2стр.2_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(89,NULL,0,NULL,89,7,0,0,0,'т.2стр.3гр.3 =  т.2стр.3_1гр.3 +  т.2стр.3_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(90,NULL,0,NULL,90,7,0,0,0,'т.2стр.5гр.3 =  т.2стр.5_1гр.3 +  т.2стр.5_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(91,NULL,0,NULL,91,7,0,0,0,'т.2стр.6гр.3 =  т.2стр.6_1гр.3 +  т.2стр.6_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(92,NULL,0,NULL,92,7,0,0,0,'т.2стр.15гр.3 =  т.2стр.15_1гр.3 +  т.2стр.15_2гр.3',1,1,1,'20140409','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(93,NULL,0,NULL,93,7,0,0,0,'т.2стр.16гр.3 =  т.2стр.16_1гр.3 +  т.2стр.16_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(94,NULL,0,NULL,95,7,0,0,0,'т.3стр.12гр.4 =  т.3стр.1гр.4 +  т.3стр.3гр.4 +  т.3стр.5гр.4 +  т.3стр.6гр.4 +  т.3стр.7гр.4 +  т.3стр.10гр.4 +  т.3стр.11гр.4',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(95,NULL,0,NULL,96,7,0,0,0,'т.3стр.12гр.5 =  т.3стр.1гр.5 +  т.3стр.3гр.5 +  т.3стр.5гр.5 +  т.3стр.6гр.5 +  т.3стр.7гр.5 +  т.3стр.10гр.5 +  т.3стр.11гр.5',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(96,NULL,0,NULL,97,7,0,0,0,'т.12стр.3гр.5 =  т.12стр.4гр.5 +  т.12стр.5гр.5',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(97,NULL,0,NULL,98,7,0,0,0,'т.14стр.2гр.3 =  т.14стр.2_1гр.3 +  т.14стр.2_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(98,NULL,0,NULL,99,7,0,0,0,'т.14стр.11гр.3 =  т.14стр.11_1гр.3 +  т.14стр.11_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(99,NULL,0,NULL,100,7,0,0,0,'т.14стр.12гр.3 =  т.14стр.12_1гр.3 +  т.14стр.12_2гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(100,NULL,0,NULL,101,7,0,0,0,'т.14гр.3 =  т.14гр.3 -  т.14гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(101,NULL,0,NULL,102,7,0,0,0,'т.14гр.3 =  т.14гр.3 -  т.14гр.3',1,1,1,'20140401','','','','4fss','20140101','','=',0,'','')
INSERT #A VALUES(102,NULL,0,NULL,103,7,0,0,0,'т.2стр.8гр.3 =  т.2стр.1гр.3 +  т.2стр.2гр.3 +  т.2стр.3гр.3 +  т.2стр.4гр.3 +  т.2стр.5гр.3 +  т.2стр.6гр.3 +  т.2стр.7гр.3',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(103,NULL,0,NULL,104,7,0,0,0,'т.2стр.18гр.3 =  т.2стр.12гр.3 +  т.2стр.15гр.3 +  т.2стр.16гр.3 +  т.2стр.17гр.3',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(104,NULL,0,NULL,105,7,0,0,0,'т.12стр.7гр.3 =  т.12стр.1гр.3 +  т.12стр.2гр.3 +  т.12стр.3гр.3 +  т.12стр.6гр.3',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(105,NULL,0,NULL,106,7,0,0,0,'т.12стр.7гр.5 =  т.12стр.1гр.5 +  т.12стр.2гр.5 +  т.12стр.3гр.5 +  т.12стр.6гр.5',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(106,NULL,0,NULL,107,7,0,0,0,'т.12стр.7гр.6 =  т.12стр.1гр.6 +  т.12стр.2гр.6 +  т.12стр.3гр.6 +  т.12стр.6гр.6',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(107,NULL,0,NULL,108,7,0,0,0,'т.12стр.7гр.8 =  т.12стр.1гр.8 +  т.12стр.2гр.8 +  т.12стр.3гр.8 +  т.12стр.6гр.8',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(108,NULL,0,NULL,109,7,0,0,0,'т.12стр.7гр.9 =  т.12стр.1гр.9 +  т.12стр.2гр.9 +  т.12стр.3гр.9 +  т.12стр.6гр.9',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(109,NULL,0,NULL,110,7,0,0,0,'т.12стр.7гр.11 =  т.12стр.1гр.11 +  т.12стр.2гр.11 +  т.12стр.3гр.11 +  т.12стр.6гр.11',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(110,NULL,0,NULL,111,7,0,0,0,'т.12стр.7гр.12 =  т.12стр.1гр.12 +  т.12стр.2гр.12 +  т.12стр.3гр.12 +  т.12стр.6гр.12',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(111,NULL,0,NULL,112,7,0,0,0,'т.12стр.7гр.14 =  т.12стр.1гр.14 +  т.12стр.2гр.14 +  т.12стр.3гр.14 +  т.12стр.6гр.14',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(112,NULL,0,NULL,113,7,0,0,0,'т.12стр.7гр.15 =  т.12стр.1гр.15 +  т.12стр.2гр.15 +  т.12стр.3гр.15 +  т.12стр.6гр.15',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(113,NULL,0,NULL,114,7,0,0,0,'т.12стр.7гр.17 =  т.12стр.1гр.17 +  т.12стр.2гр.17 +  т.12стр.3гр.17 +  т.12стр.6гр.17',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(114,NULL,0,NULL,115,7,0,0,0,'т.12стр.7гр.18 =  т.12стр.1гр.18 +  т.12стр.2гр.18 +  т.12стр.3гр.18 +  т.12стр.6гр.18',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(115,NULL,0,NULL,116,7,0,0,0,'т.12стр.7гр.20 =  т.12стр.1гр.20 +  т.12стр.2гр.20 +  т.12стр.3гр.20 +  т.12стр.6гр.20',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(116,NULL,0,NULL,117,7,0,0,0,'т.14стр.8гр.3 =  т.14стр.1гр.3 +  т.14стр.2гр.3 +  т.14стр.3гр.3 +  т.14стр.4гр.3 +  т.14стр.5гр.3 +  т.14стр.6гр.3 +  т.14стр.7гр.3',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(117,NULL,0,NULL,118,7,0,0,0,'т.14стр.14гр.3 =  т.14стр.10гр.3 +  т.14стр.11гр.3 +  т.14стр.12гр.3 +  т.14стр.13гр.3',1,2,1,'20140401','','','','4fss','20140101','','=',1,'','')
INSERT #A VALUES(118,NULL,0,NULL,119,7,0,0,0,'Проверки =  0',0,100,1,'20140401','','','','4fss','20140101','','=',9,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 118
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','12','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','6','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(26,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(27,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(28,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(29,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(30,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(31,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(32,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(33,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(34,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(35,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(36,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(37,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_3','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_4','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_5','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_2','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(38,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_3','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_4','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_5','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_2','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(39,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_3','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_4','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_5','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','10','15',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(40,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','7','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','9','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','16',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(41,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','16',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','16',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(42,2,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''1'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(43,2,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''15'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(44,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','7','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(45,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(46,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(47,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','8','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','9','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(48,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(49,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(50,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(51,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(52,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(53,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(54,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(55,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(56,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(57,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(58,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(59,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(60,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(61,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(62,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(63,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(64,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(65,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(66,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','4','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(67,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(68,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(68,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(69,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(69,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','10','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','15',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(70,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','15',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(71,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','15',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(72,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','15',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(73,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','6','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','15',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(74,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','7','15',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(75,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','8','15',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(76,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','9',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(77,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(78,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,5,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,6,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','5','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(79,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','4','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','3','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,5,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','1','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,6,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','12','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(80,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','10','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','12','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(81,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','10','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(82,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(83,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(84,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(84,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(84,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(85,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(85,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(85,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(86,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''1'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(86,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(86,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(87,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''15'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(87,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(87,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(88,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(89,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(90,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(91,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(92,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(93,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(93,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(93,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16_2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','12','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(94,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','10','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','12','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(95,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','5','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','10','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','11','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(96,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','4','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','5','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(97,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2_2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(98,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11_2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(99,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(99,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(99,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12_2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''1'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(100,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''10''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,1,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''15'' AND COL(3) < CONVERT(FLOAT,0)','','','','','3','','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(101,2,4,'+',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,3,4,'-',NULL,NULL,NULL,NULL,0,0,'','','','CODE = ''9''','','','','','3','','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(102,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','18','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(103,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','15','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','16','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','17','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(104,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(105,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(106,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(107,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(108,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','9','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(109,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','11','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(110,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','12','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(111,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','14','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(112,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','15','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(113,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','17','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(114,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','18','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','7','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(115,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','1','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','2','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','3','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','20','6','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','8','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(116,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','1','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','3','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','4','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','5','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','6','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','7','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','14','14',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(117,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','10','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','11','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','12','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','13','14',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(118,1,2,'+',NULL,NULL,NULL,NULL,0,0,'SA_4FSS_EXPORT_TEST(0)','Проверки','','','','','','','','','',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(118,2,1,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 424
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '3         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'3','Квартальные формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '999999    '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'999999','формы отчетности',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-07-04 11:11:39.253',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-07-04 11:11:39.253'
	BEGIN
		SELECT @vcMessage = 'Форма 4fss с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 4fss с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-07-04 11:11:39.253. Обновление отклонено.'
	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. (июл 24 2014 12:25:27:753PM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : РСВ-1 (Расчет по начисленным и уплаченным страховым взносам на ОПС и в ФСС (ФЗ от 24 июля 2009 г. № 212-ФЗ))
-- Дата ввода : 20140101
-- Дата окончания действия :
-- Версия : 2014-07-24 12:25:27.753
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = 'РСВ-1' AND [START_DATE] = '20140101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-07-24 12:25:27.753',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + 'РСВ-1',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = 'РСВ-1'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20140101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SALARY'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Расчет по начисленным и уплаченным страховым взносам на ОПС и в ФСС (ФЗ от 24 июля 2009 г. № 212-ФЗ)',@vcNEW_FORM_CODE,@dNEW_START_DATE,2,0,0,1,2291,'i_report_export_nalog',0,0,'19000101',NULL,''
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, 'sa_print_rsv_1_pfr_2014()','RSV_1_PFR_2014.bas','','KirRepMakerMultiSheet.XLS','RSV-1-PFR_2014.XLT','',NULL,'i_report_export_nalog',0,NULL,NULL,NULL,'          ','REPORTS_ATR_PERS_UCH,REPORTS_ATR_TYPE_KOR',NULL,NULL,'RN_PRINT_RSV1|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Титульный лист', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование',@iLINK_TABLE,0,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код',@iLINK_TABLE,1,1,2,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Количество застрахованных лиц',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Среднесписочная численность',@iLINK_TABLE,1,0,4,1,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Титульный лист', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1. Расчет по начисленным и уплаченным страховым', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Страховые взносы на ОПС за периоды, начиная с 2014 г.',@iLINK_TABLE,1,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Страховые взносы на ОПС за периоды 2010-2013: страховая часть',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Страховые взносы на ОПС за периоды 2010-2013: накопительная часть',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Страховые взносы на ОПС:по доп тарифу - занятых на видах работ, указанных в подпункте 1 пункта 1 статьи 27 Федерального закона № 173-ФЗ',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Страховые взносы на ОПС:по доп тарифу - занятых на видах работ, указанных в подпунктах 2-18 пункта 1 статьи 27 Федерального закона № 173-ФЗ',@iLINK_TABLE,1,0,7,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Страховые взносы на ОМС',@iLINK_TABLE,1,0,8,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р1. Расчет по начисленным и уплаченным страховым', @iLINK_FORM,2, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2. Расчет страховых взносов по тарифу', @iLINK_FORM,3
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода: 1 месяц',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода: 2 месяц',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода: 3 месяц',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2. Расчет страховых взносов по тарифу', @iLINK_FORM,3, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2_1. Расчет страховых взносов по тарифу ОИ', @iLINK_FORM,4
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода: 1 месяц',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода: 2 месяц',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода: 3 месяц',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2_1. Расчет страховых взносов по тарифу ОИ', @iLINK_FORM,4, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.2_2.3.Расчет страховых взнос. по доп.тар. для о', @iLINK_FORM,5
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,0,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода: 1 месяц',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода: 2 месяц',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода: 3 месяц',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.2_2.3.Расчет страховых взнос. по доп.тар. для о', @iLINK_FORM,5, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.4_1.Расчет страховых по доп.тар. 1', @iLINK_FORM,6
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,0,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода: 1 месяц',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода: 2 месяц',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода: 3 месяц',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.4_1.Расчет страховых по доп.тар. 1', @iLINK_FORM,6, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.4_2.Расчет страховых по доп.тарифу 2', @iLINK_FORM,7
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,0,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода: 1 месяц',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода: 2 месяц',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода: 3 месяц',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.4_2.Расчет страховых по доп.тарифу 2', @iLINK_FORM,7, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.5.1.Перечень пачек док-ов исход. свед. индивид.', @iLINK_FORM,8
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ пп',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Сведения о базе для начисления страховых взносов на обязательное пенсионное страхование с сумм выплат и иных вознаграждений, не превышающих предельную величину базы для начисления страховых взносов, содержащиеся в пачке документов',@iLINK_TABLE,1,0,3,2,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Сведения о начисленных страховых взносах с сумм, не превышающих предельную величину базы для начисления страховых взносов, содержащихся в пачке документов',@iLINK_TABLE,1,0,4,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Сведения о количестве застрахованных лиц в пачке документов',@iLINK_TABLE,1,0,5,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Имя файла (номер пачки документов)',@iLINK_TABLE,1,1,6,0,50,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Дата составления',@iLINK_TABLE,1,1,7,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Тип сведений',@iLINK_TABLE,1,0,8,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Период',@iLINK_TABLE,1,0,9,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Год',@iLINK_TABLE,1,0,10,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Ссылка на документ',@iLINK_TABLE,1,0,11,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.5.1.Перечень пачек док-ов исход. свед. индивид.', @iLINK_FORM,8, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_PERS_UCH @dateBeginPeriod, @dateEndPeriod, @depLink, 0, @LSF',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р2.5.2.Переч. пачек док-ов коррект. свед. индивид(', @iLINK_FORM,9
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ пп',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Сведения о периоде, за который производится корректировка сведений - отчетный период (код)',@iLINK_TABLE,1,1,3,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Сведения о периоде, за который производится корректировка сведений - год',@iLINK_TABLE,1,1,4,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Сведения о сумме доначисленных страховых взносов, содержащихся в пачке документов (руб.коп.)на обязательное пенсионное страхование за периоды, начиная с 2014 г.',@iLINK_TABLE,1,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Сведения о сумме доначисленных страховых взносов, содержащихся в пачке документов (руб.коп.)за периоды 2010-2013 гг.на страховую часть',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Сведения о сумме доначисленных страховых взносов, содержащихся в пачке документов (руб.коп.) за периоды 2010-2013 гг.на накопительную часть',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Сведения о количестве застрахованных лиц в пачке документов',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Имя файла (номер пачки документов)',@iLINK_TABLE,1,1,9,0,50,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Дата составления',@iLINK_TABLE,1,1,10,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Тип сведений',@iLINK_TABLE,1,0,11,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Период(код)',@iLINK_TABLE,1,1,12,0,1,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Период(год)',@iLINK_TABLE,1,1,13,0,4,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Сумма базы',@iLINK_TABLE,1,0,14,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 15,'Сумма ОПС',@iLINK_TABLE,1,0,15,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 16,'Ссылка на документ',@iLINK_TABLE,1,0,16,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р2.5.2.Переч. пачек док-ов коррект. свед. индивид(', @iLINK_FORM,9, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_PERS_UCH @dateBeginPeriod, @dateEndPeriod, @depLink, 1, @LSF',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.1_3.2. Соотв. условиям  п.3 ч.1 ст.58 № 212-ФЗ', @iLINK_FORM,10
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода, 1 месяц',@iLINK_TABLE,1,0,4,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода, 2 месяц',@iLINK_TABLE,1,0,5,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода, 3 месяц',@iLINK_TABLE,1,0,6,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.1_3.2. Соотв. условиям  п.3 ч.1 ст.58 № 212-ФЗ', @iLINK_FORM,10, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.3. Соответствия условиям п.6 ч.1 ст.58 № 212-ФЗ', @iLINK_FORM,11
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'По итогам 9-ти месяцев года, предшествующего текущему расчетному перио',@iLINK_TABLE,1,0,3,1,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'По итогам текущего отчетного (расчетного) периода',@iLINK_TABLE,1,0,4,2,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Дата записи в реестре  аккредитованных организаций',@iLINK_TABLE,1,1,5,5,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'№ записи в реестре аккредитованных организаций',@iLINK_TABLE,1,1,6,6,50,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.3. Соответствия условиям п.6 ч.1 ст.58 № 212-ФЗ', @iLINK_FORM,11, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.4. Соответствие условиям п.7 ч.1 ст. 58  №212-Ф', @iLINK_FORM,12
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Наименование вида экономической деятельности с указанием кода ОКВЭД',@iLINK_TABLE,1,1,2,0,254,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'',@iLINK_TABLE,1,1,3,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Код строки',@iLINK_TABLE,1,1,4,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Доходы по виду экономической деятельности',@iLINK_TABLE,1,0,5,5,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Доля дох. и поступ по данному виду эконом деят-ти в общей сумме доходо',@iLINK_TABLE,1,0,6,6,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Дата внесения в реестр СМИ',@iLINK_TABLE,1,1,7,7,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'№ записи в реестре СМИ',@iLINK_TABLE,1,1,8,8,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.4. Соответствие условиям п.7 ч.1 ст. 58  №212-Ф', @iLINK_FORM,12, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.5_3.6. Соотв. условиям п.8,п.11 ч.1. ст.58 № 21', @iLINK_FORM,13
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'С начала отчетного (расчетного) периода',@iLINK_TABLE,0,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'По итогам года, предшествующего текущему расчетному периоду',@iLINK_TABLE,1,0,4,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'По итогам текущего расчетного периода',@iLINK_TABLE,1,0,5,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.5_3.6. Соотв. условиям п.8,п.11 ч.1. ст.58 № 21', @iLINK_FORM,13, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р4.Суммы доначисл. страховых взносов с начала расч', @iLINK_FORM,14
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,3,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Основание для доначисления страховых взносов*',@iLINK_TABLE,1,0,2,0,0,1,NULL,NULL,NULL,'9',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Код основания для применения части 2.1 статьи 58.3 Федерального закона от 24 июля 2009 г.',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Период, за который выявлены и доначислены страховые взносы, год',@iLINK_TABLE,1,1,4,4,4,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Период, за который выявлены и доначислены страховые взносы, месяц',@iLINK_TABLE,1,0,5,5,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Страховые взносы: страховая часть, начиная с 2014 г. - Всего',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Страховые взносы: страховая часть, начиная с 2014 г. - в том числе с сумм, превышающих предельную величину базы для начисления страховых взносов',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Страховые взносы: страховая часть - Всего',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Страховые взносы: страховая часть - в том числе сумм превышающих предельную величину базы для начисления страховых взносов',@iLINK_TABLE,1,0,9,9,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Страховые взносы на обязательное пенсионное страхование, накопительная',@iLINK_TABLE,1,0,10,10,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Страх. взносы на ОПС, по доп тарифу: в соответствии с частью 1 статьи 58.3 Федерального закона от 24 июля 2009 г. № 212-ФЗ',@iLINK_TABLE,1,0,11,11,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Страх. взносы на ОПС, по доп тарифу: в соответствии с частью 2 статьи 58.3 Федерального закона от 24 июля 2009 г. № 212-ФЗ',@iLINK_TABLE,1,0,12,12,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Страх. взносы на ОПС, по доп тарифу: в соответствии с частью 2.1 статьи 58.3 Федерального закона от 24 июля 2009 г. № 212-ФЗ',@iLINK_TABLE,1,0,13,13,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Страховые взносы на обязательное медицинское страхование',@iLINK_TABLE,1,0,14,14,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р4.Суммы доначисл. страховых взносов с начала расч', @iLINK_FORM,14, @iLINK_CODE_COL,1,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р5.Свед., необходимые для применения п.1 ч.3 ст.9', @iLINK_FORM,15
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,3,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Фамилия, имя, отчество обучающегося',@iLINK_TABLE,1,1,2,0,254,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Сведения из справки (номер, дата), подтверждающие членство в студенческом отряде',@iLINK_TABLE,1,1,3,0,20,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Сведения из справки (номер, дата), подтверждающие очную форму обучения',@iLINK_TABLE,1,1,4,0,20,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Всего с начала расчетного периода',@iLINK_TABLE,0,0,5,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'в том числе за последние три месяца отчетного периода, 1 месяц',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'в том числе за последние три месяца отчетного периода, 2 месяц',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'в том числе за последние три месяца отчетного периода, 3 месяц',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р5.Свед., необходимые для применения п.1 ч.3 ст.9', @iLINK_FORM,15, @iLINK_CODE_COL,1,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р5_2.Свед, необходимые для прим п.1 ч.3 ст.9 № 212', @iLINK_FORM,16
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Дата записи в реестре',@iLINK_TABLE,1,1,3,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'№ записи в реестре',@iLINK_TABLE,1,1,4,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р5_2.Свед, необходимые для прим п.1 ч.3 ст.9 № 212', @iLINK_FORM,16, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р6.1.Сведения о застрахованном лице', @iLINK_FORM,17
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Фамилия',@iLINK_TABLE,1,1,2,0,100,1,NULL,NULL,NULL,NULL,8,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Имя',@iLINK_TABLE,1,1,3,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Отчество',@iLINK_TABLE,1,1,4,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'СНИЛС',@iLINK_TABLE,1,1,5,0,14,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Тип сведений',@iLINK_TABLE,1,1,6,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Номер пачки',@iLINK_TABLE,1,1,7,0,3,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Наименование файла',@iLINK_TABLE,1,1,8,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Дата документа',@iLINK_TABLE,1,1,9,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р6.1.Сведения о застрахованном лице', @iLINK_FORM,17, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_PERS_UCH_SZV @dateBeginPeriod, @dateEndPeriod, @depLink, 0 , @LSF',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р6.4. Свед. о сумме вып. и иных вознаг., начисленн', @iLINK_FORM,18
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'СНИЛС',@iLINK_TABLE,1,1,2,0,14,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'',@iLINK_TABLE,1,1,3,0,254,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Код строки',@iLINK_TABLE,1,1,4,0,4,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Код категории застрахованного лица',@iLINK_TABLE,1,1,5,0,15,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Сумма выплат и иных вознаграждений, начисленных в пользу физического лица',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'База для начисления страховых взносов на обязательное пенсионное страхование с сумм выплат и иных вознаграждений, не превышающих предельную величину базы для начисления страховых взносов, Всего',@iLINK_TABLE,1,0,7,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'в том числе  по гражданско-правовым  договорам',@iLINK_TABLE,1,0,8,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Сумма выплат и иных вознаграждений, превышающая предельную величину базы для начисления страховых взносов',@iLINK_TABLE,1,0,9,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Отчетный период(код)',@iLINK_TABLE,1,1,10,0,1,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Календарный год',@iLINK_TABLE,1,1,11,0,4,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Тип сведений',@iLINK_TABLE,1,1,12,0,14,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Отчетный период(код) корректирующие\отменяющие',@iLINK_TABLE,1,1,13,0,1,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Календарный год - корректирующие\отменяющие',@iLINK_TABLE,1,1,14,0,4,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 15,'Номер',@iLINK_TABLE,0,0,15,0,0,1,NULL,NULL,NULL,NULL,9,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 16,'Фамилия',@iLINK_TABLE,1,1,16,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 17,'Имя',@iLINK_TABLE,1,1,17,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 18,'Отчество',@iLINK_TABLE,1,1,18,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 19,'Период корректировки (код)1',@iLINK_TABLE,1,0,19,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 20,'Год корректировки (код)1',@iLINK_TABLE,1,0,20,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 21,'Сумма на ОПС1',@iLINK_TABLE,1,0,21,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 22,'Сумма на страховую часть ОПС1',@iLINK_TABLE,1,0,22,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 23,'Сумма на накопительную часть ОПС1',@iLINK_TABLE,1,0,23,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 24,'Период корректировки(код)2',@iLINK_TABLE,1,0,24,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 25,'Год корректировки (код)2',@iLINK_TABLE,1,0,25,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 26,'Сумма на ОПС2',@iLINK_TABLE,1,0,26,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 27,'Сумма на страховую часть ОПС2',@iLINK_TABLE,1,0,27,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 28,'Сумма на накопительную часть ОПС2',@iLINK_TABLE,1,0,28,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 29,'Период корректировки(код)3',@iLINK_TABLE,1,0,29,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 30,'Год корректировки (код)3',@iLINK_TABLE,1,0,30,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 31,'Сумма на ОПС3',@iLINK_TABLE,1,0,31,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 32,'Сумма на страховую часть ОПС3',@iLINK_TABLE,1,0,32,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 33,'Сумма на накопительную часть ОПС3',@iLINK_TABLE,1,0,33,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 34,'Период корректировки(код)4',@iLINK_TABLE,1,0,34,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 35,'Год корректировки (код)4',@iLINK_TABLE,1,0,35,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 36,'Сумма на ОПС4',@iLINK_TABLE,1,0,36,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 37,'Сумма на страховую часть ОПС4',@iLINK_TABLE,1,0,37,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 38,'Сумма на накопительную часть ОПС4',@iLINK_TABLE,1,0,38,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 39,'Период корректировки(код)5',@iLINK_TABLE,1,0,39,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 40,'Год корректировки (код)5',@iLINK_TABLE,1,0,40,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 41,'Сумма на ОПС5',@iLINK_TABLE,1,0,41,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 42,'Сумма на страховую часть ОПС5',@iLINK_TABLE,1,0,42,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 43,'Сумма на накопительную часть ОПС5',@iLINK_TABLE,1,0,43,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 44,'Общая сумма для раздела 6_5',@iLINK_TABLE,1,0,44,0,2,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р6.4. Свед. о сумме вып. и иных вознаг., начисленн', @iLINK_FORM,18, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_PERS_UCH_SZV @dateBeginPeriod, @dateEndPeriod, @depLink, 1, @LSF',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р6.6.Информация о корректирующих сведениях', @iLINK_FORM,19
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Отчетный период (код)',@iLINK_TABLE,1,0,2,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Год',@iLINK_TABLE,1,1,3,0,4,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Сумма доначисленных страховых взносов (руб.коп.) на ОПС с 2014 г',@iLINK_TABLE,1,0,4,3,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Сумма доначисленных страховых взносов (руб.коп.) - на страховую часть',@iLINK_TABLE,1,0,5,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Сумма доначисленных страховых взносов (руб.коп.) - на накопительную часть',@iLINK_TABLE,1,0,6,5,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'СНИЛС',@iLINK_TABLE,0,1,7,0,14,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Номер',@iLINK_TABLE,0,0,8,0,0,1,NULL,NULL,NULL,NULL,9,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р6.6.Информация о корректирующих сведениях', @iLINK_FORM,19, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_PERS_UCH_SZV @dateBeginPeriod, @dateEndPeriod, @depLink, 2, @LSF',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р6.7.Свед. о сумме вып. п1, 2 и п.1 ст.58.3 № 212-', @iLINK_FORM,20
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'',@iLINK_TABLE,1,1,2,0,254,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Код строки',@iLINK_TABLE,1,1,3,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Код специальной оценки условий труда',@iLINK_TABLE,1,1,4,0,15,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Сумма выплат и иных вознаграждений, начисленых в пользу физического лица, занятого на видах работ, указанных в подпункте 1 пункта 1 статьи 27 Федерального закона от  17 декабря 2001 г. № 173-ФЗ',@iLINK_TABLE,1,0,5,4,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Сумма выплат и иных вознаграждений, начисленных в пользу физического лица, занятого на видах работ, указанных в подпунктах 2-18 пункта 1 статьи 27 Федерального закона от  17 декабря 2001 г.',@iLINK_TABLE,1,0,6,5,0,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'СНИЛС',@iLINK_TABLE,1,1,7,0,14,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Номер',@iLINK_TABLE,1,0,8,0,0,1,NULL,NULL,NULL,NULL,9,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Тип сведений',@iLINK_TABLE,1,0,9,0,0,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Начало периода с (дд.мм.гггг.)1',@iLINK_TABLE,0,1,10,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Конец периода по (дд.мм.гггг.)1',@iLINK_TABLE,1,1,11,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Территориальные условия труда(код)1',@iLINK_TABLE,1,1,12,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Особые условия труда (код)1',@iLINK_TABLE,1,1,13,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Исчисление страхового стажа - Основание (код)1',@iLINK_TABLE,1,1,14,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 15,'Исчисление страхового стажа - Дополнительные сведения1',@iLINK_TABLE,1,1,15,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 16,'Условия досрочного назначения трудовой пенсии - Основание (код)1',@iLINK_TABLE,1,1,16,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 17,'Условия досрочного назначения трудовой пенсии - Дополнительные сведения1',@iLINK_TABLE,1,1,17,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 18,'Начало периода с (дд.мм.гггг.)2',@iLINK_TABLE,1,1,18,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 19,'Конец периода по (дд.мм.гггг.)2',@iLINK_TABLE,0,1,19,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 20,'Территориальные условия труда(код)2',@iLINK_TABLE,0,1,20,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 21,'Особые условия труда (код)2',@iLINK_TABLE,0,1,21,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 22,'Исчисление страхового стажа - Основание (код)2',@iLINK_TABLE,1,1,22,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 23,'Исчисление страхового стажа - Дополнительные сведения2',@iLINK_TABLE,1,1,23,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 24,'Условия досрочного назначения трудовой пенсии - Основание (код)2',@iLINK_TABLE,1,1,24,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 25,'Условия досрочного назначения трудовой пенсии - Дополнительные сведения2',@iLINK_TABLE,0,1,25,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 26,'Начало периода с (дд.мм.гггг.)3',@iLINK_TABLE,1,1,26,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 27,'Конец периода по (дд.мм.гггг.)3',@iLINK_TABLE,1,1,27,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 28,'Территориальные условия труда(код)3',@iLINK_TABLE,1,1,28,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 29,'Особые условия труда (код)3',@iLINK_TABLE,1,1,29,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 30,'Исчисление страхового стажа - Основание (код)3',@iLINK_TABLE,1,1,30,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 31,'Исчисление страхового стажа - Дополнительные сведения3',@iLINK_TABLE,1,1,31,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 32,'Условия досрочного назначения трудовой пенсии - Основание (код)3',@iLINK_TABLE,1,1,32,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 33,'Условия досрочного назначения трудовой пенсии - Дополнительные сведения3',@iLINK_TABLE,1,1,33,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 34,'Начало периода с (дд.мм.гггг.)4',@iLINK_TABLE,1,1,34,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 35,'Конец периода по (дд.мм.гггг.)4',@iLINK_TABLE,1,1,35,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 36,'Территориальные условия труда(код)4',@iLINK_TABLE,1,1,36,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 37,'Особые условия труда (код)4',@iLINK_TABLE,1,1,37,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 38,'Исчисление страхового стажа - Основание (код)4',@iLINK_TABLE,1,1,38,0,20,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 39,'Исчисление страхового стажа - Дополнительные сведения4',@iLINK_TABLE,1,1,39,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 40,'Условия досрочного назначения трудовой пенсии - Основание (код)4',@iLINK_TABLE,1,1,40,0,10,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 41,'Условия досрочного назначения трудовой пенсии - Дополнительные сведения4',@iLINK_TABLE,1,1,41,0,100,1,NULL,NULL,NULL,NULL,1,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 42,'Фамилия',@iLINK_TABLE,0,1,42,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 43,'Имя',@iLINK_TABLE,0,1,43,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 44,'Отчество',@iLINK_TABLE,0,1,44,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р6.7.Свед. о сумме вып. п1, 2 и п.1 ст.58.3 № 212-', @iLINK_FORM,20, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_PERS_UCH_SZV @dateBeginPeriod, @dateEndPeriod, @depLink, 3, @LSF',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р6.8. Период работы за последние три месяца отчетн', @iLINK_FORM,21
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ пп',@iLINK_TABLE,1,1,1,0,254,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Начало периода с (дд.мм.гггг.)',@iLINK_TABLE,1,1,2,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Конец периода по (дд.мм.гггг)',@iLINK_TABLE,1,1,3,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Территориальные условия труда(код)',@iLINK_TABLE,1,1,4,0,20,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Особые условия труда (код)',@iLINK_TABLE,1,1,5,0,20,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Исчисление страхового стажа - Основание (код)',@iLINK_TABLE,1,1,6,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Исчисление страхового стажа - Дополнительные сведения',@iLINK_TABLE,1,1,7,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Условия досрочного назначения трудовой пенсии - Основание (код)',@iLINK_TABLE,1,1,8,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Условия досрочного назначения трудовой пенсии - Дополнительные сведения',@iLINK_TABLE,1,1,9,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'СНИЛС',@iLINK_TABLE,1,1,10,0,14,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Номер',@iLINK_TABLE,1,0,11,0,0,1,NULL,NULL,NULL,NULL,8,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Тип сведений',@iLINK_TABLE,0,0,12,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Фамилия',@iLINK_TABLE,0,1,13,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Имя',@iLINK_TABLE,0,1,14,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 15,'Отчество',@iLINK_TABLE,0,1,15,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р6.8. Период работы за последние три месяца отчетн', @iLINK_FORM,21, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_PERS_UCH_SZV @dateBeginPeriod, @dateEndPeriod, @depLink, 4, @LSF',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (1,1,1,1)
INSERT #R VALUES (1,2,0,1)
INSERT #R VALUES (3,2,0,1)
INSERT #R VALUES (4,2,0,1)
INSERT #R VALUES (5,2,0,1)
INSERT #R VALUES (6,2,1,1)
INSERT #R VALUES (7,2,0,1)
INSERT #R VALUES (8,2,1,1)
INSERT #R VALUES (11,2,0,1)
INSERT #R VALUES (12,2,0,1)
INSERT #R VALUES (13,2,0,1)
INSERT #R VALUES (14,2,0,1)
INSERT #R VALUES (16,2,0,1)
INSERT #R VALUES (2,2,0,1)
INSERT #R VALUES (10,2,1,1)
INSERT #R VALUES (15,2,1,1)
INSERT #R VALUES (1,3,0,1)
INSERT #R VALUES (2,3,0,1)
INSERT #R VALUES (3,3,0,1)
INSERT #R VALUES (4,3,0,1)
INSERT #R VALUES (5,3,1,1)
INSERT #R VALUES (6,3,0,1)
INSERT #R VALUES (7,3,0,1)
INSERT #R VALUES (8,3,0,1)
INSERT #R VALUES (9,3,0,1)
INSERT #R VALUES (10,3,0,1)
INSERT #R VALUES (11,3,0,1)
INSERT #R VALUES (12,3,0,1)
INSERT #R VALUES (13,3,0,1)
INSERT #R VALUES (14,3,2,1)
INSERT #R VALUES (15,3,0,1)
INSERT #R VALUES (1,4,0,1)
INSERT #R VALUES (2,4,0,1)
INSERT #R VALUES (3,4,0,1)
INSERT #R VALUES (4,4,0,1)
INSERT #R VALUES (5,4,1,1)
INSERT #R VALUES (6,4,0,1)
INSERT #R VALUES (7,4,0,1)
INSERT #R VALUES (8,4,0,1)
INSERT #R VALUES (9,4,0,1)
INSERT #R VALUES (10,4,0,1)
INSERT #R VALUES (11,4,0,1)
INSERT #R VALUES (12,4,0,1)
INSERT #R VALUES (13,4,0,1)
INSERT #R VALUES (14,4,0,1)
INSERT #R VALUES (15,4,2,1)
INSERT #R VALUES (1,5,0,1)
INSERT #R VALUES (2,5,0,1)
INSERT #R VALUES (3,5,1,1)
INSERT #R VALUES (4,5,0,1)
INSERT #R VALUES (5,5,0,1)
INSERT #R VALUES (6,5,0,1)
INSERT #R VALUES (7,5,0,1)
INSERT #R VALUES (8,5,0,1)
INSERT #R VALUES (10,5,0,1)
INSERT #R VALUES (9,5,2,1)
INSERT #R VALUES (1,6,0,1)
INSERT #R VALUES (2,6,0,1)
INSERT #R VALUES (3,6,0,1)
INSERT #R VALUES (5,6,0,1)
INSERT #R VALUES (6,6,0,1)
INSERT #R VALUES (7,6,0,1)
INSERT #R VALUES (9,6,0,1)
INSERT #R VALUES (10,6,0,1)
INSERT #R VALUES (11,6,0,1)
INSERT #R VALUES (12,6,0,1)
INSERT #R VALUES (14,6,0,1)
INSERT #R VALUES (15,6,0,1)
INSERT #R VALUES (16,6,0,1)
INSERT #R VALUES (17,6,0,1)
INSERT #R VALUES (19,6,0,1)
INSERT #R VALUES (20,6,0,1)
INSERT #R VALUES (21,6,0,1)
INSERT #R VALUES (22,6,0,1)
INSERT #R VALUES (24,6,0,1)
INSERT #R VALUES (25,6,0,1)
INSERT #R VALUES (4,6,1,1)
INSERT #R VALUES (8,6,2,1)
INSERT #R VALUES (13,6,3,1)
INSERT #R VALUES (18,6,4,1)
INSERT #R VALUES (23,6,5,1)
INSERT #R VALUES (1,7,0,1)
INSERT #R VALUES (2,7,0,1)
INSERT #R VALUES (3,7,0,1)
INSERT #R VALUES (5,7,0,1)
INSERT #R VALUES (6,7,0,1)
INSERT #R VALUES (7,7,0,1)
INSERT #R VALUES (9,7,0,1)
INSERT #R VALUES (10,7,0,1)
INSERT #R VALUES (11,7,0,1)
INSERT #R VALUES (12,7,0,1)
INSERT #R VALUES (14,7,0,1)
INSERT #R VALUES (15,7,0,1)
INSERT #R VALUES (16,7,0,1)
INSERT #R VALUES (17,7,0,1)
INSERT #R VALUES (19,7,0,1)
INSERT #R VALUES (20,7,0,1)
INSERT #R VALUES (21,7,0,1)
INSERT #R VALUES (22,7,0,1)
INSERT #R VALUES (24,7,0,1)
INSERT #R VALUES (25,7,0,1)
INSERT #R VALUES (4,7,1,1)
INSERT #R VALUES (8,7,2,1)
INSERT #R VALUES (13,7,3,1)
INSERT #R VALUES (18,7,4,1)
INSERT #R VALUES (23,7,5,1)
INSERT #R VALUES (1,10,0,1)
INSERT #R VALUES (2,10,0,1)
INSERT #R VALUES (3,10,1,1)
INSERT #R VALUES (4,10,0,1)
INSERT #R VALUES (5,10,0,1)
INSERT #R VALUES (7,10,0,1)
INSERT #R VALUES (8,10,0,1)
INSERT #R VALUES (6,10,2,1)
INSERT #R VALUES (9,10,3,1)
INSERT #R VALUES (1,11,0,1)
INSERT #R VALUES (2,11,0,1)
INSERT #R VALUES (3,11,1,1)
INSERT #R VALUES (4,11,0,1)
INSERT #R VALUES (5,11,0,1)
INSERT #R VALUES (1,12,0,1)
INSERT #R VALUES (2,12,0,1)
INSERT #R VALUES (3,12,0,1)
INSERT #R VALUES (4,12,0,1)
INSERT #R VALUES (5,12,0,1)
INSERT #R VALUES (6,12,0,1)
INSERT #R VALUES (7,12,0,1)
INSERT #R VALUES (8,12,0,1)
INSERT #R VALUES (9,12,0,1)
INSERT #R VALUES (10,12,0,1)
INSERT #R VALUES (11,12,1,1)
INSERT #R VALUES (12,12,0,1)
INSERT #R VALUES (2,13,0,1)
INSERT #R VALUES (3,13,1,1)
INSERT #R VALUES (1,13,0,1)
INSERT #R VALUES (4,13,0,1)
INSERT #R VALUES (5,13,0,1)
INSERT #R VALUES (6,13,0,1)
INSERT #R VALUES (7,13,0,1)
INSERT #R VALUES (8,13,1,1)
INSERT #R VALUES (1,16,0,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 141
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,1,1,'Показатель                                                                                                                                                                                                                                                    ')
INSERT #F VALUES (1,1,2,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (1,1,3,'РСВ1_14_ПФР_УСТАНОВКА() + РСВ1_ЗНАЧЕНИЕ(К.СТР.,1)')
INSERT #F VALUES (1,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,2)')
INSERT #F VALUES (2,1,1,'Остаток страховых взносов, подлежащих уплате на начало расчетного периода
(+) задолженность, (-) переплата                                                                                                                                                   ')
INSERT #F VALUES (2,2,1,'Начислено страховых взносов с начала расчетного периода                                                                                                                                                                                                       ')
INSERT #F VALUES (2,3,1,'в том числе за последние три месяца отчетного периода : 1 месяц                                                                                                                                                                                               ')
INSERT #F VALUES (2,4,1,'         2 месяц                                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,5,1,'         3 месяц                                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,6,1,'Итого подлежит уплате за последние 3 месяца (с.111 + с.112 + с.113)                                                                                                                                                                                           ')
INSERT #F VALUES (2,7,1,'Доначислено страховых взносов с начала расчетного периода                                                                                                                                                                                                     ')
INSERT #F VALUES (2,8,1,'В том числе с сумм, превышающих предельную величину базы для начисления страховых взносов                                                                                                                                                                     ')
INSERT #F VALUES (2,10,1,'Всего к уплате (с. 100 + с. 110 + с. 120)                                                                                                                                                                                                                     ')
INSERT #F VALUES (2,11,1,'Уплачено с начала расчетного периода                                                                                                                                                                                                                          ')
INSERT #F VALUES (2,12,1,'в том числе за последние три месяца отчетного периода: 1 месяц                                                                                                                                                                                                ')
INSERT #F VALUES (2,13,1,'         2 месяц                                                                                                                                                                                                                                              ')
INSERT #F VALUES (2,14,1,'        3 месяц                                                                                                                                                                                                                                               ')
INSERT #F VALUES (2,15,1,'        итого (с. 141 + с. 142 + с. 143)                                                                                                                                                                                                                      ')
INSERT #F VALUES (2,16,1,'Остаток страховых взносов, подлежащих уплате
на конец отчетного периода (с.130 - с.140) (+) задолженность, (-) переплата                                                                                                                                     ')
INSERT #F VALUES (2,1,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,2,2,'110                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,3,2,'111                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,4,2,'112                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,5,2,'113                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,6,2,'114                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,7,2,'120                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,8,2,'121                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,10,2,'130                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,11,2,'140                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,12,2,'141                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,13,2,'142                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,14,2,'143                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,15,2,'144                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,16,2,'150                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (2,12,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (2,13,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (2,14,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (2,1,4,'КТСН("_.303.10","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,3,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,4,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (2,12,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (2,13,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (2,14,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (2,1,5,'КТСН("_.303.11","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,2,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,3,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,4,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,5,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,6,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,8,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (2,12,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (2,13,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (2,14,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (2,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (2,8,6,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,6,'АДТКТ("_.303.09, КАУ =kau_RSV1_s1","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=НАЧ.ГОДА") + АДТКТ("_.303.09, КАУ =kau_RSV1_s1","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,12,6,'АДТКТ("_.303.09, КАУ =kau_RSV1_s1","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(1)") + АДТКТ("_.303.09, КАУ =kau_RSV1_s1","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,13,6,'АДТКТ("_.303.09, КАУ =kau_RSV1_s1","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(2)") + АДТКТ("_.303.09, КАУ =kau_RSV1_s1","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,14,6,'АДТКТ("_.303.09, КАУ =kau_RSV1_s1","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(3)") + АДТКТ("_.303.09, КАУ =kau_RSV1_s1","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,1,7,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,7)')
INSERT #F VALUES (2,8,7,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,7,'АДТКТ("_.303.09, КАУ =kau_RSV1_s2","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=НАЧ.ГОДА") + АДТКТ("_.303.09, КАУ =kau_RSV1_s2","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,12,7,'АДТКТ("_.303.09, КАУ =kau_RSV1_s2","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(1)") + АДТКТ("_.303.09, КАУ =kau_RSV1_s2","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,13,7,'АДТКТ("_.303.09, КАУ =kau_RSV1_s2","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(2)") + АДТКТ("_.303.09, КАУ =kau_RSV1_s2","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,14,7,'АДТКТ("_.303.09, КАУ =kau_RSV1_s2","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(3)") + АДТКТ("_.303.09, КАУ =kau_RSV1_s2","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,1,8,'КТСН("_.303.07","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,8,8,'ЗАПРЕТ()')
INSERT #F VALUES (2,11,8,'АДТКТ("_.303.07","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=НАЧ.ГОДА") + АДТКТ("_.303.07","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,12,8,'АДТКТ("_.303.07","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(1)") + АДТКТ("_.303.07","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,13,8,'АДТКТ("_.303.07","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(2)") + АДТКТ("_.303.07","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,14,8,'АДТКТ("_.303.07","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(3)") + АДТКТ("_.303.07","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (3,1,1,'Сумма выплат и иных вознаграждений, на-численных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с международными договорами                                                            ')
INSERT #F VALUES (3,2,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с международными договорами                                                                                   ')
INSERT #F VALUES (3,3,1,'Сумма расходов, принимаемых к вычету в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                                       ')
INSERT #F VALUES (3,4,1,'Суммы выплат и иных вознаграждений, превышающие предельную величину базы для начисления страховых взносов                                                                                                                                                     ')
INSERT #F VALUES (3,5,1,'База для начисления страховых взносов на обязательное пенсионное страхование (с. 200 - с. 201 - с. 202 - с. 203)                                                                                                                                              ')
INSERT #F VALUES (3,6,1,'Начислено страховых взносов на обязательное пенсионное страхование:с сумм, не превышающих предельную базу для начисления страховых взносов                                                                                                                    ')
INSERT #F VALUES (3,15,1,'Начислено страховых взносов на обязательное медицинское страхование                                                                                                                                                                                           ')
INSERT #F VALUES (3,7,1,'с сумм, превышающих предельную величину базы для начисления страховых взносов                                                                                                                                                                                 ')
INSERT #F VALUES (3,8,1,'Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы в соответствии с тарифом страховых взносов, всего (чел.)                                                                                                         ')
INSERT #F VALUES (3,9,1,'в том числе количество физических лиц, выплаты и иные вознаграждения которым превысили предельную величину базы для начисления страховых взносов  (чел.)                                                                                                      ')
INSERT #F VALUES (3,10,1,'Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009г. 
№ 212-ФЗ и в соответствии с международными договорами                                                             ')
INSERT #F VALUES (3,11,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии с частями 1, 2 статьи 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с международными договорами                                                                        ')
INSERT #F VALUES (3,12,1,'Сумма расходов, принимаемых к вычету в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                                       ')
INSERT #F VALUES (3,13,1,'Суммы выплат и иных вознаграждений, превышающие предельную величину базы для начисления страховых взносов                                                                                                                                                     ')
INSERT #F VALUES (3,14,1,'База для начисления страховых взносов на обязательное медицинское страхование (с. 210 - с. 211 - с. 212 - с. 213)                                                                                                                                             ')
INSERT #F VALUES (3,1,2,'200                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,2,2,'201                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,3,2,'202                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,4,2,'203                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,5,2,'204                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,6,2,'205                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,15,2,'215                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,7,2,'206                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,8,2,'207                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,9,2,'208                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,10,2,'210                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,11,2,'211                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,12,2,'212                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,13,2,'213                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,14,2,'214                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,1,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,3,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,4,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,6,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,15,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,7,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,8,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,9,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,10,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,12,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,13,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,3,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,4,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,6,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,15,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,7,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,8,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,9,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,10,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,12,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,13,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,1,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,3,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,4,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,6,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,15,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,7,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,8,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,9,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,10,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,12,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,13,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,3,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,4,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,6,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,15,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,7,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,8,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,9,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,10,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,11,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,12,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,13,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,1,1,'Сумма выплат и иных вознаграждений, на-численных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с международными договорами                                                            ')
INSERT #F VALUES (4,2,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с международными договорами                                                                                   ')
INSERT #F VALUES (4,3,1,'Сумма расходов, принимаемых к вычету в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                                       ')
INSERT #F VALUES (4,4,1,'Суммы выплат и иных вознаграждений, превышающие предельную величину базы для начисления страховых взносов
от 24 июля 2009 г. № 212-ФЗ: 1966 г.р. и старше                                                                                                    ')
INSERT #F VALUES (4,5,1,'База для начисления страховых взносов на обязательное пенсионное страхование (с. 200 - с. 201 - с. 202 - с. 203)                                                                                                                                              ')
INSERT #F VALUES (4,6,1,'Начислено страховых взносов на обязательное пенсионное страхование:с сумм, не превышающих предельную базу для начисления страховых взносов                                                                                                                    ')
INSERT #F VALUES (4,7,1,'с сумм, превышающих предельную величину базы для начисления страховых взносов                                                                                                                                                                                 ')
INSERT #F VALUES (4,8,1,'Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы в соответствии с тарифом страховых взносов, всего (чел.)                                                                                                         ')
INSERT #F VALUES (4,9,1,'в том числе количество физических лиц, выплаты и иные вознаграждения которым превысили предельную величину базы для начисления страховых взносов  (чел.)                                                                                                      ')
INSERT #F VALUES (4,10,1,'Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009г. 
№ 212-ФЗ и в соответствии с международными договорами                                                             ')
INSERT #F VALUES (4,11,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии с частями 1, 2 статьи 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с международными договорами                                                                        ')
INSERT #F VALUES (4,12,1,'Сумма расходов, принимаемых к вычету в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                                       ')
INSERT #F VALUES (4,13,1,'Суммы выплат и иных вознаграждений, превышающие предельную величину базы для начисления страховых взносов                                                                                                                                                     ')
INSERT #F VALUES (4,15,1,'Начислено страховых взносов на обязательное медицинское страхование                                                                                                                                                                                           ')
INSERT #F VALUES (4,14,1,'База для начисления страховых взносов на обязательное медицинское страхование (с. 210 - с. 211 - с. 212 - с. 213)                                                                                                                                             ')
INSERT #F VALUES (4,1,2,'2000                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,2,2,'2010                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,3,2,'2020                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,4,2,'2030                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,5,2,'2040                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,6,2,'2050                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,7,2,'2060                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,8,2,'2070                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,9,2,'2080                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,10,2,'2100                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,11,2,'2110                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,12,2,'2120                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,13,2,'2130                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,15,2,'2150                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,14,2,'2140                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,1,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,3,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,4,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,6,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,7,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,8,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,9,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,10,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,12,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,13,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,15,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,3,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,4,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,6,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,7,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,8,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,9,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,10,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,12,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,13,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,15,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,1,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,3,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,4,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,6,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,7,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,8,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,9,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,10,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,12,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,13,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,15,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,3,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,4,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,6,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,7,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,8,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,9,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,10,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,11,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,12,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,13,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,15,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,1,1,'Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ  (по доп.тарифу 1)                                                                                        ')
INSERT #F VALUES (5,2,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. 
№ 212-ФЗ (по доп тарифу 1)                                                                                                            ')
INSERT #F VALUES (5,3,1,'База для начисления страховых взносов по дополнительному тарифу 1(с. 220 - с. 221)                                                                                                                                                                            ')
INSERT #F VALUES (5,4,1,'Начислено страховых взносов по дополнительному тарифу 1                                                                                                                                                                                                       ')
INSERT #F VALUES (5,5,1,'Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу 1 (чел.)                                                                                                                               ')
INSERT #F VALUES (5,6,1,'Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ (по доп тарифу 2)                                                                                         ')
INSERT #F VALUES (5,7,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ (по доп тарифу 2)                                                                                                              ')
INSERT #F VALUES (5,8,1,'База для начисления страховых взносов по дополнительному тарифу 2 (с. 230 - с. 231)                                                                                                                                                                           ')
INSERT #F VALUES (5,9,1,'Начислено страховых взносов по дополнительному тарифу 2                                                                                                                                                                                                       ')
INSERT #F VALUES (5,10,1,'Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу 2 (чел.)                                                                                                                               ')
INSERT #F VALUES (5,1,2,'220                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,2,2,'221                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,3,2,'223                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,4,2,'224                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,5,2,'225                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,6,2,'230                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,7,2,'231                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,8,2,'233                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,9,2,'234                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,10,2,'235                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,1,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,4,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,5,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,6,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,7,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,9,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,10,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,4,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,5,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,6,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,7,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,9,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,10,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,1,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,4,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,5,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,6,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,7,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,9,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,10,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,4,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,5,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,6,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,7,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,9,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,10,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,1,1,'4 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                         ')
INSERT #F VALUES (6,2,1,'4 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                              ')
INSERT #F VALUES (6,5,1,'4 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                               ')
INSERT #F VALUES (6,6,1,'3.4 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                       ')
INSERT #F VALUES (6,7,1,'3.4 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                            ')
INSERT #F VALUES (6,10,1,'3.4 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                             ')
INSERT #F VALUES (6,11,1,'3.3 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                       ')
INSERT #F VALUES (6,12,1,'3.3 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                            ')
INSERT #F VALUES (6,15,1,'3.3 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                             ')
INSERT #F VALUES (6,16,1,'3.2 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                       ')
INSERT #F VALUES (6,17,1,'3.2 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                            ')
INSERT #F VALUES (6,19,1,'3.2 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                              ')
INSERT #F VALUES (6,20,1,'3.2 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                             ')
INSERT #F VALUES (6,21,1,'3.1 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                       ')
INSERT #F VALUES (6,22,1,'3.1 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                            ')
INSERT #F VALUES (6,24,1,'3.1 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                              ')
INSERT #F VALUES (6,25,1,'3.1 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                             ')
INSERT #F VALUES (6,3,1,'4 База для начисления страховых взносов по дополнительному тарифу  (с. 240 - с. 241)                                                                                                                                                                          ')
INSERT #F VALUES (6,4,1,'4 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                                ')
INSERT #F VALUES (6,8,1,'3.4 База для начисления страховых взносов по дополнительному тарифу  (с. 246 - с. 247)                                                                                                                                                                        ')
INSERT #F VALUES (6,9,1,'3.4 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                              ')
INSERT #F VALUES (6,13,1,'3.3 База для начисления страховых взносов по дополнительному тарифу  (с. 252 - с. 253)                                                                                                                                                                        ')
INSERT #F VALUES (6,14,1,'3.3 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                              ')
INSERT #F VALUES (6,18,1,'3.2 База для начисления страховых взносов по дополнительному тарифу  (с. 258 - с. 259)                                                                                                                                                                        ')
INSERT #F VALUES (6,23,1,'3.1 База для начисления страховых взносов по дополнительному тарифу  (с. 264 - с. 265)                                                                                                                                                                        ')
INSERT #F VALUES (6,1,2,'240                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,2,2,'241                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,5,2,'245                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,6,2,'246                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,7,2,'247                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,10,2,'251                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,11,2,'252                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,12,2,'253                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,15,2,'257                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,16,2,'258                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,17,2,'259                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,19,2,'262                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,20,2,'263                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,21,2,'264                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,22,2,'265                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,24,2,'268                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,25,2,'269                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,3,2,'243                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,4,2,'244                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,8,2,'249                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,9,2,'250                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,13,2,'255                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,14,2,'256                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,18,2,'261                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,23,2,'267                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (6,1,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,5,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,6,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,7,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,10,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,12,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,15,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,16,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,17,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,19,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,20,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,21,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,22,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,24,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,25,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,4,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,9,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,14,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (6,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,5,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,6,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,7,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,10,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,12,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,15,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,16,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,17,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,19,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,20,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,21,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,22,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,24,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,25,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,4,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,9,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,14,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (6,1,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,5,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,6,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,7,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,10,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,12,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,15,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,16,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,17,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,19,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,20,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,21,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,22,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,24,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,25,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,4,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,9,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,14,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (6,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,5,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,6,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,7,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,10,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,11,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,12,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,15,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,16,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,17,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,19,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,20,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,21,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,22,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,24,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,25,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,4,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,9,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (6,14,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,1,1,'4 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                         ')
INSERT #F VALUES (7,2,1,'4 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                              ')
INSERT #F VALUES (7,5,1,'4 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                               ')
INSERT #F VALUES (7,6,1,'3.4 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                       ')
INSERT #F VALUES (7,7,1,'3.4 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                            ')
INSERT #F VALUES (7,10,1,'3.4 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                             ')
INSERT #F VALUES (7,11,1,'3.3 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                       ')
INSERT #F VALUES (7,12,1,'3.3 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                            ')
INSERT #F VALUES (7,15,1,'3.3 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                             ')
INSERT #F VALUES (7,16,1,'3.2 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                       ')
INSERT #F VALUES (7,17,1,'3.2 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                            ')
INSERT #F VALUES (7,19,1,'3.2 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                              ')
INSERT #F VALUES (7,20,1,'3.2 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                             ')
INSERT #F VALUES (7,21,1,'3.1 Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                       ')
INSERT #F VALUES (7,22,1,'3.1 Суммы, не подлежащие обложению страховыми взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                                            ')
INSERT #F VALUES (7,24,1,'3.1 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                              ')
INSERT #F VALUES (7,25,1,'3.1 Количество физических лиц, с выплат и иных вознаграждений которым начислены страховые взносы по дополнительному тарифу (чел.)                                                                                                                             ')
INSERT #F VALUES (7,3,1,'4 База для начисления страховых взносов по дополнительному тарифу  (с. 240 - с. 241)                                                                                                                                                                          ')
INSERT #F VALUES (7,4,1,'4 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                                ')
INSERT #F VALUES (7,8,1,'3.4 База для начисления страховых взносов по дополнительному тарифу  (с. 246 - с. 247)                                                                                                                                                                        ')
INSERT #F VALUES (7,9,1,'3.4 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                              ')
INSERT #F VALUES (7,13,1,'3.3 База для начисления страховых взносов по дополнительному тарифу  (с. 252 - с. 253)                                                                                                                                                                        ')
INSERT #F VALUES (7,14,1,'3.3 Начислено страховых взносов по дополнительному тарифу, всего                                                                                                                                                                                              ')
INSERT #F VALUES (7,18,1,'3.2 База для начисления страховых взносов по дополнительному тарифу  (с. 258 - с. 259)                                                                                                                                                                        ')
INSERT #F VALUES (7,23,1,'3.1 База для начисления страховых взносов по дополнительному тарифу  (с. 264 - с. 265)                                                                                                                                                                        ')
INSERT #F VALUES (7,1,2,'2400                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,2,2,'2410                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,5,2,'2450                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,6,2,'2460                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,7,2,'2470                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,10,2,'2510                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,11,2,'2520                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,12,2,'2530                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,15,2,'2570                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,16,2,'2580                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,17,2,'2590                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,19,2,'2620                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,20,2,'2630                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,21,2,'2640                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,22,2,'2650                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,24,2,'2680                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,25,2,'2690                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,3,2,'2430                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,4,2,'2440                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,8,2,'2490                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,9,2,'2500                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,13,2,'2550                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,14,2,'2560                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,18,2,'2610                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,23,2,'2670                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (7,1,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,5,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,6,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,7,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,10,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,12,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,15,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,16,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,17,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,19,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,20,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,21,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,22,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,24,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,25,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,4,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,9,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,14,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (7,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,5,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,6,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,7,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,10,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,12,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,15,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,16,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,17,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,19,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,20,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,21,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,22,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,24,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,25,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,4,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,9,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,14,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (7,1,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,5,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,6,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,7,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,10,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,12,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,15,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,16,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,17,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,19,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,20,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,21,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,22,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,24,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,25,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,4,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,9,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,14,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (7,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,5,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,6,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,7,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,10,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,11,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,12,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,15,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,16,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,17,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,19,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,20,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,21,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,22,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,24,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,25,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,4,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,9,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,14,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (10,1,1,'Численность членов организации, всего (чел.)                                                                                                                                                                                                                  ')
INSERT #F VALUES (10,2,1,'       из них:
численность инвалидов и их законных представителей (чел.)                                                                                                                                                                                     ')
INSERT #F VALUES (10,3,1,'Удельный вес численности инвалидов и их законных представителей в численности членов организации (%) (с. 322 / с. 321) х 100
(с. 322 / с. 321) х 100                                                                                                         ')
INSERT #F VALUES (10,4,1,'Среднесписочная численность физических лиц, всего (чел.)                                                                                                                                                                                                      ')
INSERT #F VALUES (10,5,1,'из них: среднесписочная численность инвалидов (чел.)                                                                                                                                                                                                          ')
INSERT #F VALUES (10,7,1,'Фонд оплаты труда, всего (в рублях)                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,8,1,'из них: заработная плата инвалидов (в рублях)                                                                                                                                                                                                                 ')
INSERT #F VALUES (10,6,1,'Удельный вес инвалидов в среднесписочной численности (%) (с. 332 / с. 331) х 100                                                                                                                                                                              ')
INSERT #F VALUES (10,9,1,'Удельный вес заработной платы инвалидов (%) (с. 335 / с. 334) х 100                                                                                                                                                                                           ')
INSERT #F VALUES (10,1,2,'321                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,2,2,'322                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,3,2,'323                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,4,2,'331                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,5,2,'332                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,7,2,'334                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,8,2,'335                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,6,2,'333                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,9,2,'336                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,4,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (10,5,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (10,4,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (10,5,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (10,4,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (10,5,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (10,4,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (10,5,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (11,1,1,'Сумма доходов, определяемая в соответствии со статьей 248 Налогового кодекса Российской Федерации*, всего (в рублях)                                                                                                                                          ')
INSERT #F VALUES (11,2,1,'      из них:сумма доходов, определяемая исходя из критериев, указанных в пункте 2 части 2.1 или пункте  2 части 2.2 статьи 57 Федерального закона от 24 июля 2009 г. № 212-ФЗ (в рублях)                                                                     ')
INSERT #F VALUES (11,3,1,'Доля доходов, определяемая в целях применения части 5 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%) (с. 342 / с. 341) х 100(с. 342 / с. 341) х 100                                                                                            ')
INSERT #F VALUES (11,4,1,'Средняя численность работников/среднесписочная численность работников (чел.)
среднесписочная численность работников**(чел.)                                                                                                                                  ')
INSERT #F VALUES (11,5,1,'Сведения из реестра аккредитованных организаций, осуществляющих деятельность в
области информационных технологий **                                                                                                                                          ')
INSERT #F VALUES (11,1,2,'341                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,2,2,'342                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,3,2,'343                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,4,2,'344                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,5,2,'345                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (11,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (11,1,5,'ЗАПРЕТ()')
INSERT #F VALUES (11,2,5,'ЗАПРЕТ()')
INSERT #F VALUES (11,3,5,'ЗАПРЕТ()')
INSERT #F VALUES (11,4,5,'ЗАПРЕТ()')
INSERT #F VALUES (11,1,6,'ЗАПРЕТ()')
INSERT #F VALUES (11,2,6,'ЗАПРЕТ()')
INSERT #F VALUES (11,3,6,'ЗАПРЕТ()')
INSERT #F VALUES (11,4,6,'ЗАПРЕТ()')
INSERT #F VALUES (12,1,1,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,2,1,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,3,1,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,4,1,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,5,1,'5                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,6,1,'6                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,7,1,'7                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,8,1,'8                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,9,1,'9                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (12,10,1,'10                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (12,12,1,'Сведения из реестра СМИ**                                                                                                                                                                                                                                     ')
INSERT #F VALUES (12,11,3,'Итого по всем видам деятельности')
INSERT #F VALUES (12,1,4,'350a                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,2,4,'350b                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,3,4,'350c                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,4,4,'350d                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,5,4,'350e                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,6,4,'350f                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,7,4,'350g                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,8,4,'350h                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,9,4,'350j                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,10,4,'350k                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,11,4,'350l                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (12,12,4,'351                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (12,12,5,'ЗАПРЕТ()')
INSERT #F VALUES (12,11,6,'ЗАПРЕТ()')
INSERT #F VALUES (12,12,6,'ЗАПРЕТ()')
INSERT #F VALUES (12,1,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,2,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,6,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,7,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,8,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,9,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,10,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,11,7,'ЗАПРЕТ()')
INSERT #F VALUES (12,1,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,2,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,3,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,4,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,5,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,6,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,7,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,8,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,9,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,10,8,'ЗАПРЕТ()')
INSERT #F VALUES (12,11,8,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,1,'Сумма доходов, определяемая в соответствии со статьей 346.15 Налогового кодекса Российской Федерации, всего (в рублях)                                                                                                                                        ')
INSERT #F VALUES (13,2,1,'из них: сумма доходов, определяемая  в целях применения части 1.4 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (в рублях)                                                                                                                        ')
INSERT #F VALUES (13,3,1,'Доля доходов, определяемая  в целях применения части 1.4  статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%)
(с. 362 / с. 361) х 100                                                                                                              ')
INSERT #F VALUES (13,4,1,'Сумма доходов*, всего (в рублях)                                                                                                                                                                                                                              ')
INSERT #F VALUES (13,5,1,'из них:сумма доходов в виде целевых поступлений на содерж. некоммерч. орг. и ведение ими уставной деят-ти, поименованной в п.11 ч.1 ст.58 Федерального закона от 24.07.2009 г. №212-ФЗ,опред. в соответ. с п.2 ст.251  НК РФ (в рублях)                       ')
INSERT #F VALUES (13,6,1,'сумма доходов в виде грантов, получ. для осуществления деят-ти, поименованной в п.11 ч.1 ст.58 № 212-ФЗ от 24 июля 2009 г. определяемых в соответствии с подпунктом 14 пункта 1 статьи 251 НК РФ(в рублях)                                                    ')
INSERT #F VALUES (13,7,1,'сумма доходов от осуществления видов экономической деятельности, указанных в подпунктах «р» - «ф», «я.4» - «я.6» пункта 8 части 1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (в рублях)                                                        ')
INSERT #F VALUES (13,8,1,'Доля доходов, определяемая в целях применения части 5.1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%) (с. 372 + с. 373 + с.374) / с. 371 х 100                                                                                                ')
INSERT #F VALUES (13,1,2,'361                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,2,2,'362                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,3,2,'363                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,4,2,'371                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,5,2,'372                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,6,2,'373                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,7,2,'374                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,8,2,'375                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,4,3,'ЗАПРЕТ()')
INSERT #F VALUES (13,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (13,6,3,'ЗАПРЕТ()')
INSERT #F VALUES (13,7,3,'ЗАПРЕТ()')
INSERT #F VALUES (13,8,3,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,2,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,3,4,'ЗАПРЕТ()')
INSERT #F VALUES (13,1,5,'ЗАПРЕТ()')
INSERT #F VALUES (13,2,5,'ЗАПРЕТ()')
INSERT #F VALUES (13,3,5,'ЗАПРЕТ()')
INSERT #F VALUES (16,1,1,'Сведения из реестра молодежных и детских общественных объединений, пользующихся государственной поддержкой                                                                                                                                                    ')
INSERT #F VALUES (16,1,2,'501                                                                                                                                                                                                                                                           ')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 677
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'т.2стр.114гр.3 =  т.2стр.111гр.3 +  т.2стр.112гр.3 +  т.2стр.113гр.3',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(2,NULL,0,NULL,2,7,0,0,0,'т.2стр.114гр.6 =  т.2стр.111гр.6 +  т.2стр.112гр.6 +  т.2стр.113гр.6',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(3,NULL,0,NULL,3,7,0,0,0,'т.2стр.114гр.7 =  т.2стр.111гр.7 +  т.2стр.112гр.7 +  т.2стр.113гр.7',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(4,NULL,0,NULL,4,7,0,0,0,'т.2стр.114гр.8 =  т.2стр.111гр.8 +  т.2стр.112гр.8 +  т.2стр.113гр.8',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(5,NULL,0,NULL,5,7,0,0,0,'т.2стр.130гр.3 =  т.2стр.100гр.3 +  т.2стр.110гр.3 +  т.2стр.120гр.3',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(6,NULL,0,NULL,6,7,0,0,0,'т.2стр.130гр.4 =  т.2стр.100гр.4 +  т.2стр.110гр.4 +  т.2стр.120гр.4',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(7,NULL,0,NULL,7,7,0,0,0,'т.2стр.130гр.5 =  т.2стр.100гр.5 +  т.2стр.110гр.5 +  т.2стр.120гр.5',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(8,NULL,0,NULL,8,7,0,0,0,'т.2стр.130гр.6 =  т.2стр.100гр.6 +  т.2стр.110гр.6 +  т.2стр.120гр.6',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(9,NULL,0,NULL,9,7,0,0,0,'т.2стр.130гр.7 =  т.2стр.100гр.7 +  т.2стр.110гр.7 +  т.2стр.120гр.7',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(10,NULL,0,NULL,10,7,0,0,0,'т.2стр.130гр.8 =  т.2стр.100гр.8 +  т.2стр.110гр.8 +  т.2стр.120гр.8',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(11,NULL,0,NULL,11,7,0,0,0,'т.2стр.144гр.3 =  т.2стр.141гр.3 +  т.2стр.142гр.3 +  т.2стр.143гр.3',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(12,NULL,0,NULL,12,7,0,0,0,'т.2стр.144гр.4 =  т.2стр.141гр.4 +  т.2стр.142гр.4 +  т.2стр.143гр.4',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(13,NULL,0,NULL,13,7,0,0,0,'т.2стр.144гр.5 =  т.2стр.141гр.5 +  т.2стр.142гр.5 +  т.2стр.143гр.5',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(14,NULL,0,NULL,14,7,0,0,0,'т.2стр.144гр.5 =  т.2стр.141гр.5 +  т.2стр.142гр.5 +  т.2стр.143гр.5',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(15,NULL,0,NULL,15,7,0,0,0,'т.2стр.144гр.6 =  т.2стр.141гр.6 +  т.2стр.142гр.6 +  т.2стр.143гр.6',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(16,NULL,0,NULL,16,7,0,0,0,'т.2стр.144гр.7 =  т.2стр.141гр.7 +  т.2стр.142гр.7 +  т.2стр.143гр.7',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(17,NULL,0,NULL,17,7,0,0,0,'т.2стр.144гр.8 =  т.2стр.141гр.8 +  т.2стр.142гр.8 +  т.2стр.143гр.8',1,11,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(18,NULL,0,NULL,18,7,0,0,0,'т.2стр.150гр.3 =  т.2стр.130гр.3 -  т.2стр.140гр.3',1,12,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(19,NULL,0,NULL,19,7,0,0,0,'т.2стр.150гр.4 =  т.2стр.130гр.4 -  т.2стр.140гр.4',1,12,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(20,NULL,0,NULL,20,7,0,0,0,'т.2стр.150гр.5 =  т.2стр.130гр.5 -  т.2стр.140гр.5',1,12,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(21,NULL,0,NULL,21,7,0,0,0,'т.2стр.150гр.6 =  т.2стр.130гр.6 -  т.2стр.140гр.6',1,12,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(22,NULL,0,NULL,22,7,0,0,0,'т.2стр.150гр.7 =  т.2стр.130гр.7 -  т.2стр.140гр.7',1,12,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(23,NULL,0,NULL,23,7,0,0,0,'т.2стр.150гр.8 =  т.2стр.130гр.8 -  т.2стр.140гр.8',1,12,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(24,NULL,0,NULL,24,7,0,0,0,'т.2стр.110гр.3 =  т.3стр.205гр.3 +  т.3стр.206гр.3 +  т.4стр.2050гр.3 +  т.4стр.2060гр.3',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(25,NULL,0,NULL,25,7,0,0,0,'т.2стр.110гр.6 =  т.5стр.224гр.3 +  т.6стр.244гр.3 +  т.6стр.250гр.3 +  т.6стр.256гр.3 +  т.6стр.262гр.3 +  т.6стр.268гр.3',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(26,NULL,0,NULL,26,7,0,0,0,'т.2стр.110гр.7 =  т.5стр.234гр.3 +  т.7стр.2440гр.3 +  т.7стр.2500гр.3 +  т.7стр.2560гр.3 +  т.7стр.2620гр.3 +  т.7стр.2680гр.3',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(27,NULL,0,NULL,27,7,0,0,0,'т.2стр.110гр.8 =  т.3стр.215гр.3 +  т.4стр.2150гр.3',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(28,NULL,0,NULL,28,7,0,0,0,'т.2стр.111гр.3 =  т.3стр.205гр.4 +  т.3стр.206гр.4 +  т.4стр.2050гр.4 +  т.4стр.2060гр.4',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(29,NULL,0,NULL,29,7,0,0,0,'т.2стр.112гр.3 =  т.3стр.205гр.5 +  т.3стр.206гр.5 +  т.4стр.2050гр.5 +  т.4стр.2060гр.5',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(30,NULL,0,NULL,30,7,0,0,0,'т.2стр.113гр.3 =  т.3стр.205гр.6 +  т.3стр.206гр.6 +  т.4стр.2050гр.6 +  т.4стр.2060гр.6',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(31,NULL,0,NULL,31,7,0,0,0,'т.2стр.111гр.6 =  т.5стр.224гр.4 +  т.6стр.244гр.4 +  т.6стр.250гр.4 +  т.6стр.256гр.4 +  т.6стр.262гр.4 +  т.6стр.268гр.4',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(32,NULL,0,NULL,32,7,0,0,0,'т.2стр.112гр.6 =  т.5стр.224гр.5 +  т.6стр.244гр.5 +  т.6стр.250гр.5 +  т.6стр.256гр.5 +  т.6стр.262гр.5 +  т.6стр.268гр.5',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(33,NULL,0,NULL,33,7,0,0,0,'т.2стр.113гр.6 =  т.5стр.224гр.6 +  т.6стр.244гр.6 +  т.6стр.250гр.6 +  т.6стр.256гр.6 +  т.6стр.262гр.6 +  т.6стр.268гр.6',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(34,NULL,0,NULL,34,7,0,0,0,'т.2стр.111гр.7 =  т.5стр.234гр.4 +  т.7стр.2440гр.4 +  т.7стр.2500гр.4 +  т.7стр.2560гр.4 +  т.7стр.2620гр.4 +  т.7стр.2680гр.4',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(35,NULL,0,NULL,35,7,0,0,0,'т.2стр.112гр.7 =  т.5стр.234гр.5 +  т.7стр.2440гр.5 +  т.7стр.2500гр.5 +  т.7стр.2560гр.5 +  т.7стр.2620гр.5 +  т.7стр.2680гр.5',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(36,NULL,0,NULL,36,7,0,0,0,'т.2стр.113гр.7 =  т.5стр.234гр.6 +  т.7стр.2440гр.6 +  т.7стр.2500гр.6 +  т.7стр.2560гр.6 +  т.7стр.2620гр.6 +  т.7стр.2680гр.6',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(37,NULL,0,NULL,37,7,0,0,0,'т.2стр.111гр.8 =  т.3стр.215гр.4 +  т.4стр.2150гр.4',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(38,NULL,0,NULL,38,7,0,0,0,'т.2стр.112гр.8 =  т.3стр.215гр.5 +  т.4стр.2150гр.5',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(39,NULL,0,NULL,39,7,0,0,0,'т.2стр.113гр.8 =  т.3стр.215гр.6 +  т.4стр.2150гр.6',1,10,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(40,NULL,0,NULL,40,7,0,0,0,'т.3стр.204гр.3 =  т.3стр.200гр.3 -  т.3стр.201гр.3 -  т.3стр.202гр.3 -  т.3стр.203гр.3',1,0,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(41,NULL,0,NULL,41,7,0,0,0,'т.3стр.204гр.4 =  т.3стр.200гр.4 -  т.3стр.201гр.4 -  т.3стр.202гр.4 -  т.3стр.203гр.4',1,0,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(42,NULL,0,NULL,42,7,0,0,0,'т.3стр.204гр.5 =  т.3стр.200гр.5 -  т.3стр.201гр.5 -  т.3стр.202гр.5 -  т.3стр.203гр.5',1,0,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(43,NULL,0,NULL,43,7,0,0,0,'т.3стр.204гр.6 =  т.3стр.200гр.6 -  т.3стр.201гр.6 -  т.3стр.202гр.6 -  т.3стр.203гр.6',1,0,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(44,NULL,0,NULL,44,7,0,0,0,'т.4стр.2040гр.3 =  т.4стр.2000гр.3 -  т.4стр.2010гр.3 -  т.4стр.2020гр.3 -  т.4стр.2030гр.3',1,0,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(45,NULL,0,NULL,45,7,0,0,0,'т.4стр.2040гр.4 =  т.4стр.2000гр.4 -  т.4стр.2010гр.4 -  т.4стр.2020гр.4 -  т.4стр.2030гр.4',1,0,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(46,NULL,0,NULL,46,7,0,0,0,'т.4стр.2040гр.5 =  т.4стр.2000гр.5 -  т.4стр.2010гр.5 -  т.4стр.2020гр.5 -  т.4стр.2030гр.5',1,0,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(47,NULL,0,NULL,47,7,0,0,0,'т.4стр.2040гр.6 =  т.4стр.2000гр.6 -  т.4стр.2010гр.6 -  т.4стр.2020гр.6 -  т.4стр.2030гр.6',1,0,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(48,NULL,0,NULL,48,7,0,0,0,'т.3стр.214гр.3 =  т.3стр.210гр.3 -  т.3стр.211гр.3 -  т.3стр.212гр.3 -  т.3стр.213гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(49,NULL,0,NULL,49,7,0,0,0,'т.3стр.214гр.4 =  т.3стр.210гр.4 -  т.3стр.211гр.4 -  т.3стр.212гр.4 -  т.3стр.213гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(50,NULL,0,NULL,50,7,0,0,0,'т.3стр.214гр.5 =  т.3стр.210гр.5 -  т.3стр.211гр.5 -  т.3стр.212гр.5 -  т.3стр.213гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(51,NULL,0,NULL,51,7,0,0,0,'т.3стр.214гр.6 =  т.3стр.210гр.6 -  т.3стр.211гр.6 -  т.3стр.212гр.6 -  т.3стр.213гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(52,NULL,0,NULL,52,7,0,0,0,'т.4стр.2140гр.3 =  т.4стр.2100гр.3 -  т.4стр.2110гр.3 -  т.4стр.2120гр.3 -  т.4стр.2130гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(53,NULL,0,NULL,53,7,0,0,0,'т.4стр.2140гр.4 =  т.4стр.2100гр.4 -  т.4стр.2110гр.4 -  т.4стр.2120гр.4 -  т.4стр.2130гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(54,NULL,0,NULL,54,7,0,0,0,'т.4стр.2140гр.5 =  т.4стр.2100гр.5 -  т.4стр.2110гр.5 -  т.4стр.2120гр.5 -  т.4стр.2130гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(55,NULL,0,NULL,55,7,0,0,0,'т.4стр.2140гр.6 =  т.4стр.2100гр.6 -  т.4стр.2110гр.6 -  т.4стр.2120гр.6 -  т.4стр.2130гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(56,NULL,0,NULL,56,7,0,0,0,'т.5стр.223гр.3 =  т.5стр.220гр.3 -  т.5стр.221гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(57,NULL,0,NULL,57,7,0,0,0,'т.5стр.223гр.4 =  т.5стр.220гр.4 -  т.5стр.221гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(58,NULL,0,NULL,58,7,0,0,0,'т.5стр.223гр.5 =  т.5стр.220гр.5 -  т.5стр.221гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(59,NULL,0,NULL,59,7,0,0,0,'т.5стр.223гр.6 =  т.5стр.220гр.6 -  т.5стр.221гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(60,NULL,0,NULL,60,7,0,0,0,'т.5стр.233гр.3 =  т.5стр.230гр.3 -  т.5стр.231гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(61,NULL,0,NULL,61,7,0,0,0,'т.5стр.233гр.4 =  т.5стр.230гр.4 -  т.5стр.231гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(62,NULL,0,NULL,62,7,0,0,0,'т.5стр.233гр.5 =  т.5стр.230гр.5 -  т.5стр.231гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(63,NULL,0,NULL,63,7,0,0,0,'т.5стр.233гр.6 =  т.5стр.230гр.6 -  т.5стр.231гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(64,NULL,0,NULL,64,7,0,0,0,'т.6стр.243гр.3 =  т.6стр.240гр.3 -  т.6стр.241гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(65,NULL,0,NULL,65,7,0,0,0,'т.6стр.243гр.4 =  т.6стр.240гр.4 -  т.6стр.241гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(66,NULL,0,NULL,66,7,0,0,0,'т.6стр.243гр.5 =  т.6стр.240гр.5 -  т.6стр.241гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(67,NULL,0,NULL,67,7,0,0,0,'т.6стр.243гр.6 =  т.6стр.240гр.6 -  т.6стр.241гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(68,NULL,0,NULL,68,7,0,0,0,'т.6стр.249гр.3 =  т.6стр.246гр.3 -  т.6стр.247гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(69,NULL,0,NULL,69,7,0,0,0,'т.6стр.249гр.4 =  т.6стр.246гр.4 -  т.6стр.247гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(70,NULL,0,NULL,70,7,0,0,0,'т.6стр.249гр.5 =  т.6стр.246гр.5 -  т.6стр.247гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(71,NULL,0,NULL,71,7,0,0,0,'т.6стр.249гр.6 =  т.6стр.246гр.6 -  т.6стр.247гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(72,NULL,0,NULL,72,7,0,0,0,'т.6стр.255гр.3 =  т.6стр.252гр.3 -  т.6стр.253гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(73,NULL,0,NULL,73,7,0,0,0,'т.6стр.255гр.4 =  т.6стр.252гр.4 -  т.6стр.253гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(74,NULL,0,NULL,74,7,0,0,0,'т.6стр.255гр.5 =  т.6стр.252гр.5 -  т.6стр.253гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(75,NULL,0,NULL,75,7,0,0,0,'т.6стр.255гр.6 =  т.6стр.252гр.6 -  т.6стр.253гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(76,NULL,0,NULL,76,7,0,0,0,'т.6стр.261гр.3 =  т.6стр.258гр.3 -  т.6стр.259гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(77,NULL,0,NULL,77,7,0,0,0,'т.6стр.261гр.4 =  т.6стр.258гр.4 -  т.6стр.259гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(78,NULL,0,NULL,78,7,0,0,0,'т.6стр.261гр.5 =  т.6стр.258гр.5 -  т.6стр.259гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(79,NULL,0,NULL,79,7,0,0,0,'т.6стр.261гр.6 =  т.6стр.258гр.6 -  т.6стр.259гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(80,NULL,0,NULL,80,7,0,0,0,'т.6стр.267гр.3 =  т.6стр.264гр.3 -  т.6стр.265гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(81,NULL,0,NULL,81,7,0,0,0,'т.6стр.267гр.4 =  т.6стр.264гр.4 -  т.6стр.265гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(82,NULL,0,NULL,82,7,0,0,0,'т.6стр.267гр.5 =  т.6стр.264гр.5 -  т.6стр.265гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(83,NULL,0,NULL,83,7,0,0,0,'т.6стр.267гр.6 =  т.6стр.264гр.6 -  т.6стр.265гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(84,NULL,0,NULL,84,7,0,0,0,'т.7стр.2430гр.3 =  т.7стр.2400гр.3 -  т.7стр.2410гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(85,NULL,0,NULL,85,7,0,0,0,'т.7стр.2430гр.4 =  т.7стр.2400гр.4 -  т.7стр.2410гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(86,NULL,0,NULL,86,7,0,0,0,'т.7стр.2430гр.5 =  т.7стр.2400гр.5 -  т.7стр.2410гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(87,NULL,0,NULL,87,7,0,0,0,'т.7стр.2430гр.6 =  т.7стр.2400гр.6 -  т.7стр.2410гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(88,NULL,0,NULL,88,7,0,0,0,'т.7стр.2490гр.3 =  т.7стр.2460гр.3 -  т.7стр.2470гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(89,NULL,0,NULL,89,7,0,0,0,'т.7стр.2490гр.4 =  т.7стр.2460гр.4 -  т.7стр.2470гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(90,NULL,0,NULL,90,7,0,0,0,'т.7стр.2490гр.5 =  т.7стр.2460гр.5 -  т.7стр.2470гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(91,NULL,0,NULL,91,7,0,0,0,'т.7стр.2490гр.6 =  т.7стр.2460гр.6 -  т.7стр.2470гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(92,NULL,0,NULL,92,7,0,0,0,'т.7стр.2550гр.3 =  т.7стр.2520гр.3 -  т.7стр.2530гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(93,NULL,0,NULL,93,7,0,0,0,'т.7стр.2550гр.4 =  т.7стр.2520гр.4 -  т.7стр.2530гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(94,NULL,0,NULL,94,7,0,0,0,'т.7стр.2550гр.5 =  т.7стр.2520гр.5 -  т.7стр.2530гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(95,NULL,0,NULL,95,7,0,0,0,'т.7стр.2550гр.6 =  т.7стр.2520гр.6 -  т.7стр.2530гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(96,NULL,0,NULL,96,7,0,0,0,'т.7стр.2670гр.3 =  т.7стр.2640гр.3 -  т.7стр.2650гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(97,NULL,0,NULL,97,7,0,0,0,'т.7стр.2670гр.4 =  т.7стр.2640гр.4 -  т.7стр.2650гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(98,NULL,0,NULL,98,7,0,0,0,'т.7стр.2670гр.5 =  т.7стр.2640гр.5 -  т.7стр.2650гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(99,NULL,0,NULL,99,7,0,0,0,'т.7стр.2670гр.6 =  т.7стр.2640гр.6 -  т.7стр.2650гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(100,NULL,0,NULL,100,7,0,0,0,'т.10стр.323гр.3 =  т.10стр.322гр.3 /  т.10стр.321гр.3 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(101,NULL,0,NULL,101,7,0,0,0,'т.10стр.323гр.4 =  т.10стр.322гр.4 /  т.10стр.321гр.4 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(102,NULL,0,NULL,102,7,0,0,0,'т.10стр.323гр.5 =  т.10стр.322гр.5 /  т.10стр.321гр.5 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(103,NULL,0,NULL,103,7,0,0,0,'т.10стр.323гр.6 =  т.10стр.322гр.6 /  т.10стр.321гр.6 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(104,NULL,0,NULL,104,7,0,0,0,'т.10стр.333гр.3 =  т.10стр.332гр.3 /  т.10стр.331гр.3 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(105,NULL,0,NULL,105,7,0,0,0,'т.10стр.333гр.4 =  т.10стр.332гр.4 /  т.10стр.331гр.4 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(106,NULL,0,NULL,106,7,0,0,0,'т.10стр.333гр.5 =  т.10стр.332гр.5 /  т.10стр.331гр.5 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(107,NULL,0,NULL,107,7,0,0,0,'т.10стр.333гр.6 =  т.10стр.332гр.6 /  т.10стр.331гр.6 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(108,NULL,0,NULL,108,7,0,0,0,'т.10стр.336гр.3 =  т.10стр.335гр.3 /  т.10стр.334гр.3 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(109,NULL,0,NULL,109,7,0,0,0,'т.10стр.336гр.4 =  т.10стр.335гр.4 /  т.10стр.334гр.4 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(110,NULL,0,NULL,110,7,0,0,0,'т.10стр.336гр.5 =  т.10стр.335гр.5 /  т.10стр.334гр.5 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(111,NULL,0,NULL,111,7,0,0,0,'т.10стр.336гр.6 =  т.10стр.335гр.6 /  т.10стр.334гр.6 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(112,NULL,0,NULL,112,7,0,0,0,'т.11стр.343гр.3 =  т.11стр.342гр.3 /  т.11стр.341гр.3 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(113,NULL,0,NULL,113,7,0,0,0,'т.11стр.343гр.4 =  т.11стр.342гр.4 /  т.11стр.341гр.4 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(114,NULL,0,NULL,114,7,0,0,0,'т.13стр.363гр.3 =  т.13стр.362гр.3 /  т.13стр.361гр.3 *  100',1,1,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(115,NULL,0,NULL,115,7,0,0,0,'т.13стр.375гр.4 =  т.13стр.372гр.4 +  т.13стр.373гр.4 +  т.13стр.374гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(116,NULL,0,NULL,116,7,0,0,0,'т.13стр.375гр.4 =  т.13стр.375гр.4 /  т.13стр.371гр.4 *  100',1,2,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(117,NULL,0,NULL,117,7,0,0,0,'т.13стр.375гр.5 =  т.13стр.372гр.5 +  т.13стр.373гр.5 +  т.13стр.374гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(118,NULL,0,NULL,118,7,0,0,0,'т.13стр.375гр.5 =  т.13стр.375гр.5 /  т.13стр.371гр.5 *  100',1,2,1,'20140415','','','','РСВ-1','20140101','','=',0,'','')
INSERT #A VALUES(119,NULL,0,NULL,119,7,0,0,0,'т.7стр.2610гр.3 =  т.7стр.2580гр.3 -  т.7стр.2590гр.3',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(120,NULL,0,NULL,120,7,0,0,0,'т.7стр.2610гр.4 =  т.7стр.2580гр.4 -  т.7стр.2590гр.4',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(121,NULL,0,NULL,121,7,0,0,0,'т.7стр.2610гр.5 =  т.7стр.2580гр.5 -  т.7стр.2590гр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(122,NULL,0,NULL,122,7,0,0,0,'т.7стр.2610гр.6 =  т.7стр.2580гр.6 -  т.7стр.2590гр.6',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
INSERT #A VALUES(123,NULL,0,NULL,123,7,0,0,0,'т.12стр.350lгр.5 =  т.12стр.350aгр.5 +  т.12стр.350bгр.5 +  т.12стр.350cгр.5 +  т.12стр.350dгр.5 +  т.12стр.350eгр.5 +  т.12стр.350fгр.5 +  т.12стр.350gгр.5 +  т.12стр.350jгр.5 +  т.12стр.350kгр.5',1,1,1,'20140415','','','','РСВ-1','20140101','','=',1,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 123
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','205','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','206','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2050','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2060','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','224','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','244','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','250','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','256','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','262','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','268','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(26,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','234','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2440','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2500','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2560','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2620','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2680','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(27,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','215','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2150','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(28,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','205','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','206','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2050','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2060','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(29,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','205','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','206','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2050','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2060','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(30,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','205','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','206','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2050','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2060','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(31,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','224','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','244','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','250','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','256','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','262','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','268','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(32,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','224','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','244','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','250','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','256','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','262','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','268','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(33,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','224','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','244','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','250','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','256','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','262','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','268','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(34,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','234','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2440','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2500','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2560','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2620','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2680','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(35,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','234','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2440','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2500','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2560','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2620','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2680','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(36,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','234','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2440','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2500','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2560','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2620','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2680','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(37,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','215','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2150','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(38,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','215','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2150','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','8','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(39,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','215','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2150','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','204','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(40,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','200','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','203','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','204','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(41,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','200','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','203','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','204','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(42,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','200','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','203','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','204','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(43,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','200','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','203','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2040','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(44,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2000','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2010','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2020','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2030','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2040','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(45,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2000','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2010','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2020','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2030','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2040','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(46,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2000','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2010','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2020','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2030','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2040','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(47,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2000','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2010','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2020','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2030','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','214','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(48,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','210','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','213','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','214','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(49,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','210','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','213','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','214','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(50,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','210','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','213','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','214','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(51,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','210','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','213','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2140','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(52,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2100','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2110','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2120','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2130','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2140','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(53,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2100','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2110','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2120','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2130','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2140','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(54,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2100','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2110','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2120','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2130','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2140','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(55,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2100','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2110','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2120','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2130','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','223','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(56,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','220','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','221','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','223','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(57,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','220','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','221','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','223','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(58,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','220','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','221','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','223','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(59,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','220','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','221','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','233','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(60,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','230','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','231','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','233','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(61,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','230','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','231','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','233','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(62,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','230','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','231','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','233','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(63,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','230','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','231','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','243','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(64,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','240','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','241','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','243','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(65,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','240','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','241','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','243','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(66,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','240','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','241','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','243','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(67,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','240','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','241','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(68,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','249','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(68,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','246','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(68,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','247','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(69,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','249','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(69,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','246','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(69,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','247','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','249','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(70,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','246','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','247','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','249','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(71,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','246','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','247','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','255','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(72,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','252','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','253','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','255','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(73,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','252','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','253','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','255','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(74,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','252','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','253','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','255','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(75,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','252','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','253','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','261','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(76,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','258','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','259','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','261','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(77,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','258','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','259','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','261','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(78,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','258','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','259','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','261','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(79,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','258','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','259','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','267','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(80,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','264','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','265','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','267','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(81,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','264','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','265','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','267','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(82,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','264','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','265','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','267','6',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(83,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','264','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','265','6',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(84,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2430','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(84,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2400','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(84,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2410','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(85,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2430','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(85,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2400','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(85,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2410','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(86,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2430','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(86,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2400','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(86,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2410','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(87,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2430','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(87,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2400','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(87,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2410','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2490','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(88,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2460','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2470','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2490','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(89,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2460','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2470','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2490','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(90,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2460','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2470','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2490','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(91,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2460','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2470','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2550','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(92,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2520','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(92,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2530','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(93,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2550','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(93,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2520','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(93,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2530','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2550','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(94,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2520','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(94,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2530','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2550','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(95,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2520','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(95,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2530','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2670','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(96,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2640','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(96,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2650','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2670','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(97,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2640','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(97,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2650','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2670','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(98,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2640','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(98,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2650','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(99,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2670','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(99,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2640','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(99,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2650','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','323','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(100,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','322','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','321','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(100,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','323','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(101,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','322','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','321','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(101,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','323','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(102,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','322','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','321','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(102,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','323','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(103,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','322','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','321','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(103,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','333','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(104,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','332','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','331','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(104,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','333','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(105,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','332','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','331','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(105,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','333','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(106,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','332','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','331','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(106,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','333','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(107,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','332','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','331','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(107,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','336','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(108,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','335','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','334','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(108,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','336','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(109,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','335','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','334','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(109,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','336','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(110,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','335','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','334','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(110,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','336','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(111,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','335','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','334','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(111,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','343','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(112,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','342','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','341','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(112,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','343','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(113,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','342','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','341','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(113,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','363','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(114,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','362','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','361','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(114,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','375','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(115,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','372','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','373','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(115,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','374','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','375','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(116,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','375','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','371','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(116,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','375','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(117,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','372','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','373','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(117,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','374','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(118,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','375','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(118,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','375','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(118,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','371','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(118,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(119,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2610','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(119,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2580','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(119,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2590','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(120,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2610','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(120,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2580','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(120,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2590','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(121,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2610','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(121,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2580','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(121,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2590','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(122,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2610','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(122,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2580','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(122,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2590','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350l','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(123,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350a','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350b','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350c','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350d','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350e','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350f','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350g','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,9,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350j','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(123,10,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350k','12',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 484
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '3         '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'3','Квартальные формы',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-07-24 12:25:27.753',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-07-24 12:25:27.753'
	BEGIN
		SELECT @vcMessage = 'Форма РСВ-1 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма РСВ-1 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-07-24 12:25:27.753. Обновление отклонено.'
	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
-- Отчет "Табель"
-- Сгенерировано скриптом scriptObjectVar 'SYS_T13_FORM'

/*** Сам отчет ***/

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= 'SYS_T13_FORM'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'SYS_T13_FORM'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Табель',101, 
	(Select link from object_var where code = 'KADRY_SQL_CATALOG'),
	'SYS_T13_FORM',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'SYS_T13_FORM') 
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= '	EXEC KIR_EXEC_KADR_TABEL_REPORT 
		''SYS_T13_FORM_MAIN_PARAM'', 
		@nOption2, 
		@nCheck1,
		@nCombo1 /* Сортировка №3 */,
		@nCheck3  /* ФИО полностью */,
		@nCheck5 /* Пустой табель */,
              @nOption1 /* Форма табеля */
'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#REP_TABEL'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(@nOption1 = 2,"FORM-T13SOCR.XLT",IIF(@nOption1 = 3,"F-0504421K.XLT",IIF(@nOption1 = 4,"TabelCompact.xlt",IIF(@nOption1 =5,"FORM-T12.xlt",IIF(@nOption1 = 7,"F-0504421(148n).XLT",IIF(@nOption1 = 6,"F-0504421M.XLT",IIF(@nOption1 = 1,"FORM-T13.XLT",IIF(@nOption1 = 8,"TabelCompact_NEW.xlt",""))))))))'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #REP_TABEL
	@cText1 varchar(8000)	/* Ссылка на документ */,
	@nOption1 int	/* Форма табеля */,
	@nOption2 int	/* Сортировка №1 */,
	@nCheck1 int	/* Сортировка №2 */,
	@nCombo1 int	/* Сортировка №3 */,
	@nCheck2 int	/* Группа с новой страницы */,
	@nCheck3 int	/* ФИО полностью */,
	@nCheck4 int	/* Формат А3 */,
	@nCheck5 int	/* Пустой табель */
AS
BEGIN

	EXEC KIR_EXEC_KADR_TABEL_REPORT 
		''SYS_T13_FORM_MAIN_PARAM'', 
		@nOption2, 
		@nCheck1,
		@nCombo1 /* Сортировка №3 */,
		@nCheck3  /* ФИО полностью */,
		@nCheck5 /* Пустой табель */,
              @nOption1 /* Форма табеля */


END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	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 = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADD_MODULE'),
	VALUE= 'KIRREPTABEL.BAS'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SYS_T13_FORM') 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 = 'SYS_T13_FORM'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SYS_T13_FORM_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 = 'SYS_T13_FORM'),
		'SYS_T13_FORM_NASTR_GR',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SYS_T13_FORM_MAIN_PARAM' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_TEXTBOX'),
					'Ссылка на документ',2, 
					(Select link from object_var where code = 'SYS_T13_FORM_NASTR_GR'),
					'SYS_T13_FORM_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 = 'SYS_T13_FORM_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SYS_T13_FORM_NASTR2' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_OPTIONGROUP'),
					'Форма табеля',3, 
					(Select link from object_var where code = 'SYS_T13_FORM_NASTR_GR'),
					'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'OPTIONGROUP'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'форма №Т-13,форма №Т-13(сжатая),форма №421,компактная форма,форма №Т-12,форма №421(сжатая),форма №421(148н),компактная форма(новая)'
						
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 = 'SYS_T13_FORM_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nOption1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'форма №421(148н)'
						
						
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 = 'SYS_T13_FORM_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SYS_T13_FORM_NASTR3' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_OPTIONGROUP'),
					'Сортировка №1',4, 
					(Select link from object_var where code = 'SYS_T13_FORM_NASTR_GR'),
					'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR3'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR3'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR3'),
							(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 = 'SYS_T13_FORM_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'COMBOBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nOption2'
						
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 = 'SYS_T13_FORM_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'по табельному номеру'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'по табельному номеру'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'по табельному номеру'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR3'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR3'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SYS_T13_FORM_NASTR4' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Сортировка №2',5, 
					(Select link from object_var where code = 'SYS_T13_FORM_NASTR_GR'),
					'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR4'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR4'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR4'),
							(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 = 'SYS_T13_FORM_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'COMBOBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR4'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR4') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR4'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SYS_T13_FORM_NASTR5' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Группа с новой страницы',7, 
					(Select link from object_var where code = 'SYS_T13_FORM_NASTR_GR'),
					'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR5'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							'Группа записей из первой сортировки будет начинаться с новой страницы, если задана вторая сортировка.
Не работает совместно с опцией "Формат А3"'
						
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 = 'SYS_T13_FORM_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_NUMPARAM'),
							'2'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SAVE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCheck2'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Выкл.'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Выкл.'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR5'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Выкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR5') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR5'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SYS_T13_FORM_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_COMBOBOX'),
					'Сортировка №3',6, 
					(Select link from object_var where code = 'SYS_T13_FORM_NASTR_GR'),
					'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR6'),
							(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 = 'SYS_T13_FORM_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'COMBOBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR6'),
							(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 = 'SYS_T13_FORM_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR6'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@nCombo1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLTYPE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR6') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR6'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SYS_T13_FORM_NASTR7' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'ФИО полностью',8, 
					(Select link from object_var where code = 'SYS_T13_FORM_NASTR_GR'),
					'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR7'),
							(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 = 'SYS_T13_FORM_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR7'),
							(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 = 'SYS_T13_FORM_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR7'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_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 = 'SYS_T13_FORM_NASTR7') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR7'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SYS_T13_FORM_NASTR8' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Формат А3',9, 
					(Select link from object_var where code = 'SYS_T13_FORM_NASTR_GR'),
					'SYS_T13_FORM_NASTR8',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR8'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR8'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR8'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR8'),
							(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 = 'SYS_T13_FORM_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							'При установленной опции очет форматируется  в A3. Если опция не установлена, то отчет форматируется в A4'
						
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 = 'SYS_T13_FORM_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR8'),
							(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 = 'SYS_T13_FORM_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_SAVE'),
							'1'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SOURCE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Выкл.,Вкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR8'),
							(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 = 'SYS_T13_FORM_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Выкл.'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Выкл.'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Выкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR8'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR8') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR8'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'1'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SYS_T13_FORM_NASTR9' 
					INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
					Select (Select link from s_objects where code = 'NASTR_QUERY_CHECKBOX'),
					'Пустой табель',10, 
					(Select link from object_var where code = 'SYS_T13_FORM_NASTR_GR'),
					'SYS_T13_FORM_NASTR9',NULL, NULL, 1
					
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'EDITABLE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR9'),
							(Select link from s_property where code = 'EDITABLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR9'),
							(Select link from s_property where code = 'SQUERY_NASTR_NON_VISIBLE'),
							'0'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'FORMAT') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR9'),
							(Select link from s_property where code = 'FORMAT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CAPTION') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_CAPTION'),
							'Пустой табель'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_CONTROL') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_CONTROL'),
							'CHECKBOX'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NOTE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_NOTE'),
							'Формируется пустая форма табеля'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_NUMPARAM') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR9'),
							(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 = 'SYS_T13_FORM_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR9'),
							(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 = 'SYS_T13_FORM_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_SOURCE'),
							'Выкл.,Вкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_SQLPARAM') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR9'),
							(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 = 'SYS_T13_FORM_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLTYPE'),
							'int'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Выкл.'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Выкл.'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Выкл.'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR9'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL') and LINK_UP = (Select link from object_var where code = 'SYS_T13_FORM_NASTR9') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SYS_T13_FORM_NASTR9'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO


GO
-- Отчет "СПВ-1 (Для выходящих на пенсию)"
-- Сгенерировано скриптом scriptObjectVar 'SZV4_PER_SPV2'

/*** Сам отчет ***/

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= 'SZV4_PER_SPV2'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'SZV4_PER_SPV2'
	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'),
	'SZV4_PER_SPV2',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'SZV4_PER_SPV2') 
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'exec SZV4_PRINT_SPV2 @nSel_Spr1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#SZV4_SPV2'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.t.,"PFR_SPV_2.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #SZV4_SPV2
	@nSel_Spr1 int	/* LSel_Spr */
AS
BEGIN

exec SZV4_PRINT_SPV2 @nSel_Spr1

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	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 = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	PROPERTY= (Select LINK from s_property where code = 'SQUERY_NO_SHOW'),
	VALUE= '1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SZV4_PER_SPV2') 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 = 'SZV4_PER_SPV2'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SZV4_PER_SPV2_GRP' 
		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 = 'SZV4_PER_SPV2'),
		'SZV4_PER_SPV2_GRP',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SZV4_PER_SPV2_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'),
					'LSel_Spr',2, 
					(Select link from object_var where code = 'SZV4_PER_SPV2_GRP'),
					'SZV4_PER_SPV2_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 = 'SZV4_PER_SPV2_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZV4_PER_SPV2_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 = 'SZV4_PER_SPV2_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZV4_PER_SPV2_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 = 'SZV4_PER_SPV2_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZV4_PER_SPV2_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 = 'SZV4_PER_SPV2_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZV4_PER_SPV2_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 = 'SZV4_PER_SPV2_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZV4_PER_SPV2_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 = 'SZV4_PER_SPV2_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZV4_PER_SPV2_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 = 'SZV4_PER_SPV2_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZV4_PER_SPV2_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 = 'SZV4_PER_SPV2_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZV4_PER_SPV2_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 = 'SZV4_PER_SPV2_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZV4_PER_SPV2_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 = 'SZV4_PER_SPV2_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZV4_PER_SPV2_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 = 'SZV4_PER_SPV2_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZV4_PER_SPV2_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 = 'SZV4_PER_SPV2_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZV4_PER_SPV2_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'       208'
						
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE') and LINK_UP = (Select link from object_var where code = 'SZV4_PER_SPV2_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZV4_PER_SPV2_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 = 'SZV4_PER_SPV2_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZV4_PER_SPV2_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 = 'SZV4_PER_SPV2_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZV4_PER_SPV2_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO


GO
--добавление видов деятельности в таблицу SZV4_SPR

IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'РАБОТА')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'РАБОТА', 
			'Работа',
			'20140101'
END 	
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'РАБСВПК')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'РАБСВПК', 
			'Работа, подтвержденная свидетельскими показаниями',
			'20140101'
END
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'РАБЗАГР')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'РАБЗАГР', 
			'Работа за границей',
			'20140101'
END 
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'СЛУЖБА')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'СЛУЖБА', 
			'Военная  служба  и  другая, приравненная к ней, служба',
			'20140101'
END 	
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'СЛПРИЗ')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'СЛПРИЗ', 
			'Военная служба по призыву',
			'20140101'
END 

IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'РАБВОВ')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'РАБВОВ', 
			'Работа  во  время   Великой Отечественной войны',
			'20140101'
END 

IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'СЛДАПБЛ')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'СЛДАПБЛ', 
			'Служба в  воинских  частях, штабах и учреждениях, входящих в состав действующей армии, в партизанских отрядах и соединениях в период боевых действий',
			'20140101'
END 

IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'ИЗЛВТР')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'ИЗЛВТР', 
			'Время нахождения на излечении в лечебных учреждениях вследствие военной травмы',
			'20140101'
END 

IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'РАБЛОК')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'РАБЛОК', 
			'Работа в г.Ленинграде в период блокады (с 8 сентября 1941 г. по 27 января 1944 г.)',
			'20140101'
END 

IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'СЛПРОЖ')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'СЛПРОЖ', 
			'Проживание жен (мужей) военнослужащих, проходящих военную службу по контракту',
			'20140101'
END 

IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'СОЦСТРАХ')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'СОЦСТРАХ', 
			'Период временной нетрудоспособности, начавшейся в период работы, и период пребывания на инвалидности I и II групп.',
			'20140101'
END 

IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'СТРАХБЛ')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'СТРАХБЛ', 
			'Период получения пособия по государственному социальному страхованию в период временной нетрудоспособности',
			'20140101'
END 

IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'НЕРАБМАТЬ')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'НЕРАБМАТЬ', 
			'Уход неработающей матери за ребенком',
			'20140101'
END 

IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'УХОД-ДЕТИ')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'УХОД-ДЕТИ', 
			'Уход одного из родителей за ребенком',
			'20140101'
END 

IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'УХОД-ИНВД')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'УХОД-ИНВД', 
			'Уход, осуществляемый за инвалидом 1 группы, ребенком-инвалидом, престарелым',
			'20140101'
END 

IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'ТРУДЛИЦО')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'ТРУДЛИЦО', 
			'Уход трудоспособным лицом за инвалидом I группы, ребенком инвалидом или за лицом, достигшим возраста 80 лет',
			'20140101'
END 

IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'УХОД-ВИЧ')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'УХОД-ВИЧ', 
			'Уход родителей и иных законных представителей за ВИЧ инфицированными несовершеннолетними детьми',
			'20140101'
END 
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'БЕЗР')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'БЕЗР', 
			'Получение пособия по безработице, участия в оплачиваемых общественных работах, переезда по направлению службы занятости в другую местность',
			'20140101'
END 
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'РЕАБИЛИТ')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'РЕАБИЛИТ', 
			'Содержание под стражей лиц,необоснованно привлеченных к уголовной ответственности, необоснованно репрессированных и впоследствии впоследствии отбывание наказания этими лицами в местах лишения свободы и ссылке',
			'20140101'
END 
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'ПРОФЗАБ')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'ПРОФЗАБ', 
			'Пребывание на инвалидности I и II группы, полученной вследствие увечья, связанного с производством,или профессионального заболевания',
			'20140101'
END 
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'ПЕРЕСМОТР')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'ПЕРЕСМОТР', 
			'Пребывание в местах заключения сверх срока, назначенного при пересмотре дела',
			'20140101'
END 
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'ДВСТО')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'ДВСТО', 
			'Подготовка к профессиональной деятельности - обучение',
			'20140101'
END 
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'ПРЗАГР')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'ПРЗАГР', 
			'Проживание за границей жен(мужей) работников советских учреждений и международных организаций',
			'20140101'
END 
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'ПРОВОВ')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'ПРОВОВ', 
			'Проживание в районах,временно оккупированной неприятелем в период Великой Отечественной войны',
			'20140101'
END 
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'ПРБЛОК')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'ПРБЛОК', 
			'Проживание в г.Ленинграде в период его блокады',
			'20140101'
END 
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'ПРКОНЦ')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'ПРКОНЦ', 
			'Нахождение в концлагерях',
			'20140101'
END 
IF NOT EXISTS(SELECT * FROM SZV4_SPR WHERE ltrim(rtrim(spr_code)) = 'VID_WORK' AND ltrim(rtrim(code)) = 'ПРОЖСУПР')
BEGIN 
	INSERT INTO SZV4_SPR (spr_code, code , NAME, date1 )
	SELECT 'VID_WORK',
			'ПРОЖСУПР', 
			'Период проживания супругов военнослужащих, проходящих военную службу по контракту, вместе с супругами в местностях, где они не могли трудиться в связи с отсутствием возможности трудоустройства',
			'20140101'
END 

GO
-- Отчет "СЗВ-K (Сведения  о трудовом стаже застрахованного лица (СЗВ-К))"
-- Сгенерировано скриптом scriptObjectVar 'SZVK_PRINT'

/*** Сам отчет ***/

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= 'SZVK_PRINT'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'SZVK_PRINT'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'СЗВ-К (Сведения о трудовом стаже застрахованного лица)',NULL, 
	(Select link from object_var where code = 'SQL_REPORT_CATALOG_SALARY'),
	'SZVK_PRINT',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'SZVK_PRINT') 
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'exec SZVK_PRINT @nSel_Spr1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#SZVK'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.t.,"SZV_K.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #SZVK
	@nSel_Spr1 int	/* LSel_Spr */
AS
BEGIN

exec SZVK_PRINT @nSel_Spr1

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	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 = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	PROPERTY= (Select LINK from s_property where code = 'SQUERY_NO_SHOW'),
	VALUE= '1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SZVK_PRINT') 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 = 'SZVK_PRINT'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SZVK_PRINT_GRP1' 
		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 = 'SZVK_PRINT'),
		'SZVK_PRINT_GRP1',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SZVK_PRINT_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'),
					'LSel_Spr',2, 
					(Select link from object_var where code = 'SZVK_PRINT_GRP1'),
					'SZVK_PRINT_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 = 'SZVK_PRINT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZVK_PRINT_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 = 'SZVK_PRINT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZVK_PRINT_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 = 'SZVK_PRINT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZVK_PRINT_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 = 'SZVK_PRINT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZVK_PRINT_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 = 'SZVK_PRINT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZVK_PRINT_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 = 'SZVK_PRINT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZVK_PRINT_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 = 'SZVK_PRINT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZVK_PRINT_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 = 'SZVK_PRINT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZVK_PRINT_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 = 'SZVK_PRINT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZVK_PRINT_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 = 'SZVK_PRINT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZVK_PRINT_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 = 'SZVK_PRINT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZVK_PRINT_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 = 'SZVK_PRINT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZVK_PRINT_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 = 'SZVK_PRINT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZVK_PRINT_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 = 'SZVK_PRINT_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SZVK_PRINT_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO


GO
/****** Объект: Дополнительное условие******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'S_BNK_FORMAT_TBL_VIEW_DOP')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'S_BNK_FORMAT_TBL_VIEW_DOP')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'S_BNK_FORMAT_TBL_VIEW_DOP')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'S_BNK_FORMAT_TBL_VIEW_DOP')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'S_BNK_FORMAT_TBL_VIEW_DOP'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'S_BNK_FORMAT_TBL_VIEW_DOP')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='S_BNK_FORMAT_TBL_VIEW_DOP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'S_BNK_FORMAT_TBL_VIEW_DOP', 'Дополнительное условие', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='S_BANK_FORMAT_TABLE_VIEW'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'S_BNK_FORMAT_TBL_VIEW_DOP', NAME = 'Дополнительное условие', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='S_BANK_FORMAT_TABLE_VIEW'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='S_BNK_FORMAT_TBL_VIEW_DOP'
GO
EXEC X_SET_PROP 'S_BNK_FORMAT_TBL_VIEW_DOP', 'TITLE', 'Доп. условие'
GO
EXEC X_SET_PROP 'S_BNK_FORMAT_TBL_VIEW_DOP', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'S_BNK_FORMAT_TBL_VIEW_DOP', 'CONTROLSOURCE', 'm.cAlias+''.DOP'''
GO
EXEC X_SET_PROP 'S_BNK_FORMAT_TBL_VIEW_DOP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'S_BNK_FORMAT_TBL_VIEW_DOP', 'ROWSOURCE', '"Только первая строка,Все кроме первой строки,Только последняя строка,Все кроме последней строки"'
GO
EXEC X_SET_PROP 'S_BNK_FORMAT_TBL_VIEW_DOP', 'SHORT_CODE_OBJ', 'DOP'
GO
EXEC X_SET_PROP 'S_BNK_FORMAT_TBL_VIEW_DOP', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.DOP'''
GO
EXEC X_SET_PROP 'S_BNK_FORMAT_TBL_VIEW_DOP', 'CONTROL_NAME_EDIT', 'ACombo13'
GO
EXEC X_SET_PROP 'S_BNK_FORMAT_TBL_VIEW_DOP', 'COMMENTARY', 'Дополнительное условие для обработки выбранного поля'
GO

GO

/****** Объект: Формат строки файла******/
EXEC X_SET_PROP 'S_BANK_FORMAT_TABLE_VIEW', 'SAVE_OBJECT_METHOD', 'X_SAVE("KIR_BANK_FORMAT_SAVE_STR",m.cAlias,"LINK_PART, LINK_FLD,CODE, ORDERS, IsFixed, MaxLen, Decimals, 	PadType, RightBorder, PaddingChar,CODE_DBF,TYPE_DBF,CONST_VALUE,SQLNULL(FUNC),SQLNULL(DOP)","S_BANK_FORMAT_TABLE_VIEW")'
GO
GO
/****** Объект: Номер больничного******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'VDR_DIS_NUMBER')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'VDR_DIS_NUMBER')
	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 = 'VDR_DIS_NUMBER')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'VDR_DIS_NUMBER')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'VDR_DIS_NUMBER'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'VDR_DIS_NUMBER')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='VDR_DIS_NUMBER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'VDR_DIS_NUMBER', 'Номер больничного', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='VACATION_DIS_REF'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'VDR_DIS_NUMBER', NAME = 'Номер больничного', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='VACATION_DIS_REF'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='VDR_DIS_NUMBER'
GO
EXEC X_SET_PROP 'VDR_DIS_NUMBER', 'TITLE', 'Номер'
GO
EXEC X_SET_PROP 'VDR_DIS_NUMBER', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("ORDER_DISABILITY_SHEET",oForm.ALIAS,"LINK, NUMBER, DATE, COMMENTARY, DATE1, DAYS, DATE2, NAME_TYP_ARHE", "DIS_LINK, NUMBER, DATE, COMMENTARY, DATE1, DAYS, DATE2, ARHE_NAME", "", "", "ref_empl="+str(oform.empl_link), .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'VDR_DIS_NUMBER', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'VDR_DIS_NUMBER', 'CONTROLSOURCE', 'm.cAlias+".NUMBER"'
GO
EXEC X_SET_PROP 'VDR_DIS_NUMBER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'VDR_DIS_NUMBER', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'VDR_DIS_NUMBER', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'VDR_DIS_NUMBER', 'TYPE_FIELD_DICT', 'CHAR(2)'
GO
EXEC X_SET_PROP 'VDR_DIS_NUMBER', 'SHORT_CODE_OBJ', 'NUMBER'
GO
EXEC X_SET_PROP 'VDR_DIS_NUMBER', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NUMBER"'
GO
EXEC X_SET_PROP 'VDR_DIS_NUMBER', 'CONTROL_NAME_EDIT', 'asel_spr1'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[XU_ADMIN_BACKUP_FILELIST]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[XU_ADMIN_BACKUP_FILELIST]

GO

CREATE     PROCEDURE [dbo].XU_ADMIN_BACKUP_FILELIST
	@parFILENAME	varchar(254) = null
AS
	CREATE TABLE #filelist (LogicalName nvarchar(128), PhysicalName nvarchar(260), Type char(1), FileGroupName nvarchar(128),
			[Size] numeric(20,0), [MaxSize] numeric(20,0))
	
	IF @@microsoftversion / 0x01000000  >= 9
		ALTER table #filelist
		ADD 
		FileID bigint,
 		CreateLSN numeric(25,0),
		DropLSN numeric(25,0) NULL,
		UniqueID uniqueidentifier,
		ReadOnlyLSN numeric(25,0) NULL,
		ReadWriteLSN numeric(25,0) NULL,
		BackupSizeInBytes bigint,
		SourceBlockSize int,
		FileGroupID int,
		LogGroupGUID uniqueidentifier NULL,
		DifferentialBaseLSN numeric(25,0) NULL,
		DifferentialBaseGUID uniqueidentifier,
		IsReadOnly bit,
		IsPresent bit

	IF @@microsoftversion / 0x01000000  >= 10
		ALTER table #filelist
		ADD 
		TDEThumbprint varchar(16)

	IF @parFILENAME is null BEGIN
		SELECT TOP 1 checked=convert(bit, 0), * FROM #filelist
		RETURN 0
	END
	DECLARE @FExists int, @FisDir int
	CREATE TABLE #temp (FExists int, FisDir int, Parent int)
	INSERT INTO #temp
	EXECUTE master.dbo.xp_fileexist @parFILENAME
	IF @@ERROR<>0
		RETURN 7
	--есть ли вообще такой файл и не каталог ли это
	SELECT @FExists = FExists, @FisDir = FisDir FROM #temp
	IF @FExists=0 or @FisDir=1
		RETURN 131
	INSERT #filelist
	EXEC XU_ADMIN_RESTORE_FILELISTONLY @parFILENAME
	SELECT checked = convert(bit, 0), LogicalName, PhysicalName = convert(varchar(254), PhysicalName), Type, FileGroupName, [Size], [MaxSize] FROM #filelist
RETURN 0







GO


GRANT EXECUTE ON dbo.[XU_ADMIN_BACKUP_FILELIST] TO PUBLIC

GO


--Расширенные свойства--

