
--BEFORE CODE 12.02.2014
--Таблица out_table_osnov
IF not exists(select * from sysobjects where id = object_id('[dbo].[OUT_TABLE_OSNOV]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[OUT_TABLE_OSNOV] (
	[LINK_UP] int NOT NULL ,
	[OBJECT] int NOT NULL ,
	[OSNOV] int NULL )
GO

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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


GO



GO
-- ОБНОВИТЬ ТРИГГЕРЫ --
EXEC dbo.X_UPDATE_DELETE_TRIGGERS 
GO


GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR', 'Реестр перечисления денежных средств', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='GROUP_KASSA_DOCUMENTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR', NAME = 'Реестр перечисления денежных средств', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='GROUP_KASSA_DOCUMENTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='BB_REESTR_DEN_SR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_DEP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_DEP_NAME', 'Наименование организации', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_DEP_NAME', NAME = 'Наименование организации', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_DEP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_BACC_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_BACC_LINK', 'Ссылка на cчет', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_BACC_LINK', NAME = 'Ссылка на cчет', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_BACC_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_BACC_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_BACC_CODE', 'Код счета', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_BACC_CODE', NAME = 'Код счета', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_BACC_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_BACC_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_BACC_NAME', 'Наименование Счета', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_BACC_NAME', NAME = 'Наименование Счета', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_BACC_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_CARD_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_CARD_LINK', 'ссылка на  карту', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_CARD_LINK', NAME = 'ссылка на  карту', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_CARD_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_CARD_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_CARD_CODE', 'Код карты', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_CARD_CODE', NAME = 'Код карты', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_CARD_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_COMMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_COMMENT', 'Комментарий', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_COMMENT', NAME = 'Комментарий', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_COMMENT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_OSNOV_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_OSNOV_LINK', 'ссылка на  документ', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_OSNOV_LINK', NAME = 'ссылка на  документ', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_OSNOV_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_OSNOV_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_OSNOV_NAME', 'Документ', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_OSNOV_NAME', NAME = 'Документ', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_OSNOV_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_TABLE', 'Таблица выдачи денег', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_TABLE', NAME = 'Таблица выдачи денег', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_TABLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_T_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_T_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_T_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_T_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_T_CARD_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_T_CARD_LINK', 'Сссылка на карту', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_T_CARD_LINK', NAME = 'Сссылка на карту', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_T_CARD_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_T_CARD_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_T_CARD_CODE', 'Код карты', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_T_CARD_CODE', NAME = 'Код карты', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_T_CARD_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_T_EMP_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_T_EMP_LINK', 'Сыылка на сотрудника', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_T_EMP_LINK', NAME = 'Сыылка на сотрудника', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_T_EMP_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_T_EMP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_T_EMP_NAME', 'Ф.И.О. сотрудника', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_T_EMP_NAME', NAME = 'Ф.И.О. сотрудника', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_T_EMP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_T_EKR_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_T_EKR_LINK', 'Ссылка на ЭКР', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_T_EKR_LINK', NAME = 'Ссылка на ЭКР', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_T_EKR_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_T_EKR_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_T_EKR_CODE', 'Код ЭКР', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_T_EKR_CODE', NAME = 'Код ЭКР', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_T_EKR_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_T_KBK_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_T_KBK_LINK', 'Ссылка на КБК', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_T_KBK_LINK', NAME = 'Ссылка на КБК', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_T_KBK_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_T_KBK_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_REESTR_DEN_SR_T_KBK_CODE', 'Код КБК', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_REESTR_DEN_SR_T_KBK_CODE', NAME = 'Код КБК', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_REESTR_DEN_SR_T_KBK_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_F0504501_TAB_SUMMA_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_F0504501_TAB_SUMMA_1', 'Сумма', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_F0504501_TAB_SUMMA_1', NAME = 'Сумма', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_F0504501_TAB_SUMMA_1'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR', 'TITLE', 'Реестр перечисления денежных средств на карты сотрудников по расходам на командировки'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR', 'INIT_OBJECT_METHOD', 'bb_spisok_reestr_den_sr (m.Obj_Code)'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS (m.cAlias,"BB_REESTR_DEN_SR", "BV_DELETE_DOCUMENTS", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_BB_REESTR_DEN_SR'', m.cAlias,"NUMBER, SQLNULL(DATE), SUMMA, COMMENT, SQLNULL(DEP_LINK), SQLNULL(ACC_LINK),SQLNULL(BACC_LINK),SQLNULL(CARD_LINK), SQLNULL(OSNOV_LINK)","BB_REESTR_DEN_SR")'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''BB_REESTR_DEN_SR'')'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_LIST_ZB("BB_REESTR_DEN_SR")'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST("BB_REESTR_DEN_SR")'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR', 'SNAME', 'Реестр перечисления'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR', 'QUERY_REPORT', 'F-0504501.XLT'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR', 'HELP_TOPIC', '19'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_DEP_NAME', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_DEP_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_DEP_NAME', 'CONTROLSOURCE', 'm.cAlias+".DEP_NAME"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_DEP_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_DEP_NAME', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_DEP_NAME', 'SHORT_CODE_OBJ', 'DEP_NAME'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_DEP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DEP_NAME"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_LINK', 'TITLE', 'Счет'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_LINK', 'CONTROLSOURCE', 'm.cAlias+".BACC_LINK"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_LINK', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_LINK', 'SHORT_CODE_OBJ', 'BACC_LINK'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias+".BACC_LINK"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_CODE', 'TITLE', 'Счет'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_CODE', 'EDIT_OBJECT_METHOD', 'X_VALID_HEAD_AP(N_VIBOR_01 ("DICTIONARY_ACCOUNTS", oForm.ALIAS, "LINK,CODE,ANAME", "BACC_LINK, BACC_CODE,  BACC_NAME", "", "", "", .T., 1, oForm, oObj),m.oForm, m.oObj)'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_CODE', 'CONTROLSOURCE', 'm.cAlias+".BACC_CODE"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_CODE', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_CODE', 'SHORT_CODE_OBJ', 'BACC_NAME'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".BACC_CODE"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_CODE', 'CONTROL_NAME', 'Asel_spr3'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_CODE', 'CONTROL_NAME_EDIT', 'Asel_spr3'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_NAME', 'TITLE', 'Счет'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_NAME', 'EDIT_OBJECT_METHOD', 'X_VALID_HEAD_AP(N_VIBOR_01 ("DICTIONARY_ACCOUNTS", oForm.ALIAS, "LINK,CODE,BANK_CODE", "KOR_ACC_LINK, KOR_ACC_CODE,  KOR_BIK", "", "", m.cWhere, .T., 1, oForm, oObj),m.oForm, m.oObj)'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_NAME', 'CONTROLSOURCE', 'm.cAlias+".BACC_NAME"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_NAME', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_NAME', 'SHORT_CODE_OBJ', 'BACC_NAME'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".BACC_NAME"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_NAME', 'CONTROL_NAME', 'aTxtN3'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_BACC_NAME', 'CONTROL_NAME_EDIT', 'aTxtN3'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_CARD_CODE', 'TITLE', 'Код карты'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_CARD_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CARD_CODE"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_CARD_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CARD_CODE"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_COMMENT', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_COMMENT', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_COMMENT', 'CONTROLSOURCE', 'm.cAlias + ".COMMENT"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_COMMENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_COMMENT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COMMENT"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_COMMENT', 'CONTROL_NAME', 'aTxt7'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_COMMENT', 'CONTROL_NAME_EDIT', 'aTxt7'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_OSNOV_NAME', 'TITLE', 'Документ'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_OSNOV_NAME', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_OSNOV_NAME', 'CONTROLSOURCE', 'm.cAlias + ".OSNOV_NAME"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_OSNOV_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".OSNOV_NAME"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_OSNOV_NAME', 'CONTROL_NAME_EDIT', 'aTxtN5'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_TABLE', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_BB_REESTR_DEN_SR_TABLE'', m.cAlias,''SQLNULL(LINK_UP), ORDERS, CARD_LINK, EKR_LINK, KBK_LINK, SUMMA'',"BB_REESTR_DEN_SR_TABLE ")'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_TABLE', 'SELECT_RECORDS_METHOD', 'SQL.EXEC(''SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * FROM dbo.BB_REESTR_DEN_SR_TABLE WHERE LINK_UP = ''+STR(m.nLINK_DOC), m.cAlias)'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_TABLE', 'SERVER_TABLE_NAME', 'OUT_TABLE_ROW'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_MARKER', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_MARKER', 'CONTROLSOURCE', 'm.cAlias+''.CHECKED'''
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_MARKER', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_LINK', 'TITLE', 'Сссылка на карту'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_LINK', 'CONTROLSOURCE', 'm.cAlias + ".CARD_LINK"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_LINK', 'STORAGE', 'PERSON_ECARDS'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_LINK', 'REFERENCE_TO_DICT', 'SD_PERSON_ECARD'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_LINK', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_LINK', 'SHORT_CODE_OBJ', 'CARD_LINK'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CARD_LINK"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_CODE', 'TITLE', 'Код карты'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_CODE', 'EDIT_OBJECT_METHOD', 'N_VIBOR_01 ("SD_PERSON_ECARD", oObj.parent.Parent.RECORDSOURCE, "LINK,LIC_SCHET,NAME_PERS", "CARD_LINK, CARD_CODE, EMP_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CARD_CODE"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_CODE', 'STORAGE', 'PERSON_ECARDS'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_CODE', 'REFERENCE_TO_DICT', 'BB_REESTR_DEN_SR_T_CARD_LINK'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_CODE', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_CODE', 'SHORT_CODE_OBJ', 'CARD_CODE'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CARD_CODE"'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_CARD_CODE', 'REFERENCE_TO_FIELD', 'LIC_SCHET'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_LINK', 'TITLE', 'Сыылка на сотрудника'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_LINK', 'VISIBLE', '0'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_LINK', 'STORAGE', 'PERSON_ECARDS'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_LINK', 'REFERENCE_TO_DICT', 'BB_REESTR_DEN_SR_T_CARD_LINK'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_LINK', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_LINK', 'SHORT_CODE_OBJ', 'PERS_LINK'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_LINK', 'REFERENCE_TO_FIELD', 'PERS_LINK'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_NAME', 'TITLE', 'Ф.И.О. сотрудника'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_NAME', 'CONTROLSOURCE', 'm.cAlias+''.EMP_NAME'''
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_NAME', 'OPERATE_METHOD', 'X_OPERATE_METHOD ("KU_EMPL_PLACING", EVALUATE(m.cAliasOperate+''.EMP_LINK''))'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_NAME', 'STORAGE', 'PERSON_ECARDS'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_NAME', 'REFERENCE_TO_DICT', 'BB_REESTR_DEN_SR_T_CARD_LINK'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_NAME', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_NAME', 'SHORT_CODE_OBJ', 'EMP_NAME'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.EMP_NAME'''
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EMP_NAME', 'REFERENCE_TO_FIELD', '(select  NAME_PEERS = LTRIM(RTRIM(FM)) + '' '' + LEFT(LTRIM(RTRIM(IM)),1) + ''.'' + LEFT(LTRIM(RTRIM(OT)),1) + ''.''  FROM PERSON P where P.LINK = PE.PERS_LINK)'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_LINK', 'TITLE', 'Ссылка на ЭКР'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_LINK', 'CONTROLSOURCE', 'm.cAlias+''.EKR_LINK'''
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_LINK', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_ITEM'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_LINK', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_LINK', 'SHORT_CODE_OBJ', 'EKR_LINK'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_CODE', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_CODE', 'EDIT_OBJECT_METHOD', 'a_vibor_01("DICTIONARY_ITEM", oObj.parent.Parent.RECORDSOURCE, "LINK,CODE", "EKR_LINK, EKR_CODE", "", "","",  .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_CODE', 'CONTROLSOURCE', 'm.cAlias+''.EKR_CODE'''
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_CODE', 'OPERATE_METHOD', 'X_OPERATE_METHOD ("DICTIONARY_KOSGU", EVALUATE(m.cAliasOperate+''.EKR_LINK''))
'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_CODE', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_CODE', 'REFERENCE_TO_DICT', 'BB_REESTR_DEN_SR_T_EKR_LINK'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_CODE', 'TYPE_FIELD_DICT', 'CHAR(3)'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_CODE', 'SHORT_CODE_OBJ', 'EKR_CODE'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_EKR_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_KBK_LINK', 'STORAGE', 'KL_KBK'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_KBK_LINK', 'REFERENCE_TO_DICT', 'bi_diction_kbk'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_KBK_LINK', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_KBK_LINK', 'SHORT_CODE_OBJ', 'KBK_LINK'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_KBK_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_KBK_CODE', 'TITLE', 'КБК'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_KBK_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("bi_diction_kbk", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE", "KBK_LINK, KBK_CODE", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_KBK_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_KBK_CODE', 'CONTROLSOURCE', 'm.cAlias+''.KBK_CODE'''
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_KBK_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_KBK_CODE', 'STORAGE', 'KL_KBK'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_KBK_CODE', 'REFERENCE_TO_DICT', 'BB_REESTR_DEN_SR_T_KBK_LINK'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_KBK_CODE', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_KBK_CODE', 'SHORT_CODE_OBJ', 'KBK_CODE'
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_KBK_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.KBK_CODE'''
GO
EXEC X_SET_PROP 'BB_REESTR_DEN_SR_T_KBK_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_F0504501_TAB_SUMMA_1', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'DOC_F0504501_TAB_SUMMA_1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_F0504501_TAB_SUMMA_1', 'CONTROLSOURCE', 'm.cAlias+''.SUMMA'''
GO
EXEC X_SET_PROP 'DOC_F0504501_TAB_SUMMA_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_F0504501_TAB_SUMMA_1', 'STORAGE', 'SUMMA'
GO
EXEC X_SET_PROP 'DOC_F0504501_TAB_SUMMA_1', 'TYPE_FIELD_DICT', 'NUMERIC(9,2)'
GO
EXEC X_SET_PROP 'DOC_F0504501_TAB_SUMMA_1', 'SHORT_CODE_OBJ', 'SUMMA'
GO
EXEC X_SET_PROP 'DOC_F0504501_TAB_SUMMA_1', 'INPUT_MASK', '9999 999.99'
GO

GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OKATO', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTION_PAY_OKTMO",oForm.ALIAS, " CODE", "OKATO", "", "", "", .T., 0, oForm, oObj)'
GO

GO

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

GO






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

CREATE     PROCEDURE dbo.BK_FORM_SAVE_DOCUMENT_TABLE
	@varKScCode varchar(30)
AS
BEGIN
	DECLARE
		@varKSnLink		int,
		@varKSCurLINK	int,
		@varKSRefLINK	int,
		@varKSCurCODE	varchar(30),
		@varKSShortCode	varchar(30),
		@varKSInALIAS	varchar(10),
		@varKSType	varchar(100),
		@varKSStorage	varchar(30),
		@varKSSel_Str	varchar(8000),
		@varKSCur_Str	varchar(8000),
		@varKSADDTYPE	varchar(100),
		@varKScResCode	varchar(100),
		@varKSchrNAME	varchar(100)
--
	DECLARE 
		@varKSpartParams	varchar(8000),
		@varKSpartDiction	varchar(8000),
		@varKSpartDepartment	varchar(8000),
		@varKSpartSubdiv	varchar(8000),
		@varKSpartAccount	varchar(8000),
		@varKSpartSumma		varchar(8000),
		@varKSpartDate		varchar(8000),
		@varKSpartString	varchar(8000),
		@varKSSaveMethod	varchar(8000),
		@varKSchrCodeType	varchar(100),
		@varKSchrNameType	varchar(100),
		@varKSchrRefField	varchar(100),

		@varKSpartEmpl	varchar(8000),
		@varKSpartKBK	varchar(8000),
		@varKSpartKOSGU	varchar(8000),
		@varKSpartG_PROV varchar(8000),
		@varKSpartINVENTORY	varchar(8000),
		@varKSpartNOMENCLATURE varchar(8000),
		@varKSpartFIN_SOURCE	varchar(8000),
		@varKSpartPERSON_ECARDS varchar(8000)


	SELECT @varKSnLink = LINK FROM S_OBJECTS WHERE CODE = @varKScCode

PRINT '---------------'+@varKScCode
IF @varKSnLink is null OR @varKSnLink=0
BEGIN
	print 'Произошла неустранимая ошибка при формировании запроса.
     Попробуйте обратиться в службу поддержки.
    Или просто задайте правильное имя объекта!'
	Return
END
	Select @varKSType=NAME FROM S_OBJECTS WHERE CODE=@varKScCode
	print '('+@varKSType+')'

	DECLARE SEL_CURSOR CURSOR STATIC LOCAL
	FOR SELECT LINK, CODE, NAME
		FROM S_OBJECTS SO
		WHERE LINK_SELF=@varKSnLink AND (SELECT CODE FROM S_OBJECTS WHERE LINK=SO.LINK_CLASS)='EDIT_FIELD_CLASS'
		ORDER BY ORDERS

SET	@varKSpartParams		= ''
SET	@varKSpartDiction	= ''
SET	@varKSpartDepartment	= ''
SET @varKSpartSubdiv 	= ''
SET	@varKSpartAccount	= ''
SET	@varKSpartSumma		= ''
SET	@varKSpartString		= ''
SET	@varKSpartDate		= ''
SET	@varKSchrCodeType	= ''
SET	@varKSchrNameType	= ''
SET	@varKSSaveMethod		= 'SQLNULL(LINK_UP), ORDERS'

SET	@varKSpartEmpl	= ''
SET	@varKSpartKBK	= ''
SET	@varKSpartKOSGU	= ''
SET	@varKSpartINVENTORY	= ''
SET	@varKSpartNOMENCLATURE	= ''
set @varKSpartG_PROV = ''
SET	@varKSpartFIN_SOURCE	= ''
set @varKSpartPERSON_ECARDS = ''
	SET @varKSSel_Str=
'
--Процедура сформирована с помощью BK_FORM_SAVE_DOCUMENT_TABLE 
--'+LTRIM(convert(char, getdate()))+'
PROCEDURE dbo.X_SAVE_'+@varKScCode
	
	OPEN SEL_CURSOR
	FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE, @varKSchrNAME
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXECUTE X_GET_PROP  @varKSCurCODE, 'FIELD_IN_ALIAS', @varKSInALIAS OUTPUT
		EXECUTE X_GET_PROP  @varKSCurCODE, 'STORAGE', @varKSStorage OUTPUT
		SET @varKSStorage=UPPER(LTRIM(RTRIM(@varKSStorage)))
		IF Convert(int, @varKSInALIAS) = 1
		BEGIN
			EXECUTE X_GET_PROP  @varKSCurCODE, 'SHORT_CODE_OBJ', @varKSShortCode OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'TYPE_FIELD_DICT', @varKSType OUTPUT
			SET @varKSType = UPPER(LTRIM(RTRIM(@varKSType)))
			EXECUTE X_GET_PROP  @varKSCurCODE, 'REFERENCE_TO_FIELD', @varKSchrRefField OUTPUT
			print @varKSStorage + '	' + @varKSShortCode + '	' + @varKSType + '	' + @varKSchrRefField
			IF @varKSType = 'DATETIME'
				SET @varKSADDTYPE=',104'
			ELSE
				SET @varKSADDTYPE=''
			
		
			IF @varKSStorage IN ('SUMMA', 'STRING', 'DATE')
				OR (@varKSStorage IN('DICTION', 'DEPARTMENTS', 'ACCOUNT', 'SUBDIV',
						'EMPL', 'INVENTORY', 'KL_KBK', 'NOMENCLATURE', 'KOSGU', 'G_PROV', 'FIN_SOURCE', 'PERSON_ECARDS')
					AND @varKSchrRefField = 'LINK') 
			BEGIN
				IF @varKSStorage IN('DICTION', 'ACCOUNT', 'DEPARTMENTS', 'SUBDIV',
						'EMPL', 'INVENTORY', 'KL_KBK', 'NOMENCLATURE', 'KOSGU', 'G_PROV', 'FIN_SOURCE', 'PERSON_ECARDS')
					SET @varKSType = 'INT'
				SET @varKSpartParams = @varKSpartParams + ',' + CHAR(13) + CHAR(10) + '	@varKSp' + @varKSShortCode + SPACE(15-LEN(@varKSShortCode)) + @varKSType + ' = null'
				IF @varKSStorage = 'DATE' OR @varKSStorage IN('DICTION', 'DEPARTMENTS') AND @varKSchrRefField = 'LINK' OR @varKSType = 'DATETIME'
					SET @varKSSaveMethod = @varKSSaveMethod + ', SQLNULL(' + @varKSShortCode + ')'
				ELSE
					SET @varKSSaveMethod = @varKSSaveMethod + ', ' + @varKSShortCode
			END

			IF @varKSShortCode is null OR LTRIM(@varKSShortCode)=''
				print '****ОШИБКА!    Нет свойства SHORT_CODE_OBJ. Объект: '+@varKSCurCODE
			ELSE
			BEGIN
				IF @varKSStorage = 'DICTION' AND @varKSchrRefField = 'LINK'
				SET @varKSpartDiction = @varKSpartDiction + '
	EXEC @varKSERROR = dbo.x_UPDATE_OUT_TABLE_DICTION @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'


				IF @varKSStorage = 'DEPARTMENTS' AND @varKSchrRefField = 'LINK'
				SET @varKSpartDepartment = @varKSpartDepartment + '
	EXEC @varKSERROR = dbo.x_UPDATE_OUT_TABLE_DEPARTMENT @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR

'

				IF @varKSStorage = 'SUBDIV' AND @varKSchrRefField = 'LINK'
				SET @varKSpartSubdiv = @varKSpartSubdiv + '
	EXEC @varKSERROR = dbo.x_UPDATE_OUT_TABLE_SUBDIV @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'


				IF @varKSStorage = 'ACCOUNT' AND @varKSchrRefField = 'LINK'
				SET @varKSpartAccount = @varKSpartAccount + '
	EXEC @varKSERROR = dbo.x_UPDATE_OUT_TABLE_ACCOUNT @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'SUMMA'
				SET @varKSpartSumma = @varKSpartSumma + '
	EXEC @varKSERROR = dbo.x_UPDATE_OUT_TABLE_SUMMA @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'STRING'
				SET @varKSpartString = @varKSpartString + '
	EXEC @varKSERROR = dbo.x_UPDATE_OUT_TABLE_STRING @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'DATE'
				SET @varKSpartDate = @varKSpartDate + '
	EXEC @varKSERROR = dbo.x_UPDATE_OUT_TABLE_DATE @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'EMPL' AND @varKSchrRefField = 'LINK'
				SET @varKSpartEmpl = @varKSpartEmpl + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_EMPL @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'KL_KBK' AND @varKSchrRefField = 'LINK'
				SET @varKSpartKBK = @varKSpartKBK + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_KBK @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'INVENTORY' AND @varKSchrRefField = 'LINK'
				SET @varKSpartINVENTORY = @varKSpartINVENTORY + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_INVENTORY @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'NOMENCLATURE' AND @varKSchrRefField = 'LINK'
				SET @varKSpartNOMENCLATURE = @varKSpartNOMENCLATURE + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_NOMENCLATURE @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'KOSGU' AND @varKSchrRefField = 'LINK'
				SET @varKSpartKOSGU = @varKSpartKOSGU + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_KOSGU @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'G_PROV' AND @varKSchrRefField = 'LINK'
				SET @varKSpartG_PROV = @varKSpartG_PROV + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_G_PROV @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'FIN_SOURCE' AND @varKSchrRefField = 'LINK'
				SET @varKSpartFIN_SOURCE = @varKSpartFIN_SOURCE + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_FIN_SOURCE @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'PERSON_ECARDS' AND @varKSchrRefField = 'LINK'
				SET @varKSpartPERSON_ECARDS = @varKSpartPERSON_ECARDS + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_ECARDS @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

			END
			IF @varKSStorage NOT IN ('SUMMA', 'DATE', 'STRING', 'DICTION', 'DICTION_APP', 'DICTION_REF', 'ACCOUNT', 'DEPARTMENTS', 'SUBDIV',
						'EMPL', 'INVENTORY', 'KL_KBK', 'NOMENCLATURE', 'KOSGU', 'G_PROV', 'FIN_SOURCE', 'PERSON_ECARDS')
				Print '***Свойство STORAGE ошибочно или отсутствует! Объект:'+@varKSCurCODE

		END
		FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE, @varKSchrNAME
	END
	
	CLOSE SEL_CURSOR
	DEALLOCATE SEL_CURSOR

	
	SET @varKScResCode = 'X_SAVE_' + @varKScCode
	IF object_id(@varKScResCode) is not null
		SET @varKSSel_Str='ALTER ' + @varKSSel_Str
	ELSE
		SET @varKSSel_Str='CREATE ' + @varKSSel_Str

	SET @varKSSel_Str = @varKSSel_Str + 
'
	@varKSpLINK		int	OUTPUT,
	@varKSpLINK_UP	int,
	@varKSpORDERS	int'
	SET @varKSSel_Str = @varKSSel_Str + @varKSpartParams + 
'
AS
DECLARE @varKSERROR	tinyint,
		@varKSstrVALUE	varchar(7000),
		@varKStrancount	int
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
	--Вставка/обновление G_PROV
	EXECUTE @varKSERROR = dbo.X_UPDATE_OUT_TABLE_ROW @varKSpLINK OUTPUT, @varKSpLINK_UP, ' + LTRIM(STR(@varKSnLink)) + ', @varKSpORDERS
	IF @varKSERROR <> 0
		RETURN @varKSERROR
	--Вставка/обновление OUT_TABLE_DICTION'
 + @varKSpartDiction + 
'
	--Вставка/обновление OUT_TABLE_DEPARTMENT'

 + @varKSpartDepartment + 
'
	--Вставка/обновление OUT_TABLE_SUBDIV'

 + @varKSpartSubdiv + 
'
	--Вставка/обновление OUT_TABLE_ACCOUNT'
 + @varKSpartAccount + 
'
	--Вставка/обновление OUT_TABLE_SUMMA'
 + @varKSpartSumma + 
'
	--Вставка/обновление OUT_TABLE_STRING'
 + @varKSpartString + 
'
	--Вставка/обновление OUT_TABLE_DATE'
 + @varKSpartDate + 
'

	--Вставка/обновление OUT_TABLE_EMPL'
 + @varKSpartEmpl + 
'

	--Вставка/обновление OUT_TABLE_INVENTORY'
 + @varKSpartINVENTORY + 
'

	--Вставка/обновление OUT_TABLE_NOMENCLATURE'
 + @varKSpartNOMENCLATURE + 
'

	--Вставка/обновление OUT_TABLE_KBK'
 + @varKSpartKBK + 
'

	--Вставка/обновление OUT_TABLE_KOSGU'
 + @varKSpartKOSGU + 
'

	--Вставка/обновление OUT_TABLE_G_PROV'
 + @varKSpartG_PROV + 
'

	--Вставка/обновление OUT_TABLE_FIN_SOURCE'
 + @varKSpartFIN_SOURCE + 
'
	--Вставка/обновление OUT_TABLE_PERSON_ECARDS'
 + @varKSpartPERSON_ECARDS + 
'

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0
'
PRINT @varKSSel_Str

	EXECUTE (@varKSSel_Str)
	DECLARE @varKSprocname varchar(254), @varKSmakeby varchar(254)
	SELECT @varKSprocname = 'X_SAVE_'+@varKScCode, @varKSmakeby = 'EXECUTE BK_FORM_SAVE_DOCUMENT_TABLE ''' + @varKScCode+''''
	EXEC U_UPDATE_SCRIPT_PROPERTY @varKSprocname, @varKSmakeby
	
	UPDATE OBJECT_VALUES
	SET VALUE = 'X_SAVE(''X_SAVE_'+@varKScCode+''', m.cAlias,'''+@varKSSaveMethod+''',"'+@varKScCode+'")',
		INHERITED = 0
	WHERE OBJECT = @varKSnLink
			AND PROPERTY = (SELECT LINK FROM S_PROPERTY WHERE CODE = 'SAVE_OBJECT_METHOD')
			AND (VALUE IS NULL OR VALUE = '')

	UPDATE S_DBObjects SET Rights = 0xA WHERE Object=@varKSnLink AND DBObject=@varKScResCode
	IF @@ROWCOUNT = 0	
		INSERT INTO S_DBObjects(Object, DBObject, Rights)
			VALUES (@varKSnLink, @varKScResCode, 0xA)
END



GO


GRANT EXECUTE ON dbo.[BK_FORM_SAVE_DOCUMENT_TABLE] TO PUBLIC

GO


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


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

GO


CREATE   PROCEDURE dbo.BK_FORM_VIEW_DOCUMENT_TABLE
	@varKScCode varchar(30)
AS
	DECLARE 
		@varKSnLink		int,
		@varKSCurLINK	int,
		@varKSCurLINK2	int,
		@varKSFirst		int,
		@varKSCurCODE	varchar(30),
		@varKSRefDict	varchar(30),
		@varKSRefField	varchar(300),
		@varKSShortCode	varchar(30),
		@varKSInALIAS	varchar(10),
		@varKSType		varchar(30),
		@varKSStorage	varchar(30),
		@varKSSel_Str	varchar(7000),
		@varKSCur_Str	varchar(1000),
		@varKSEMP		varchar(1),
		@varKSRefLINK	int,
		@varKSintval		int,
		@varKShostTypeObject	varchar(30)
--	
	SELECT @varKSnLink = LINK FROM S_OBJECTS WHERE CODE = @varKScCode
IF @varKSnLink is null OR @varKSnLink=0
BEGIN
	print 'Произошла неустранимая ошибка при формировании запроса.
     Попробуйте обратиться в службу поддержки.
    Или просто задайте правильное имя объекта!'
	Return
END

	DECLARE SEL_CURSOR  CURSOR STATIC LOCAL
	FOR SELECT DISTINCT LINK, CODE 
	FROM S_OBJECTS WHERE LINK_SELF=@varKSnLink 


print '---------------------------------------'+@varKScCode+'(таблица)'
	SET @varKSSel_Str=
'
--Процедура сформирована с помощью BK_FORM_VIEW_DOCUMENT_TABLE 
--'+LTRIM(convert(char, getdate()))+'
VIEW dbo.' + LTRIM (@varKScCode) + ' AS
SELECT 
	OTR.LINK,
	OTR.LINK_UP,
	OTR.ORDERS,
	OTR.LINK_OPER'

	
	OPEN SEL_CURSOR
	FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXECUTE X_GET_PROP @varKSCurCODE, 'FIELD_IN_ALIAS', @varKSInALIAS OUTPUT
		EXECUTE X_GET_PROP @varKSCurCODE, 'STORAGE', @varKSStorage OUTPUT
		
		IF Convert(int, @varKSInALIAS) = 1 AND @varKSStorage<>''
		BEGIN
			EXECUTE X_GET_PROP  @varKSCurCODE, 'REFERENCE_TO_DICT', @varKSRefDict OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'REFERENCE_TO_FIELD', @varKSRefField OUTPUT
			SET @varKSRefField = RTRIM(LTRIM(@varKSRefField))
			EXECUTE X_GET_PROP  @varKSCurCODE, 'SHORT_CODE_OBJ', @varKSShortCode OUTPUT
			SET @varKSCurCODE = RTRIM(LTRIM(@varKSCurCODE))
			IF LEN(@varKSShortCode)>10
				print 'ПРЕДУПРЕЖДЕНИЕ: Длина поля SHORT_CODE_OBJ больше 10 символов!!!'

			SET @varKShostTypeObject = @varKSCurCODE
			IF @varKSStorage IN('DICTION', 'SUBDIV') AND @varKSRefField <> 'LINK'
			BEGIN
				Declare @varKSOVHValue varchar(254)
				Select @varKSOVHValue = RTRIM(Value)
				From OBJECT_VALUES OVH
				Where OVH.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_DICT')
					AND OVH.OBJECT = (select LINK from s_objects where code = @varKSRefDict)

				SELECT @varKShostTypeObject = SO.CODE
					FROM S_OBJECTS SO, OBJECT_VALUES OVF,
						OBJECT_VALUES OVS, S_OBJECTS SOH
					WHERE SOH.CODE = @varKSOVHValue
						AND SO.LINK_SELF = SOH.LINK

						AND OVF.OBJECT = SO.LINK AND OVF.PROPERTY = (select LINK from S_PROPERTY where CODE = 'SHORT_CODE_OBJ') AND OVF.VALUE = @varKSRefField
						AND OVS.OBJECT = SO.LINK AND OVS.PROPERTY = (select LINK from S_PROPERTY where CODE = 'STORAGE') AND OVS.VALUE = 'DICTION'
				IF @@ROWCOUNT = 0
					print '******* Ошибка! Не найден базовый тип данных!'
			END
			IF @varKSStorage = 'DICTION_APP'
				SET @varKShostTypeObject = @varKSRefField

			EXECUTE X_GET_PROP @varKShostTypeObject, 'TYPE_FIELD_DICT', @varKSType OUTPUT

			SET @varKSType = UPPER(LTRIM(@varKSType))
DECLARE	@varKSCNE	varchar(40), @varKSCSE varchar(40), @varKSTITLE varchar(40), @varKSED varchar(2), @varKSVIS varchar(2), @varKSINFO varchar(200)
			EXECUTE X_GET_PROP  @varKSCurCODE, 'CONTROL_NAME_EDIT', @varKSCNE OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'CONTROL_SOURCE_EDIT', @varKSCSE OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'TITLE', @varKSTITLE OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'EDITABLE', @varKSED OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'VISIBLE', @varKSVIS OUTPUT
			
			SET @varKSINFO='	'+convert(char(10),@varKSCNE)+convert(char(20),@varKSCSE)+convert(char(20),@varKSTITLE)+convert(varchar(2),@varKSED)+' '+convert(varchar(2),@varKSVIS)

			IF LTRIM(@varKSShortCode)='' OR @varKSShortCode is null
				print '****ОШИБКА!    Нет свойства SHORT_CODE_OBJ. Объект: '+@varKSCurCODE
			
 			IF @varKSStorage  ='DICTION_REF'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
				IF @@ROWCOUNT=0
					print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
				SELECT @varKSintval = CHARINDEX(',', @varKSRefField)
				SELECT @varKSRefLINK = LINK FROM S_OBJECTS WHERE CODE = RTRIM(SUBSTRING(@varKSRefField, 1, @varKSintval-1))
				IF @@ROWCOUNT=0
					print '****ОШИБКА!    REFERENCE_TO_FIELD не определено или ошибочно. Объект: '+@varKSCurCODE
				SELECT @varKSRefField = RTRIM(LTRIM(SUBSTRING(@varKSRefField, @varKSintval + 1, LEN(@varKSRefField) - @varKSintval)))
				IF @varKSRefField=''
					print '****ОШИБКА!    REFERENCE_TO_FIELD не определено или ошибочно. Объект: '+@varKSCurCODE
				IF @varKSRefField <> 'LINK'
				BEGIN
					SELECT @varKShostTypeObject = SO.CODE
						FROM S_OBJECTS SO, 
							OBJECT_VALUES OVH, S_OBJECTS SOH
						WHERE OVH.OBJECT = @varKSRefLINK
							AND OVH.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_DICT') 
							AND SOH.CODE = RTRIM(OVH.VALUE)
							AND SO.LINK_SELF = SOH.LINK
							AND exists(select * from OBJECT_VALUES OVF where OVF.OBJECT = SO.LINK AND OVF.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_FIELD') AND OVF.VALUE = @varKSRefField)
							AND exists(select * from OBJECT_VALUES OVS where OVS.OBJECT = SO.LINK AND OVS.PROPERTY = (select LINK from S_PROPERTY where CODE = 'STORAGE') AND OVS.VALUE = 'DICTION')
					IF @@ROWCOUNT = 0
						print '******* Ошибка! Не найден базовый тип данных!'
				END
				print 'WAS '+@varKSType
				EXECUTE X_GET_PROP @varKShostTypeObject, 'TYPE_FIELD_DICT', @varKSType OUTPUT
				print 'IS '+@varKSType
				IF @varKSType='' OR @varKSType is null
					print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				SET @varKSCur_Str=@varKSCur_Str+ 'Convert('+@varKSType+', (SELECT D.'+@varKSRefField
					SET @varKSCur_Str=@varKSCur_Str+
						' FROM DICTION_REF DR, DICTION D, OUT_TABLE_DICTION OTD'+
						' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND DR.REF_PRIMARY=OTD.DICTION AND DR.OBJECT = '+LTRIM(STR(@varKSRefLINK))+' AND D.LINK = DR.REF_FOREIGN)'

					IF @varKSType='DATETIME'
						SET @varKSCur_Str=@varKSCur_Str+',104'

				SET @varKSCur_Str=@varKSCur_Str + ')'

				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END
 			IF @varKSStorage  ='DICTION_APP'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
				IF @@ROWCOUNT=0
					print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
				SELECT @varKSRefLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefField
				IF @@ROWCOUNT=0
					print '****ОШИБКА!    REFERENCE_TO_FIELD не определено или ошибочно. Объект: '+@varKSCurCODE
				IF @varKSType='' OR @varKSType is null
					print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+', DA.VALUE'
					IF @varKSType='DATETIME'
						SET @varKSCur_Str=@varKSCur_Str+',104'
					SET @varKSCur_Str=@varKSCur_Str+')'+
						' FROM DICTION_APP DA, OUT_TABLE_DICTION OTD'+
						' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND DA.LINK_UP = OTD.DICTION AND DA.OBJECT = '+LTRIM(STR(@varKSRefLINK))+')'
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  ='DICTION'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT DICTION FROM OUT_TABLE_DICTION OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM DICTION D, OUT_TABLE_DICTION OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND D.LINK=OTD.DICTION)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END
 			IF @varKSStorage  ='ACCOUNT'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT ACCOUNT FROM dbo.OUT_TABLE_ACCOUNT OTA'+
							' WHERE OTA.LINK_UP=OTR.LINK AND OTA.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str= @varKSCur_Str+'(SELECT Convert (' +@varKSType + ', ' + @varKSRefField +
						CASE
							WHEN @varKSType = 'DATETIME' THEN ', 104'
							ELSE ''
						END +
					') FROM dbo.S_ACCOUNTS SA, dbo.OUT_TABLE_ACCOUNT OTA'+
							' WHERE OTA.LINK_UP=OTR.LINK AND OTA.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND SA.LINK=OTA.ACCOUNT)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END


 			IF @varKSStorage  ='DEPARTMENTS'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT DEPARTMENT FROM OUT_TABLE_DEPARTMENT OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.DEPARTMENTS D, dbo.OUT_TABLE_DEPARTMENT OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND D.LINK=OTD.DEPARTMENT)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  ='SUBDIV'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null

						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT SUBDIV FROM OUT_TABLE_SUBDIV OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.SUBDIV D, dbo.OUT_TABLE_SUBDIV OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND D.LINK=OTD.SUBDIV)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END


			IF @varKSCurCODE <> @varKShostTypeObject
				print '-------->' + @varKShostTypeObject + ' ' + @varKSType

			IF @varKSStorage IN ('SUMMA', 'DATE', 'STRING')
			BEGIN
				IF @varKSType = ''
					SET @varKSCur_Str = '['+@varKSShortCode+'] = (SELECT '+@varKSStorage+' FROM dbo.OUT_TABLE_'+@varKSStorage+' WHERE LINK_UP=OTR.LINK AND OBJECT='+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
					SET @varKSCur_Str = '['+@varKSShortCode+'] = CONVERT('+@varKSType+', (SELECT '+@varKSStorage+' FROM dbo.OUT_TABLE_'+@varKSStorage+' WHERE LINK_UP=OTR.LINK AND OBJECT='+LTRIM(STR(@varKSCurLINK))+'))'
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),' - ') +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),' - ')+@varKSINFO
			END

 			IF @varKSStorage  = 'INVENTORY'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT INVENTORY FROM dbo.OUT_TABLE_INVENTORY OTI'+
							' WHERE OTI.LINK_UP=OTR.LINK AND OTI.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.INVENTORY INV, dbo.OUT_TABLE_INVENTORY OTI'+
							' WHERE OTI.LINK_UP=OTR.LINK AND OTI.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND INV.LINK=OTI.INVENTORY)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  = 'NOMENCLATURE'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT NOMENCLATURE FROM dbo.OUT_TABLE_NOMENCLATURE OTN'+
							' WHERE OTN.LINK_UP=OTR.LINK AND OTN.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.NOMENCLATURE INV, dbo.OUT_TABLE_NOMENCLATURE OTN'+
							' WHERE OTN.LINK_UP=OTR.LINK AND OTN.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND INV.LINK=OTN.NOMENCLATURE)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  = 'EMPL'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT EMPL FROM dbo.OUT_TABLE_EMPL OTE'+
							' WHERE OTE.LINK_UP=OTR.LINK AND OTE.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','
					IF @varKSRefField = 'NAME_EMPL'
					BEGIN
						SET @varKSCur_Str=@varKSCur_Str+' dbo.sd_GetEmplName (OTE.EMPL))'+ 
							' FROM dbo.OUT_TABLE_EMPL OTE'+
							' WHERE OTE.LINK_UP=OTR.LINK AND OTE.OBJECT= '+LTRIM(STR(@varKSCurLINK))+ ')'
					END
					ELSE
					BEGIN						
						SET @varKSCur_Str=@varKSCur_Str + @varKSRefField
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						ELSE	
							SET @varKSCur_Str=@varKSCur_Str+')'+
								' FROM dbo.EMPL EMP, dbo.OUT_TABLE_EMPL OTE'+
								' WHERE OTE.LINK_UP=OTR.LINK AND OTE.OBJECT= '+LTRIM(STR(@varKSCurLINK))+
								' AND EMP.LINK=OTE.EMPL)'
					END

				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  = 'KL_KBK'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT KBK FROM dbo.OUT_TABLE_KBK OTKBK'+
							' WHERE OTKBK.LINK_UP=OTR.LINK AND OTKBK.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.KL_KBK KBK, dbo.OUT_TABLE_KBK OTKBK'+
							' WHERE OTKBK.LINK_UP=OTR.LINK AND OTKBK.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND KBK.LINK=OTKBK.KBK)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  = 'KOSGU'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT KOSGU FROM dbo.OUT_TABLE_KOSGU OTSGU'+
							' WHERE OTSGU.LINK_UP=OTR.LINK AND OTSGU.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.KOSGU KSGU, dbo.OUT_TABLE_KOSGU OTSGU'+
							' WHERE OTSGU.LINK_UP=OTR.LINK AND OTSGU.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND KSGU.LINK = OTSGU.KOSGU)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

			IF @varKSStorage  = 'G_PROV'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT G_PROV FROM dbo.OUT_TABLE_G_PROV OTGP'+
							' WHERE OTGP.LINK_UP=OTR.LINK AND OTGP.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.G_PROV GP, dbo.OUT_TABLE_G_PROV OTGP'+
							' WHERE OTGP.LINK_UP=OTR.LINK AND OTGP.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND GP.LINK = OTGP.G_PROV)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

			IF @varKSStorage  = 'FIN_SOURCE'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT FIN_SOURCE FROM dbo.OUT_TABLE_FIN_SOURCE OTFS'+
							' WHERE OTFS.LINK_UP=OTR.LINK AND OTFS.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.FIN_SOURCE FS, dbo.OUT_TABLE_FIN_SOURCE OTFS' +
							' WHERE OTFS.LINK_UP=OTR.LINK AND OTFS.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND FS.LINK = OTFS.FIN_SOURCE)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

			IF @varKSStorage  = 'PERSON_ECARDS'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT ECARD FROM dbo.OUT_TABLE_ECARD OTEC'+
							' WHERE OTEC.LINK_UP=OTR.LINK AND OTEC.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.PERSON_ECARDS PE, dbo.OUT_TABLE_ECARD OTEC' +
							' WHERE OTEC.LINK_UP=OTR.LINK AND OTEC.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND PE.LINK = OTEC.ECARD)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

			IF @varKSStorage  = 'OSNOV'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT OSNOV FROM dbo.OUT_TABLE_OSNOV OTOSN'+
							' WHERE OTOSN.LINK_UP=OTR.LINK AND OTOSN.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
					IF @varKSType='DATETIME'
						SET @varKSCur_Str=@varKSCur_Str+',104'

					SET @varKSCur_Str = @varKSCur_Str+')'
						+
						CASE
							WHEN @varKSRefField = 'DATE_PROV' THEN
								' FROM dbo.G_PROV G, dbo.OSNOV GP, dbo.OUT_TABLE_OSNOV OTOSN'+
								' WHERE G.LINK = GP.LINK_G_PROV AND OTOSN.LINK_UP = OTR.LINK AND OTOSN.OBJECT= '
							ELSE
								' FROM dbo.BD_OSNOV GP, dbo.OUT_TABLE_OSNOV OTOSN'+
								' WHERE OTOSN.LINK_UP=OTR.LINK AND OTOSN.OBJECT= '
						END
						+ LTRIM(STR(@varKSCurLINK))+' AND GP.LINK = OTOSN.OSNOV)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END
			
			IF @varKSStorage NOT IN ('SUMMA', 'DATE', 'STRING', 'DICTION', 'DICTION_APP', 'DICTION_REF',
					'ACCOUNT', 'DEPARTMENTS', 'SUBDIV',
					'INVENTORY', 'NOMENCLATURE', 'EMPL', 'KL_KBK', 'KOSGU', 'G_PROV',
					'FIN_SOURCE', 'PERSON_ECARDS', 'OSNOV')
			BEGIN
				SET @varKSCur_Str=''
				Print '***Свойство STORAGE ошибочно или отсутствует! Объект:'+@varKSCurCODE

			END 
			
			IF @varKSCur_Str is null
				SET @varKSCur_Str=''
			IF @varKSCur_Str<>''
			BEGIN
				SET  @varKSSel_Str=@varKSSel_Str+',
	'+@varKSCur_Str
			END
		END
		FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE
	END		
	
	CLOSE SEL_CURSOR
	DEALLOCATE SEL_CURSOR
	IF RIGHT(@varKSSel_Str,1)=','
		SET @varKSSel_Str=LEFT(@varKSSel_Str,LEN(@varKSSel_Str)-1)
	SET  @varKSSel_Str=@varKSSel_Str+'
	FROM dbo.OUT_TABLE_ROW OTR
	WHERE OTR.OBJECT = '+LTRIM(STR(@varKSnLink))
	
	IF EXISTS(SELECT * From sysobjects Where name=@varKScCode)
		SET @varKSSel_Str='ALTER ' + @varKSSel_Str
	ELSE
		SET @varKSSel_Str='CREATE ' + @varKSSel_Str
	
	EXECUTE (@varKSSel_Str)

print @varKSSel_Str

	DECLARE @varKSscriptstr varchar(7000)
	SET @varKSscriptstr = 'EXECUTE BK_FORM_VIEW_DOCUMENT_TABLE '''+@varKScCode+''''
	EXEC U_UPDATE_SCRIPT_PROPERTY @varKScCode, @varKSscriptstr

	UPDATE S_DBObjects SET Rights = 0x11 WHERE Object=@varKSnLink AND DBObject=@varKScCode
	IF @@ROWCOUNT = 0
		INSERT INTO S_DBObjects(Object, DBObject, Rights)
			VALUES (@varKSnLink, @varKScCode, 0x11)

GO

GRANT EXECUTE ON dbo.[BK_FORM_VIEW_DOCUMENT_TABLE] TO PUBLIC

GO


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


GO
EXEC X_SET_PROP 'COLUMN_DOC_PAY_OKATO1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTION_PAY_OKTMO",oForm.Pages.Page3.ALIAS, " CODE", "OKATO", "", "", "", .T., 0, oForm, oObj)'
GO

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

GO
-- !!!ФИКТИНВАЯ ДЛЯ ФОРМИРОВАНИЯ ПРОЦЕДУР!!! (ПЕРЕФОРМИРОВЫВАЕТСЯ В АФТЕР_КОДЕ) --
CREATE VIEW [dbo].BV_DOC_AO_OPTIONS
AS
	SELECT 0 as LINK ,
	[P_TYP_LINK]=		(SELECT GO.OPERATION FROM G_PROV1_OBJECT as GO WHERE GO.OBJECT= 21274),
	[P_TYP_NAME]=	CONVERT(VARCHAR(60),	(SELECT NAME_OPER FROM G_PROV1 as G1, G_PROV1_OBJECT as GO  WHERE GO.OPERATION=G1.LINK  AND GO.OBJECT=21274)),
	[R_TYP_LINK]=		(SELECT GO.OPERATION FROM G_PROV1_OBJECT as GO WHERE GO.OBJECT= 21276),
	[R_TYP_NAME]=	CONVERT(VARCHAR(60),	(SELECT NAME_OPER FROM G_PROV1 as G1, G_PROV1_OBJECT as GO  WHERE GO.OPERATION=G1.LINK  AND GO.OBJECT=21276)),
	[TITLE_PROV]=	0

GO



GO
EXEC BK_FORM_VIEW_DOCUMENT_TABLE 'BB_REESTR_DEN_SR_TABLE'
EXEC BK_FORM_SAVE_DOCUMENT_TABLE 'BB_REESTR_DEN_SR_TABLE'
GO

GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_RECEPTION_CARD', 'Заявка на получение денежных средств, перечисляемых на карту', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='GROUP_KASSA_DOCUMENTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_RECEPTION_CARD', NAME = 'Заявка на получение денежных средств, перечисляемых на карту', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='GROUP_KASSA_DOCUMENTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DOC_RECEPTION_CARD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_DEP_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_DEP_LINK', 'Организация', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_DEP_LINK', NAME = 'Организация', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_DEP_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_DEP_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_DEP_CODE', 'Код организации', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_DEP_CODE', NAME = 'Код организации', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_DEP_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_DEP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_DEP_NAME', 'Наименование организации', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_DEP_NAME', NAME = 'Наименование организации', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_DEP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_DATE_NA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_DATE_NA', 'Дата на', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_DATE_NA', NAME = 'Дата на', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_DATE_NA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_DATE_POD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_DATE_POD', 'Дата подписания', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_DATE_POD', NAME = 'Дата подписания', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_DATE_POD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_CARD_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_CARD_LINK', 'Сыллка на  банковскую карту', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_CARD_LINK', NAME = 'Сыллка на  банковскую карту', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_CARD_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_CARD_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_CARD_CODE', 'Номер банковской карты', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_CARD_CODE', NAME = 'Номер банковской карты', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_CARD_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_CARD_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_CARD_NAME', 'Банк', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_CARD_NAME', NAME = 'Банк', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_CARD_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_EMP_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_EMP_LINK', 'Получатель', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_EMP_LINK', NAME = 'Получатель', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_EMP_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_EMP_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_EMP_CODE', 'Табельный номер получателя', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_EMP_CODE', NAME = 'Табельный номер получателя', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_EMP_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_EMP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_EMP_NAME', 'ФИО получателя', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_EMP_NAME', NAME = 'ФИО получателя', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_EMP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_NUM_BO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_NUM_BO', 'Номер бюджетного обязательства', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_NUM_BO', NAME = 'Номер бюджетного обязательства', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_NUM_BO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_VID_SR_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_VID_SR_LINK', 'Ссылка на вид средств', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_VID_SR_LINK', NAME = 'Ссылка на вид средств', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_VID_SR_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_VID_SR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_VID_SR', 'Вид средств', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_VID_SR', NAME = 'Вид средств', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_RECEPTION_CARD'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_VID_SR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_TABLE', 'Таблица для заявки на получение денег', 15, (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 = 'RECEPTION_CARD_TABLE', NAME = 'Таблица для заявки на получение денег', ORDERS = '15', 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 ='RECEPTION_CARD_TABLE'
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_EXPORT_OPT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REC_CARD_EXPORT_OPT', 'Настройки экспорта', 17, (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_EXPORT_OPT', NAME = 'Настройки экспорта', ORDERS = '17', 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_EXPORT_OPT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_TABLE_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_TABLE_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_TABLE_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE_REC_NO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_TABLE_REC_NO', 'Номер', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_TABLE_REC_NO', NAME = 'Номер', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_TABLE_REC_NO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_T_FIN_S_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_T_FIN_S_NAME', 'Наименование источника финансирования', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_T_FIN_S_NAME', NAME = 'Наименование источника финансирования', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_T_FIN_S_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_T_KBK_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_T_KBK_CODE', 'Код КБК', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_T_KBK_CODE', NAME = 'Код КБК', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_T_KBK_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE_EKR_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_TABLE_EKR_CODE', 'Код ЭКР', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_TABLE_EKR_CODE', NAME = 'Код ЭКР', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_TABLE_EKR_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_T_DOP_CL_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_T_DOP_CL_CODE', 'Код доп. классификации', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_T_DOP_CL_CODE', NAME = 'Код доп. классификации', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_T_DOP_CL_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE_ITOG')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_TABLE_ITOG', 'Сумма', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_TABLE_ITOG', NAME = 'Сумма', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_TABLE_ITOG'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE_REASON')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_TABLE_REASON', 'Назначение платежа', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_TABLE_REASON', NAME = 'Назначение платежа', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_TABLE_REASON'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE_TITLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'RECEPTION_CARD_TABLE_TITLE', 'Примечание', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'RECEPTION_CARD_TABLE_TITLE', NAME = 'Примечание', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='RECEPTION_CARD_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='RECEPTION_CARD_TABLE_TITLE'
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_MONTH')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REC_CARD_MONTH', 'Выводить месяц даты', 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_MONTH', 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_MONTH'
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', 'Разделитель суммы', 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_DELIM_SUMMA', 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_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', 'Разделитель КБК', 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_KBK', 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_KBK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_FIO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REC_CARD_FIO', 'Выгружать ФИО полностью', 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_FIO', 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_FIO'
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
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REC_CARD_OPTIONS_NUM', 'Номер файла за дату', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_EXPORT_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_REC_CARD_OPTIONS_NUM', NAME = 'Номер файла за дату', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_EXPORT_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_REC_CARD_OPTIONS_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_OPTIONS_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_REC_CARD_OPTIONS_DATE', 'Дата выгрузки', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_EXPORT_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_REC_CARD_OPTIONS_DATE', NAME = 'Дата выгрузки', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_REC_CARD_EXPORT_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_REC_CARD_OPTIONS_DATE'
GO
EXEC X_SET_PROP 'DOC_RECEPTION_CARD', 'TITLE', 'Заявка на получение денежных средств, перечисляемых на карту'
GO
EXEC X_SET_PROP 'DOC_RECEPTION_CARD', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "DOC_RECEPTION_CARD", "BV_DELETE_DOCUMENTS", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DOC_RECEPTION_CARD', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_DOC_RECEPTION_CARD'', m.cAlias,"NUMBER, SQLNULL(DATE), SQLNULL(DATE_PROV), SUMMA, COMMENT, SQLNULL(DEP_LINK), SQLNULL(ACC_LINK), SQLNULL(EMP_LINK), SQLNULL(CARD_LINK), SQLNULL(DATE_NA),VID_SR,NUM_BO, SQLNULL(DATE_POD)","DOC_RECEPTION_CARD")



'
GO
EXEC X_SET_PROP 'DOC_RECEPTION_CARD', 'PRINT_OBJECT_METHOD', 'bs_print_reception_card(oForm.Alias,oForm.Pages.Page3.Table.bGrid1.RecordSource,oForm.called_form.Alias + ''_opt'')'
GO
EXEC X_SET_PROP 'DOC_RECEPTION_CARD', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''DOC_RECEPTION_CARD '')'
GO
EXEC X_SET_PROP 'DOC_RECEPTION_CARD', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_LIST_ZB("DOC_RECEPTION_CARD")'
GO
EXEC X_SET_PROP 'DOC_RECEPTION_CARD', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST("DOC_RECEPTION_CARD")'
GO
EXEC X_SET_PROP 'DOC_RECEPTION_CARD', 'SNAME', 'Заявка на получение денежных средств, перечисляемых на карту'
GO
EXEC X_SET_PROP 'DOC_RECEPTION_CARD', 'QUERY_REPORT', 'Reception_card.XLT'
GO
EXEC X_SET_PROP 'DOC_RECEPTION_CARD', 'OPTIONS_OBJECT_CODE', 'DOC_REC_CARD_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_RECEPTION_CARD', 'HELP_TOPIC', '21'
GO
EXEC X_SET_PROP 'DOC_RECEPTION_CARD', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'DOC_RECEPTION_CARD', 'CREATE_PROV_SQL', 'BB_CREATE_PROV_RECEPTION_CASH'
GO
EXEC X_SET_PROP 'DOC_RECEPTION_CARD', 'EXCH_MODEL_CODE', 'ZN'
GO
EXEC X_SET_PROP 'DOC_RECEPTION_CARD', 'EXCHANGE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_LINK', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_LINK', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_LINK', 'SHORT_CODE_OBJ', 'DEP_LINK'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_CODE', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME", "DEP_LINK, DEP_CODE, DEP_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_CODE', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_CODE', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_CODE', 'REFERENCE_TO_DICT', 'RECEPTION_CASH_DEP_LINK'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_CODE', 'TYPE_FIELD_DICT', 'VARCHAR(5)'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_CODE', 'SHORT_CODE_OBJ', 'DEP_CODE'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_CODE', 'CONTROLSOURCE_EDIT', 'm.cALIAS+".DEP_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_NAME', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_NAME', 'CONTROLSOURCE', 'm.cAlias+".DEP_NAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_NAME', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_NAME', 'SHORT_CODE_OBJ', 'DEP_NAME'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DEP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DEP_NAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_NA', 'TITLE', 'Дата на'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_NA', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_NA', 'CONTROLSOURCE', 'm.cAlias+''.DATE_NA'''
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_NA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_NA', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_NA', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_NA', 'SHORT_CODE_OBJ', 'DATE_NA'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_NA', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.DATE_NA'''
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_NA', 'CONTROL_NAME', 'Aseldate3'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_NA', 'CONTROL_NAME_EDIT', 'Aseldate3'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_POD', 'TITLE', 'Дата подписания'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_POD', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_POD', 'CONTROLSOURCE', 'm.cAlias+''.DATE_POD'''
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_POD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_POD', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_POD', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_POD', 'SHORT_CODE_OBJ', 'DATE_POD'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_POD', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.DATE_POD'''
GO
EXEC X_SET_PROP 'RECEPTION_CARD_DATE_POD', 'CONTROL_NAME_EDIT', 'Aseldate21'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_CARD_LINK', 'SHORT_CODE_OBJ', 'CARD_LINK'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_CARD_LINK', 'CONTROLSOURCE_EDIT', 'm.cALIAS+".CARD_LINK"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_CARD_CODE', 'TITLE', '№ карты'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_CARD_CODE', 'EDIT_OBJECT_METHOD', 'N_VIBOR_01 ("SD_PERSON_ECARD", oForm.ALIAS, "LINK,LIC_SCHET,BANK_NAME", "CARD_LINK, CARD_CODE, CARD_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_CARD_CODE', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_CARD_CODE', 'CONTROLSOURCE', 'm.cALIAS+".CARD_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_CARD_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_CARD_CODE', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_CARD_CODE', 'SHORT_CODE_OBJ', 'CARD_CODE'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_CARD_CODE', 'CONTROLSOURCE_EDIT', 'm.cALIAS+".CARD_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_CARD_CODE', 'CONTROL_NAME_EDIT', 'aSel_spr6'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_CARD_NAME', 'TITLE', 'Банк карты'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_CARD_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_CARD_NAME', 'SHORT_CODE_OBJ', 'CARD_NAME'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_CARD_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CARD_NAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_CARD_NAME', 'CONTROL_NAME_EDIT', 'aTxtBank'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_EMP_LINK', 'TITLE', 'Вноситель'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_EMP_LINK', 'SHORT_CODE_OBJ', 'EMP_LINK'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_EMP_CODE', 'TITLE', 'Таб. №'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_EMP_CODE', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("KU_EMPL_PLACING", oForm.ALIAS,"LINK, TAB, NAME_EMPL", "EMP_LINK, EMP_CODE, EMP_NAME", "", "", "", .T., 1, oForm, oObj,"",.T.,"EMPL_GROUPS")'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_EMP_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_EMP_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_EMP_CODE', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_EMP_CODE', 'SHORT_CODE_OBJ', 'EMP_CODE'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_EMP_CODE', 'CONTROLSOURCE_EDIT', 'm.cALIAS+".EMP_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_EMP_CODE', 'CONTROL_NAME_EDIT', 'ASel_Spr5'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_EMP_NAME', 'TITLE', 'ФИО получателя'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_EMP_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_EMP_NAME', 'SHORT_CODE_OBJ', 'EMP_NAME'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_EMP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".EMP_NAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_EMP_NAME', 'CONTROL_NAME', 'ATxtN5'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_EMP_NAME', 'CONTROL_NAME_EDIT', 'ATxtN5'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_NUM_BO', 'TITLE', 'Номер БО'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_NUM_BO', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_NUM_BO', 'CONTROLSOURCE', 'm.cAlias+".NUM_BO"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_NUM_BO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_NUM_BO', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_NUM_BO', 'SHORT_CODE_OBJ', 'NUM_BO'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_NUM_BO', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NUM_BO"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_NUM_BO', 'CONTROL_NAME_EDIT', 'AtxtN20'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_VID_SR_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_VID_SR', 'TITLE', 'Вид средств'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_VID_SR', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_VID_SR', 'CONTROLSOURCE', 'm.cAlias + ".VID_SR_SNAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_VID_SR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_VID_SR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".VID_SR_SNAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_VID_SR', 'CONTROL_NAME_EDIT', 'aCmb1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE', 'SAVE_OBJECT_METHOD', 'x_save(''X_UPDATE_RECEPTION_CASH_TABLE'', m.cAlias, ''LINK_UP, FS_CODE,0, KBK, EKR, D_CL_LINK, SUMMA, RECORD_NO, REASON, TITLE, ""'', ''RECEPTION_CARD_TABLE'')
'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE', 'SELECT_RECORDS_METHOD', 'ftable_reception_cash_select(m.cAlias, m.nLink, ''RECEPTION_CARD_TABLE_VIEW'')'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE', 'SERVER_TABLE_NAME', 'RECEPTION_CASH_TABLE'
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_EXPORT_OPT', 'TITLE', 'Настройки "Заявка на получение наличных денег"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_EXPORT_OPT', 'OPTIONS_OBJECT_CODE', 'DOC_REC_CARD_OPTIONS'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_CHECKED', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_CHECKED', 'CONTROLSOURCE', 'm.cAlias+''.CHECKED'''
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_CHECKED', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_REC_NO', 'TITLE', 'Номер'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_REC_NO', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_REC_NO', 'CONTROLSOURCE', 'm.cAlias + ".RECORD_NO"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_REC_NO', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_REC_NO', 'TYPE_FIELD_DICT', 'NUMERIC(9)'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_REC_NO', 'SHORT_CODE_OBJ', 'RECORD_NO'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_REC_NO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".RECORD_NO"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_REC_NO', 'INPUT_MASK', '999999999'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_FIN_S_NAME', 'TITLE', 'Источник финансирования'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_FIN_S_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_FIN_S_NAME', 'CONTROLSOURCE', 'm.cAlias + ".FS_NAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_FIN_S_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_FIN_S_NAME', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_FIN_S_NAME', 'SHORT_CODE_OBJ', 'FS_NAME'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_FIN_S_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FS_NAME"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_KBK_CODE', 'TITLE', 'КБК'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_KBK_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("bi_diction_kbk", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "KBK, KBK_CODE, KBK_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_KBK_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_KBK_CODE', 'CONTROLSOURCE', 'm.cAlias + ".KBK_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_KBK_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_KBK_CODE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_KBK_CODE', 'REFERENCE_TO_DICT', 'AVANCE_ACCEPT_TABLE_KBK_LINK'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_KBK_CODE', 'TYPE_FIELD_DICT', 'char(5)'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_KBK_CODE', 'SHORT_CODE_OBJ', 'KBK_CODE'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_KBK_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".KBK_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_KBK_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_EKR_CODE', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_EKR_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_ITEM", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "EKR, EKR_CODE, EKR_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_EKR_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_EKR_CODE', 'CONTROLSOURCE', 'm.cAlias + ".EKR_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_EKR_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_EKR_CODE', 'SHORT_CODE_OBJ', 'EKR_CODE'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_EKR_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".EKR_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_DOP_CL_CODE', 'TITLE', 'Доп. классиф-ия'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_DOP_CL_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("BD_DOP_CLASSIF", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "D_CL_LINK, D_CL_CODE, D_CL_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_DOP_CL_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_DOP_CL_CODE', 'CONTROLSOURCE', 'm.cAlias + ".D_CL_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_DOP_CL_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_DOP_CL_CODE', 'SHORT_CODE_OBJ', 'D_CL_CODE'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_T_DOP_CL_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".D_CL_CODE"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_ITOG', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_ITOG', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_ITOG', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_ITOG', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_ITOG', 'SHORT_CODE_OBJ', 'SUMMA'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_ITOG', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_REASON', 'TITLE', 'Назначение'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_REASON', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_REASON', 'CONTROLSOURCE', 'm.cAlias+".REASON"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_REASON', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_REASON', 'SHORT_CODE_OBJ', 'REASON'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_REASON', 'CONTROLSOURCE_EDIT', 'm.cAlias+".REASON"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_TITLE', 'TITLE', 'Примечание'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_TITLE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_TITLE', 'CONTROLSOURCE', 'm.cAlias+".TITLE"'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_TITLE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_TITLE', 'SHORT_CODE_OBJ', 'TITLE'
GO
EXEC X_SET_PROP 'RECEPTION_CARD_TABLE_TITLE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TITLE"'
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_MONTH', 'TITLE', 'Код целевого назначения'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_MONTH', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_MONTH', 'CONTROLSOURCE', 'm.cAlias + ".month"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_MONTH', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_MONTH', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_MONTH', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_MONTH', 'SHORT_CODE_OBJ', 'month'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_MONTH', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".month"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_MONTH', 'CONTROL_NAME_EDIT', 'RADIO1'
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_FIO', 'TITLE', 'Выгружать ФИО полностью'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_FIO', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_FIO', 'CONTROLSOURCE', 'm.cALIAS+ ".FIO"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_FIO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_FIO', 'CONTROL_TYPE', ''
GO
EXEC X_SET_PROP 'DOC_REC_CARD_FIO', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_FIO', 'TYPE_FIELD_DICT', 'BIT'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_FIO', 'SHORT_CODE_OBJ', 'FIO'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_FIO', 'CONTROLSOURCE_EDIT', 'm.cALIAS+ ".FIO"'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_FIO', 'CONTROL_NAME_EDIT', 'FIO_CHECKBOX'
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
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_NUM', 'TITLE', 'Номер файла за дату'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_NUM', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_NUM', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_NUM', 'SHORT_CODE_OBJ', 'NUM'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_NUM', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_DATE', 'TITLE', 'Дата выгрузки'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_DATE', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_DATE', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_DATE', 'SHORT_CODE_OBJ', 'DATE'
GO
EXEC X_SET_PROP 'DOC_REC_CARD_OPTIONS_DATE', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXECUTE X_FORM_VIEW_OPTIONS 'DOC_REC_CARD_OPTIONS'
GO
/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Заявка на получение денежных средств, перечисляемых на карту"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

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

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

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

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'DOC_RECEPTION_CARD', 'Заявка на получение денежных средств, перечисляемых на карту', @ORD, NULL, 1, @LINK_SELF, 'DOCUMENT', @OBJECT, @LINK_VAR, 3
GO

GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Таблица g_prov_card
IF not exists(select * from sysobjects where id = object_id('[dbo].[G_PROV_CARD]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[G_PROV_CARD] (
	[DOC_LINK] int NOT NULL ,
	[OBJECT] int NOT NULL ,
	[CARD] int NOT NULL )
GO

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

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

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

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

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

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


GO
--Добавление колонки [OKTMO] в таблицу SUBDIV
IF COLUMNPROPERTY(object_id('[dbo].[SUBDIV]'), 'O_OKTMO', 'AllowsNull') is null
	ALTER TABLE [dbo].[SUBDIV] ADD [O_OKTMO] VARCHAR(11) not NULL  DEFAULT ('')
	
GO



GO

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

GO
-- @iRKO_PKO = 1 - пко, @iRKO_PKO = 2 - рко
CREATE FUNCTION dbo.BK_GET_LINK_KO_PAYER
	(@iPKO_RKO	TINYINT = 0,
	@LINK_KO	INT	= NULL,
	@EMP	INT = NULL)
RETURNS TABLE
AS
RETURN
	WITH TTT (LINK_OBJ, KO, CODE)
	AS
	(
	SELECT TOP 1
		SO.LINK,
		2,
		'OPT'
	FROM dbo.S_OBJECTS SO
	WHERE SO.CODE = 'COLUMN_DOC_RKO_OPTION'
	
	UNION ALL
	
	SELECT TOP 1
		SO.LINK,
		2,
		'FACE_LINK'
	FROM dbo.S_OBJECTS SO
	WHERE SO.CODE = 'COLUMN_DOC_RKO_FACE_LINK'
	)

	SELECT
		G.LINK,
		T1.CODE,
		GPE.EMPL
	FROM dbo.G_PROV G
	INNER JOIN TTT T1 ON (T1.CODE = 'OPT'
		AND (@iPKO_RKO = 0 OR T1.KO = @iPKO_RKO))
	INNER JOIN TTT T2 ON (T2.CODE = 'FACE_LINK'
		AND (@iPKO_RKO = 0 OR T2.KO = @iPKO_RKO))
	LEFT JOIN dbo.G_PROV_VALUE GPV ON (GPV.[OBJECT] = T1.LINK_OBJ
		AND GPV.DOC_LINK = G.LINK)	
	LEFT JOIN dbo.G_PROV_EMPL GPE ON (GPE.[OBJECT] = T2.LINK_OBJ
		AND GPE.DOC_LINK = G.LINK)
	WHERE (@LINK_KO IS NULL
			OR G.LINK = @LINK_KO)
		AND GPV.VALUE = '1'
		AND (@EMP IS NULL OR GPE.EMPL = @EMP)
GO

GRANT SELECT ON dbo.[BK_GET_LINK_KO_PAYER] TO PUBLIC

GO


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


GO

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

GO

CREATE FUNCTION dbo.SA_ROUND (@nSumma NUMERIC(18,6), @nPart NUMERIC(18,2), @nTypUpDown tinyint)
/*
@nSumma,; 	&& Округляемая сумма

@nTypRound,;	&& Кратно каким частям округлять
 
@nTypUpDown	&& 0 - округлять математически, т.е. 0.5  = 1
			&& 1 - округлять вниз, т.е. 0.5 = 0
			&& 2 - округлять вверх, т.е. 0.2 = 1

Пример:
--Округлить 67.57р. до 5 копеек
SELECT dbo.SA_ROUND(67.57, 0.05, 0 )
-- Результат 67.55р.

--Округлить 67.57р. до 10 руб
SELECT dbo.SA_ROUND(67.57, 10, 0 )
-- Результат 70.00р.

*/
RETURNS NUMERIC(18,6)

AS

BEGIN

SET @nSumma = COALESCE(@nSumma,0)
SET @nPart = COALESCE(@nPart,0)
SET @nTypUpDown = COALESCE(@nTypUpDown,0)

IF @nPart = 0 
	SET @nSumma = @nSumma
ELSE
	IF @nTypUpDown < 2
		SET @nSumma = ROUND((@nSumma * 100) / (@nPart * 100),0,@nTypUpDown) * (@nPart * 100) / 100 
	ELSE
		SET @nSumma = CEILING((@nSumma * 100) / (@nPart * 100)) * (@nPart * 100) / 100 

RETURN @nSumma

END


GO


GRANT EXECUTE ON dbo.[SA_ROUND] TO PUBLIC

GO

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

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

RETURN

	-- Форматы для налога на прибыль --
	SELECT FORM_CODE = 'ND_NP',
		FNAME = 'Формат 5.02 (с 01.01.2009 г.)', PROC_NAME = 'BK_EXPORT_F1151006', 
		PRG_SKRIPT = CONVERT(VARCHAR(100),''),
		DIR = 'IMNS',
		TEST_PROC = ''
	WHERE @YEAR < 2011

	UNION ALL

	SELECT FORM_CODE = 'ND_NP',
		FNAME = 'Формат 5.03 (с 01.01.2011 г.)', PROC_NAME = 'BK_EXPORT_F1151006_503', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = ''
	WHERE @YEAR BETWEEN 2011 AND 2013

	UNION ALL

	SELECT FORM_CODE = 'ND_NP',
		FNAME = 'Формат 5.05 (с 01.12.2013 г.)', PROC_NAME = 'BK_EXPORT_F1151006_505', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = ''
	WHERE @YEAR >= 2013

	UNION ALL
	-- Форматы для транспортного налога --
	SELECT
		FORM_CODE = 'ND_TN',
		FNAME = 'Формат 4.01 (с 01.01.2007 г.)',
		PROC_NAME = 'BK_EXPORT_F1152004', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = 'BK_TEST_EXP_F1152027'
	WHERE @YEAR < 2012	

	UNION ALL

	SELECT
		FORM_CODE = 'ND_TN',
		FNAME = 'Формат 5.01 (с 01.01.2012 г.)',
		PROC_NAME = 'BK_EXPORT_F1152004_501', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = ''
	WHERE @YEAR = 2012

	UNION ALL

	SELECT
		FORM_CODE = 'ND_TN',
		FNAME = 'Формат 5.02 (с 01.01.2013 г.)',
		PROC_NAME = 'BK_EXPORT_F1152004_502', 
		PRG_SKRIPT = '',
		DIR = 'IMNS',
		TEST_PROC = ''
	WHERE @YEAR >= 2013

	UNION ALL

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

	UNION ALL

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

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

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

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

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

	UNION ALL
	-- Формат выгрузки П-4 --
	SELECT FORM_CODE = '0606010',
		FNAME = 'Формат выгрузки формы П-4 для Росстата', PROC_NAME = 'SK_EXPORT_F0606010', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''
	WHERE 
		@YEAR <= 2012	
	UNION ALL
	-- Формат выгрузки П-4 c 01.01.2013 --
	SELECT FORM_CODE = '0606010',
		FNAME = 'Формат выгрузки формы П-4 для Росстата', PROC_NAME = 'SK_EXPORT_F0606010_13', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''
	WHERE 
		@YEAR >= 2013		


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

	UNION ALL
	SELECT FORM_CODE = 'КРАТ_11',
		FNAME = 'Формат выгрузки формы 11-краткая для Росстата', PROC_NAME = 'BK_EXPORT_F0602002_2012', 
		PRG_SKRIPT = '',
		DIR = 'RST',
		TEST_PROC = ''
	WHERE 
		@YEAR >= 2012		
	
	-- Выгрузка АХД (МЗ 2013) --		
	UNION ALL
	SELECT
		FORM_CODE = 'AHD_EXPORT_REST',
		FNAME = 'Формат 1.00 (с 01.09.2013 г.)',
		PROC_NAME = 'BK_EXPORT_AHD_REST',
		PRG_SKRIPT = '',
		DIR = 'AHD',
		TEST_PROC = ''

	UNION ALL
	SELECT
		FORM_CODE = 'AHD_EXPORT_PROV',
		FNAME = 'Формат 1.00 (с 01.09.2013 г.)',
		PROC_NAME = 'BK_EXPORT_AHD_PROV',
		PRG_SKRIPT = '',
		DIR = 'AHD',
		TEST_PROC = ''
	

	-- Выгрузка данных об ОС --		
	UNION ALL
	SELECT
		FORM_CODE = 'EOD_EXPORT_INV1',
		FNAME = 'Формат 1.00 (с 01.01.2013 г.)',
		PROC_NAME = 'BK_EXPORT_INV1',
		PRG_SKRIPT = '',
		DIR = 'AHD',
		TEST_PROC = ''

GO


GRANT SELECT ON dbo.[BK_VIEW_EXPORT_FORMAT_NALOG_FN] TO PUBLIC

GO


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

GO



CREATE    FUNCTION [dbo].SUBDIVISION (@dDATE datetime = null)
RETURNS TABLE
AS
RETURN
SELECT sh.link, [subdiv_link] = s.link, s.code, s.name, 
	[link_self] = isnull(s.link_self, 0),
	s.orders, sh.dep_link, s.lim, 
	S.OBOSOB,
	S.O_OKATO,
	S.O_KPP,
	[date_begin] = (SELECT min(date_begin) FROM subdiv WHERE link_up=sh.link),
	[date_end] = (SELECT min(date_end) FROM subdiv WHERE link_up=sh.link),
	[imageindex] = case when isnull(@dDATE, ui.workdate) between s.date_begin and s.date_end then 'subdiv' else 'sack' end,
	[deleted] = case when isnull(@dDATE, ui.workdate) between s.date_begin and s.date_end then 0 else 1 end,
	[childrens] = case when exists(select * from subdiv where link_self=sh.link and isnull(@dDATE, ui.workdate) between date_begin and date_end)
			then convert(bit, 0) else convert (bit, 1) end,
	[PARENT_NAME] = isnull((SELECT top 1 NAME FROM subdiv WHERE LINK_UP = s.link_self AND isnull(@dDATE, ui.workdate) BETWEEN DATE_BEGIN AND DATE_END),''),
    S.O_OKTMO
FROM dbo.user_info ui
	INNER JOIN dbo.subdiv_head sh ON sh.dep_link = (SELECT zb_link FROM ks_options_zb)
	INNER JOIN dbo.subdiv s ON s.link_up=sh.link 
		and ((s.date_begin=isnull((SELECT max(date_begin) FROM subdiv WHERE link_up=s.link_up and isnull(@dDATE, ui.workdate)>=date_begin),
				(SELECT min(date_begin) FROM subdiv WHERE link_up=s.link_up and isnull(@dDATE, ui.workdate)<=date_begin)) and ui.code_task in ('KADRY', 'SALARY'))
			or (isnull(@dDATE, ui.workdate) between s.date_begin and s.date_end and  ui.code_task not in ('KADRY', 'SALARY')))




GO


GRANT SELECT ON dbo.[SUBDIVISION] TO PUBLIC

GO




GO

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

GO

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

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

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

CREATE VIEW dbo.[RT_VIEW_DEPDICT_125]
AS
select 
	dp.link as link,
	dp.code,
	sh_name =ISNULL(DH.[NAME], dp.NAME), 
	name = ISNULL(DH.[FULL_NAME], dp.[FULL_NAME]), 
	isnull(kbs.code,'') as ppp,
	isnull( cast(replace(dp.okato,' ','') as varchar(11/*хотя, по идее ОКАТО 11 символов*/)),'') as okato, 
	isnull( cast(replace(dp.oktmo,' ','') as varchar(11/*хотя, по идее ОКАТО 11 символов*/)),'') as oktmo, 
	coalesce((
		select coalesce(kbt.code_el,'') 
		from kl_budg_type as kbt 
		where kbt.link = (
			select kab.link_budg 
			from kl_admin_bs as kab 
			where kab.link = dp.ved_link)
		),'') as code_el,
	right('0000000000' + cast(isnull(dp.link,'0') as varchar(10)),8) as UCS,
   isnull(DH.[DATE_BEGIN], '19000101') [DATE_BEGIN],
   isnull(DH.[DATE_END], '30000101') [DATE_END] 
	from dbo.Departments as dp 
	left join dbo.kl_admin_bs as kbs on dp.ved_link = kbs.link
   left JOIN dbo.DICTIONARY_DEPARTMENT_HIST DH ON DH.[LINK_UP] = DP.[LINK]
	where dp.link in (select convert(int, code) from dbo.report_kbk where code_form = 'RT_VIEW_DEPDICT_125' and isnumeric(code) = 1)
union 
select 
	dp.link as link,
	dp.code,
	sh_name = dp.NAME, 
	name = dp.[FULL_NAME], 
	isnull(kbs.code,'') as ppp,
	isnull( cast(replace(dp.okato,' ','') as varchar(11/*хотя, по идее ОКАТО 11 символов*/)),'') as okato, 
	isnull( cast(replace(dp.oktmo,' ','') as varchar(11/*хотя, по идее ОКАТО 11 символов*/)),'') as oktmo, 
	coalesce((
		select coalesce(kbt.code_el,'') 
		from kl_budg_type as kbt 
		where kbt.link = (
			select kab.link_budg 
			from kl_admin_bs as kab 
			where kab.link = dp.ved_link)
		),'') as code_el,
	right('0000000000' + cast(isnull(dp.link,'0') as varchar(10)),8) as UCS,
  '19000101',
   isnull(DH.[DATE_BegiN]-1,'30000101') 
	from dbo.Departments as dp 
	left join dbo.kl_admin_bs as kbs on dp.ved_link = kbs.link
   left JOIN (select min(date_begin) date_begin, link_up from dbo.DICTIONARY_DEPARTMENT_HIST GROUP BY link_up) DH ON DH.[LINK_UP] = DP.[LINK]
	where dp.link in (select convert(int, code) from dbo.report_kbk where code_form = 'RT_VIEW_DEPDICT_125' and isnumeric(code) = 1)
union
select -1 as link,'Итого' as code, 'Итого' as sh_name,'Итого' as name, '' as ppp,'99999999999' as okato, '99999999999' as oktmo, '' , '', '19000101', '30000101'


GO


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

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

CREATE             VIEW FINANS_CONTRACT_TABLE
AS
Select F.LINK, F.LINK_UP, F.VKR, F.EKR, F.OKDP, F.QUANTITY, F.COST,
--	[RECORD_NO] = convert(NUMERIC(9), F.RECORD_NO),
--	[REC_CH_NO] = convert(NUMERIC(9), F.RECORD_CH_NO),
	[RECORD_NO] = F.RECORD_NO,
	[REC_CH_NO] = F.RECORD_CH_NO,
	[ERROR]	   = convert(bit, 0),
	F.P1, F.P2, F.P3, F.P4, F.P5, F.P6, F.P7, F.P8, F.P9, F.P10, F.P11, F.P12, 
	[VKR_CODE] = VKR.CODE,
	[VKR_NAME] = VKR.NAME,
	[EKR_CODE] = EKR.CODE,
	[EKR_NAME] = EKR.NAME,

	[D_CL_LINK] = F.DOP_CLASSIF,
	[D_CL_CODE] = DC.CODE,
	[D_CL_NAME] = DC.NAME,
	
	[UM_LINK] = UM.LINK,
	[UM_CODE] = UM.CODE,
	[UM_NAME] = UM.NAME,

	[ITOG]     = F.P1 + F.P2 + F.P3 + F.P4 + F.P5 + F.P6 + F.P7 + F.P8 + F.P9 + F.P10 + F.P11 + F.P12,
	[OKDP_CODE] = O.CODE,
	[OKDP_NAME] = O.NAME,
	[SUMMA]    = F.SUMMA
	
from FINANSE_CONTRACT F  
left join dbo.KL_KBK VKR 	  on VKR.LINK = F.VKR
left join dbo.KOSGU EKR 	  on EKR.LINK = F.EKR
left join dbo.BD_DOP_CLASSIF DC   on DC.LINK = F.DOP_CLASSIF
left join dbo.OKDP O	  	  on O.LINK = F.OKDP
left join dbo.DICTIONARY_DIGIT UM on UM.LINK = O.UM






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




CREATE	function dbo.BB_CREDIT_PLAT_DAY (@iLink int)
returns int 
as
begin
declare @dDateW datetime,
		@iDay int
select @dDateW = WORKDATE from dbo.USER_DATES

set @iDay = (select top 1 day(CS.DATE - @dDateW) from CREDIT_SUM CS
			inner join dbo.CREDIT_PARAM_DICTION CPD on CPD.LINK = CS.PARAM_LINK
			where CS.LINK_UP = @iLink 
					and left(CPD.CODE,2) = 'N_' 
					and CS.DATE between @dDateW and @dDateW + 30
			order by CS.DATE)
return @iDay	
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

GO


CREATE FUNCTION dbo.EMPL_STAFF(@dDATE DATETIME = NULL)
	RETURNS @RET TABLE (
		EMPL_LINK INT,
		STAFF_LINK INT,
		STAFF_HEAD INT,
		SUBDIV_LINK INT,
		SUBDIV_HEAD INT,
		POST_LINK INT,
		NUM_STAKE NUMERIC(3,2),
		MOVE_LINK INT,
		[STATUS] INT,
		NOTWORK TINYINT,
		OKLAD NUMERIC(10,2),
		LINK_KBK INT,
		KAT_LINK int,
		DATE_BEGIN DATETIME
	)
AS BEGIN
	IF @dDATE IS NULL BEGIN
		SET @dDATE = (SELECT WORKDATE FROM dbo.USER_INFO)
	END
	DECLARE @MOVES TABLE(EMPL_LINK INT, STAFF_LINK INT, NUM_STAKE NUMERIC(3,2), MOVE_LINK INT, STATUS INT, OKLAD NUMERIC(10,2), DATE_BEGIN DATETIME)
	DECLARE @MOVES2 TABLE(EMPL_LINK INT, STAFF_LINK INT, STAFF_HEAD INT, NUM_STAKE NUMERIC(3,2), MOVE_LINK INT, [STATUS] INT, OKLAD NUMERIC(10,2), DATE_BEGIN DATETIME)

	declare @oklad table (empl_link int, summa numeric(18,2) )
	insert into @oklad (empl_link, summa)
	SELECT 
		MP.EMPL_LINK,
		SUM(MP.SUMMA)
	FROM 
		dbo.PAYS P
		INNER JOIN dbo.SA_MONEY_PERIOD_FN(DEFAULT,DEFAULT) MP ON MP.PAY_LINK = P.LINK
	WHERE
		P.WAY_CALC = 1
		AND
		@dDate between MP.DATE_BEGIN and ISNULL(MP.DATE_END,'20990101')		
	GROUP BY
		MP.EMPL_LINK	

	INSERT INTO @MOVES 
	SELECT IM1.EMPL_LINK, IM1.STAFF_LINK, IM1.NUM_STAKE, IM1.LINK, IM1.STATUS, isnull(o.summa,0), IM1.DATE_BEGIN
	FROM ITEM_MOVE IM1 
		inner join 
		(
		SELECT IM.EMPL_LINK, MAX(IM.LINK) AS LINK
		FROM
			(SELECT 
				EMPL_LINK, MAX(DATE_BEGIN) AS DATE_BEGIN
			FROM dbo.item_move
			WHERE date_begin<=@dDATE and active=1 --and new_face<>2
			GROUP BY EMPL_LINK
			) M
		INNER JOIN ITEM_MOVE IM ON IM.EMPL_LINK=M.EMPL_LINK AND IM.DATE_BEGIN=M.DATE_BEGIN
			and im.active=1 --and im.new_face<>2
		GROUP BY IM.EMPL_LINK
		) M1 on IM1.LINK = M1.LINK
		left join @oklad o on o.empl_link = im1.EMPL_LINK

	DECLARE @STAFF TABLE (LINK_UP INT, DATE_BEGIN DATETIME, LINK INT)
	INSERT INTO @STAFF
	SELECT S.LINK_UP, S.DATE_BEGIN, ST.LINK
	FROM(	
		SELECT LINK_UP, MAX(DATE_BEGIN) AS DATE_BEGIN
		FROM STAFF
		WHERE DATE_BEGIN<=@dDATE
		GROUP BY LINK_UP
	) S, STAFF ST
	WHERE S.LINK_UP = ST.LINK_UP AND S.DATE_BEGIN = ST.DATE_BEGIN

	INSERT INTO @MOVES2
	SELECT M.EMPL_LINK, ST.LINK, ST.LINK_UP, M.NUM_STAKE, M.MOVE_LINK, M.STATUS, M.OKLAD, M.DATE_BEGIN
	FROM @STAFF ST, @MOVES M
	WHERE ST.LINK_UP=M.STAFF_LINK

	INSERT INTO @RET
	SELECT M.EMPL_LINK, M.STAFF_LINK, M.STAFF_HEAD, S.SUBDIV_LINK, S.SUBDIV_LINK, S.post_link, M.NUM_STAKE, M.MOVE_LINK, M.STATUS, 
		(SELECT notwork FROM empl WHERE link=m.empl_link), M.OKLAD, S.LINK_KBK, S.KAT_LINK, M.DATE_BEGIN
	FROM @MOVES2 M
	INNER JOIN dbo.staff s ON M.STAFF_LINK = S.LINK
	
	UPDATE @RET SET SUBDIV_LINK = 
	(
		SELECT TOP 1 S.LINK
		FROM SUBDIV S
		WHERE S.LINK_UP = R.SUBDIV_HEAD
			AND S.DATE_BEGIN <= @dDATE
		ORDER BY S.DATE_BEGIN DESC
	) 
	FROM @RET R
	
	RETURN
END
GO


GRANT SELECT ON dbo.[EMPL_STAFF] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE   VIEW dbo.DICTIONARY_ACCOUNTS
AS
SELECT 
	DA.LINK,
	[CODE]		 =	DA.CODE,
	[TYPE]		 = 	DA.TYPE,
	[TYPE_NAME]  = 	DAT.NAME,
	[REF_LINK_B] = 	DA.BANK_LINK,
	[BANK_CODE]  = 	B.BIK,
	[BANK_NAME]  = 	B.NAME,
	[BANK_FNAME] = 	B.FNAME,
	[BANK_CITY] = B.CITY,
	[BANK_KS]    = 	B.KS,
	[BANK_FILIAL] = B.FILIAL_NAME,
	[REF_LINK_K] =	TR.LINK,
	[KAZN_CODE]  = 	TR.CODE,
	[KAZN_INN]  = 	TR.INN,
	[KAZN_NAME]  = 	TR.NAME,
	[KAZN_F_NAME]= 	TR.FULL_NAME,
	[K_ACC_LINK] = 	DA.TA_LINK,
	[K_ACC_CODE] = 	TA.CODE,
	[REF_LINK_D] = 	DA.LINK_UP,
	 DEP_NAME    = D.NAME,
	[OWNER_NAME] =  cast(CASE WHEN DA.TYPE = 1 THEN B.NAME else TR.NAME end as varchar(40)),
	[ANAME]	     =  CASE WHEN DA.TYPE = 1 THEN RTRIM(B.NAME) + ' БИК:' + B.BIK
			ELSE RTRIM(TR.NAME) + ' р/c №' + LTRIM(RTRIM(TA.CODE)) END
FROM dbo.DEPARTMENT_ACCOUNTS DA
	LEFT OUTER JOIN dbo.DEPARTMENTS D ON D.LINK = DA.LINK_UP
	LEFT OUTER JOIN dbo.BANKS B ON DA.BANK_LINK = B.LINK 
	LEFT OUTER JOIN dbo.TREASURY_ACCOUNTS TA ON  DA.TA_LINK = TA.LINK
	LEFT OUTER JOIN dbo.TREASURY TR ON TR.LINK = TA.LINK_UP
	LEFT OUTER JOIN dbo.DICTIONARY_ACCOUNTS_TYPE DAT ON DAT.NUMBER = DA.TYPE

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

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

RETURN
END
GO


GRANT SELECT ON dbo.[BB_DEP_ACC_DOP] TO PUBLIC
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

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

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

		  DEP_LINK  = G.DEP,
		  DEP_CODE  = D.CODE,
		  DEP_NAME  = D.NAME,
		  DEP_FNAME  = D.FULL_NAME,
		  DEP_B_CODE	= D.BUDG,
		  DEP_UBP	= D.CODE_UBP,
		  DEP_TYPE	= D.BUH_TYPE,
		  DEP_INN  = D.INN,
		  DEP_KPP  = D.KPP,
		  ACC_LINK  = G.ACC,
		  ACC_CODE  = DA.CODE,   
		  BANK_NAME = DA.ANAME,  
		
		  TOFK_NAME	= DA.KAZN_F_NAME,
		  TOFK_CODE	= DA.KAZN_CODE,
		 
		  CARD_LINK	= PEC.LINK,
		  CARD_CODE	= PEC.LIC_SCHET, 
		  CARD_NAME	= B.NAME,
  		  VID = isnull(CONVERT(int, (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='BB_DET_RETURN_VID'))),1)


FROM dbo.G_PROV G WITH (NOLOCK)
inner join dbo.DEPARTMENTS D WITH (NOLOCK) on G.DEP = D.LINK
inner join dbo.DICTIONARY_ACCOUNTS DA WITH (NOLOCK) on G.ACC = DA.LINK
left join dbo.G_PROV_ECARD GPEC WITH (NOLOCK) on GPEC.DOC_LINK = G.LINK AND GPEC.OBJECT = (select link from s_objects where code='BB_DET_RETURN_CARD_LINK')
left join dbo.PERSON_ECARDS PEC on GPEC.ECARD = PEC.LINK
left join dbo.BANKS B on B.LINK = PEC.BANK_LINK
 WHERE G.OBJECT=(SELECT link from S_OBJECTS WHERE CODE='BB_DET_RETURN')




GO
grant all on dbo.DOC_RECEPTION_CARD to public

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

GO

CREATE VIEW [dbo].DICTIONARY_SUBDIVISION
AS
SELECT * FROM dbo.SUBDIVISION(default)

GO


GRANT SELECT ON dbo.[DICTIONARY_SUBDIVISION] TO PUBLIC

GO



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

CREATE     VIEW dbo.DICTIONARY_DEP_ACCOUNTS_PBS
AS
SELECT DA.*, D.CODE as DEP_CODE
FROM dbo.DEPARTMENTS D
inner join dbo.DICTIONARY_ACCOUNTS DA on D.LINK = DA.REF_LINK_D and (DA.TYPE = 2 or DA.TYPE = 4)
where D.TYPE = 2 or D.TYPE = 4 or ZB = 1

GO



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

CREATE VIEW dbo.FB_ZAYAVKA_S
AS
 	SELECT 	
		G.LINK,
		G.NUMBER,
		[FSUMMA] 	= ISNULL((select sum(FT.P1+FT.P2+FT.P3+FT.P4+FT.P5+FT.P6+FT.P7+FT.P8+FT.P9+FT.P10+FT.P11+FT.P12) 
				  	  from dbo.FINANSE FT 
				  	  inner join dbo.FINANSE_HEAD FH on FT.LINK_UP = FH.LINK
				  	  where FH.LINK_REESTR = G.LINK), 0),
		[SUMMA] 	= G.SUMMA,
		G.COMMENT,
		G.DATE,
		F.FYEAR,
		F.PER_NUM,
		PERIOD 		= (select PERIOD from dbo.PERIODS where ORD = F.PER_NUM), 
		F.PARAM,
		CHANGE_LONG 	= (case when F.PARAM & 0x1 = 1 then 'Документ изменение' else 'Основной документ' end),
		[CHANGE] 	= ISNULL((F.PARAM & 0x1) ,1),
		[KAP_LIM] 	= ISNULL((F.PARAM & 0x2),0) / 2,
		[TYPE] 		= ISNULL((F.PARAM & 0x4),0) / 4,
		[FDEP_LINK]	= FDA.LINK,
		[FDEP_CODE]	= FD.CODE,
		[FDEP_NAME]	= FD.NAME,
		[FACC_LINK]	= F.ACCOUNT,
		[FACC_CODE]	= FDA.CODE,
		[FACC_NAME]	= FDA.ANAME,
		[LINK_REESTR]	= F.LINK_REESTR,
		[NUM_REESTR]	= (SELECT NUMBER FROM G_PROV WHERE LINK = F.LINK_REESTR), 
		G.DATE_PROV,
		[FLAG_JC] 	= CASE WHEN DATE_PROV IS NULL THEN 0 ELSE 1 END,
		[DEP_LINK]	= G.DEP,
		[DEP_CODE]	= D.CODE,
		[DEP_NAME]	= D.NAME,
		[ACC_LINK]	= G.ACC,
		[ACC_CODE]	= DA.CODE,
		[ACC_NAME]	= DA.ANAME
	FROM dbo.G_PROV as G WITH (NOLOCK)
	INNER JOIN dbo.WORKMODE W on 1=1
	inner join dbo.S_OBJECTS SO on G.OBJECT = SO.LINK and SO.CODE = 'FB_ZAYAVKA_S'
	LEFT JOIN dbo.FINANSE_HEAD F ON F.LINK = G.LINK
	left join dbo.DICTIONARY_ACCOUNTS DA on DA.LINK = G.ACC
	left join dbo.DEPARTMENTS D on G.DEP = D.LINK
	left join dbo.DICTIONARY_ACCOUNTS FDA on FDA.LINK = F.ACCOUNT
	left join dbo.DEPARTMENTS FD on FDA.REF_LINK_D = FD.LINK
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant all on dbo.BB_CREDIT 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 @STATUS_EMPL TABLE(EMPL_LINK INT, [STATUS] INT)
-------------------------------------------------------------------------------------------------------
INSERT INTO @STATUS_EMPL (EMPL_LINK, [STATUS])
SELECT EMPL_LINK, [STATUS]
FROM dbo.ITEM_MOVE
WHERE @dDATE between date_begin and date_end and active=1

-- Сведения о ФИО сотрудников
DECLARE @FIO_EMPL TABLE(PERS_LINK int, [FIO] VARCHAR(100),	[NAME_EMPL] VARCHAR(100))
---------------------------------------------------------------------------------------------------------
INSERT INTO @FIO_EMPL(PERS_LINK, [FIO], [NAME_EMPL])
SELECT  [PERS_LINK] = LINK,
		[FIO] = LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(FM)) + ' ' + LTRIM(RTRIM(IM)) + ' ' + LTRIM(RTRIM(OT)),'Не заполнено'))),100),
	    [NAME_EMPL] = LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(FM)) + ' ' + LEFT(LTRIM(RTRIM(IM)),1) + '.' + LEFT(LTRIM(RTRIM(OT)),1) + '.', 'Не заполнено'))),30)
FROM dbo.PERSON

-- Сведения о телефонах, эл.адресах сотрудников ---------------------------------------------------------
DECLARE @PHONE_MAIL_EMPL TABLE(EMPL_LINK INT, [EMAIL] VARCHAR(254), [PHONE_WORK] VARCHAR(254), [PHONE_MOB] VARCHAR(254))
---------------------------------------------------------------------------------------------------------
INSERT INTO @PHONE_MAIL_EMPL(EMPL_LINK, [EMAIL], [PHONE_WORK],[PHONE_MOB])
SELECT 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]			=	FE.FIO,
		[NAME_EMPL]		= 	FE.NAME_EMPL,
		[SUBDIV_HEAD]	=	DS.link_up,
		[SUBDIV_LINK]	=	DS.LINK,
		[SUBDIV_CODE]	=	DS.CODE,
		[SUBDIV_NAME]	=	DS.NAME,
		[POST_LINK]		=	DP.LINK,
		[POST_CODE]		=	DP.CODE,
		[POST_NAME]		=	DP.NAME,
		[STAFF_HEAD]	=	PE.STAFF_HEAD,
		[STAFF_LINK]	= 	PE.STAFF_LINK,
		[NUM_STAKE]		=	PE.NUM_STAKE,
		[STATUS]		=	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   @FIO_EMPL       FE	 ON P.LINK = FE.PERS_LINK
		LEFT JOIN	dbo.GRAPH			G	 ON e.graph_link=g.link
		LEFT JOIN	@POST_EMPL		PE	 ON E.LINK = PE.EMPL_LINK
		LEFT JOIN	dbo.SAL_SFIN		KBK	 ON KBK.LINK = PE.LINK_KBK		
		LEFT JOIN	dbo.SUBDIV			DS	 ON PE.subdiv_link = DS.LINK
		LEFT JOIN	dbo.POST			DP	 ON PE.post_link = DP.LINK
		LEFT JOIN	dbo.ITEM_MOVE		IM	 ON IM.ACTIVE = 1 AND IM.NEW_FACE = 1 AND IM.EMPL_LINK = E.LINK
		LEFT JOIN	dbo.DEPARTMENTS		DEP	 ON E.DEP_LINK = DEP.LINK
		LEFT JOIN	@STATUS_EMPL	SE	 ON E.LINK = SE.EMPL_LINK	
		LEFT JOIN	@ITEM_DIS_FACE	IDF	 ON E.LINK = IDF.EMPL_LINK
		LEFT JOIN	@CHIN_EMPL		CE	 ON E.LINK = CE.EMPL_LINK
		LEFT JOIN   @PHONE_MAIL_EMPL PME ON E.LINK = PME.EMPL_LINK
		LEFT JOIN	dbo.STAFF ST ON ST.LINK = PE.STAFF_LINK
		LEFT JOIN	dbo.GR_GOS GR ON GR.LINK = ST.GR_GOS_LINK
		LEFT JOIN   DBO.KAT_GOS KAT ON KAT.LINK = ST.KAT_GOS_LINK
		--LEFT JOIN	dbo.KATEG KAT ON KAT.LINK = ST.KAT_LINK

	) T

RETURN
END


GO


GRANT SELECT ON dbo.[KU_EMPL_PLACING_FN] TO PUBLIC

GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

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

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

		  DEP_LINK  = G.DEP,
		  DEP_CODE  = D.CODE,
		  DEP_NAME  = D.NAME,
		  DEP_FNAME  = D.FULL_NAME,
		  ACC_LINK  = G.ACC,
		  ACC_CODE  = DA.CODE,   
		  
		  CARD_LINK	= C.LINK,
		  CARD_NAME	= C.NAME,
		  C.FRMT_LINK,
		  OSNOV_LINK	= O.LINK,
		  OSNOV_NAME	= O.INFO, 
		  BACC_LINK	= BDA.LINK,
		  BACC_CODE	= BDA.CODE,
		  BACC_NAME	= BDA.ANAME,
		  BBANK_LINK = BDA.REF_LINK_B
		  
FROM dbo.G_PROV G WITH (NOLOCK)
inner join dbo.DEPARTMENTS D WITH (NOLOCK) on G.DEP = D.LINK
left join dbo.DICTIONARY_ACCOUNTS DA WITH (NOLOCK) on G.ACC = DA.LINK
left join dbo.G_PROV_CARD GC WITH (NOLOCK) on GC.DOC_LINK = G.LINK AND GC.OBJECT = (select link from s_objects where code='BB_REESTR_DEN_SR_CARD_LINK')
left join dbo.CARDS C on GC.[CARD] = C.LINK
left join dbo.G_PROV_OSNOV GOSN WITH (NOLOCK) on GOSN.DOC_LINK = G.LINK AND GOSN.OBJECT = (select link from s_objects where code='BB_REESTR_DEN_SR_OSNOV_LINK')
left join dbo.BD_OSNOV O on GOSN.OSNOV = O.LINK
left join dbo.G_PROV_DEP_ACCT GDA WITH (NOLOCK) on GDA.DOC_LINK = G.LINK AND GDA.OBJECT = (select link from s_objects where code='BB_REESTR_DEN_SR_BACC_LINK')
LEFT JOIN dbo.DICTIONARY_ACCOUNTS BDA ON BDA.LINK = GDA.ACCOUNT
 WHERE G.OBJECT=(SELECT link from S_OBJECTS WHERE CODE='BB_REESTR_DEN_SR')

GO
grant all on dbo.BB_REESTR_DEN_SR to public

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

CREATE VIEW dbo.BB_ZAYAVKA_KR
AS

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

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

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

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




GO

grant all on BB_ZAYAVKA_KR to public
GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE VIEW dbo.BB_P_CREDIT
AS
 	SELECT 	
		GP.LINK,
		GP.NUMBER,
		GP.SUMMA,
		GP.COMMENT,
		GP.[DATE],
		GP.DATE_PROV,
		[FLAG_JC]   = CASE WHEN GP.DATE_PROV IS NULL THEN 0 ELSE 1 END,
		PLAT_DAY   = dbo.BB_CREDIT_PLAT_DAY(GP.LINK),
		[TYPE]	    = CT.LINK,
		[TYPE_CODE] = CT.CODE,
		[TYPE_NAME] = CT.NAME,
		[ACC_LINK]  = GP.ACC,
		[ACC_CODE]  = DA.CODE,
		[ACC_NAME]  = DA.ANAME,
		[DEP_LINK]  = GP.DEP,
		[DEP_CODE]  = D.CODE,
		[DEP_NAME]  = D.NAME,
		[KACC_LINK] = CH.ACC,
		[KACC_CODE] = DAP.CODE,
		[KACC_NAME] = DAP.ANAME,
		[KDEP_LINK] = CH.DEP,
		[KDEP_CODE] = DP.CODE,
		[KDEP_NAME] = DP.NAME,
		[DOC_LINK]  = CH.DOC_LINK,
		[DOC_NUM]   = O.[NUMBER],
		[DOC_DATE]  = O.[DATE],
		[DOC_NAME]  = RTRIM(O.TYPE),
		[ADOC_NAME] = O.INFO,
		CH.FIN_SOURCE,
		CH.NUM_ACC,
		DATE_BEG = dbo.BB_CREDIT_DATE_BEG(GP.LINK),
		DATE_END = dbo.BB_CREDIT_DATE_END(GP.LINK, default, default)
	FROM dbo.G_PROV as GP WITH (NOLOCK)
	INNER JOIN dbo.CREDIT_HEAD CH 	   	ON CH.LINK  = GP.LINK
	LEFT  JOIN dbo.DEPARTMENTS D   	   	ON D.LINK   = GP.DEP
	LEFT  JOIN dbo.DICTIONARY_ACCOUNTS DA	ON DA.LINK  = GP.ACC
	LEFT  JOIN dbo.DEPARTMENTS DP   	ON DP.LINK  = CH.DEP
	LEFT  JOIN dbo.DICTIONARY_ACCOUNTS DAP	ON DAP.LINK = CH.ACC
	LEFT  JOIN dbo.BD_OSNOV O 			ON O.LINK   = CH.DOC_LINK
	LEFT  JOIN dbo.CREDIT_TYPES CT 		ON CT.LINK  = CH.TYPE
	WHERE GP.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'BB_P_CREDIT')


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant all on dbo.BB_P_CREDIT to public
GO

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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


CREATE   VIEW BB_DET_RETURN_TABLE_VIEW
AS

Select 
	F.LINK, 
	F.LINK_UP, 
	RECORD_NO 	= convert(NUMERIC(9), F.RECORD_NO),
	KBK 		= F.KBK, 
	KBK_CODE 	= KBK.CODE,
	KBK_NAME 	= KBK.NAME,
	KBK_TYPE	= KBK.TYPE, 
	EKR 		= F.EKR, 
	EKR_CODE 	= EKR.CODE,
	EKR_NAME 	= EKR.NAME,
	D_CL_LINK 	= F.DOP_CLASSIF,
	D_CL_CODE 	= DC.CODE,
	D_CL_NAME 	= DC.NAME,
	FS_CODE 	= DFS.CODE,
	FS_NAME 	= DFS.NAME,
	VID_SR 		= VS.LINK,
	VID_SR_NAME 	= VS.NAME,
	VID_SR_SNAME 	= VS.SNAME,
	BK_CODE	    = replace(rtrim(KBK.CODE) + isnull('.' + EKR.CODE,'') + isnull('.' + DC.CODE,''),'.',isnull(DO.DELIVKBK,'')),	
	SUMMA		= F.SUMMA,
	F.TITLE
	
From RECEPTION_CASH_TABLE F  
LEFT JOIN dbo.bi_diction_kbk KBK ON KBK.LINK = F.KBK
LEFT JOIN dbo.KOSGU EKR ON EKR.LINK = F.EKR
LEFT JOIN dbo.BD_DOP_CLASSIF DC ON DC.LINK = F.DOP_CLASSIF
LEFT JOIN dbo.BB_FIN_SOURCE DFS ON DFS.CODE = F.SOURCE
LEFT JOIN dbo.BB_ZAYAVKA_KR_SOURCE VS ON VS.LINK = F.VID_SR
left join dbo.DOCUMENTS_REC_CASH_OPTIONS DO on 1=1


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

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

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

		  DEP_LINK  = G.DEP,
		  DEP_CODE  = D.CODE,
		  DEP_NAME  = D.NAME,
		  DEP_FNAME  = D.FULL_NAME,
		  DEP_B_CODE	= D.BUDG,
		  DEP_UBP	= D.CODE_UBP,
		  DEP_TYPE	= D.BUH_TYPE,
		  ACC_LINK  = G.ACC,
		  ACC_CODE  = DA.CODE,   
		  BANK_NAME = DA.ANAME,  
			
		  GRBS_NAME	= VED.NAME,
		  GRBS_CODE	= VED.CODE,
		  BUDG_NAME	= BUDG.NAME,
		  FO_NAME	= FO.FULL_NAME,
		  FO_CODE	= FO.CODE,
		  FO_OKPO	= FO.OKPO,
		  TOFK_NAME	= DA.KAZN_F_NAME,
		  TOFK_CODE	= DA.KAZN_CODE,
		  UCHR_NAME	= UCHR.NAME,

		  EMP_LINK	= GPEM.EMPL,
		  EMP_CODE	= EM.TAB, 
		  EMP_FM	= EM.FM, 
		  EMP_IM	= EM.IM, 
		  EMP_OT	= EM.OT, 
		  EMP_FIO	= EM.FIO, 
		  EMP_NAME	= EM.NAME_EMPL, 
		  EMP_POST	= EM.POST_NAME, 
		  ED_NUM	= PERS.DOC_NUM, 
		  ED_WHOM	= PERS.DOC_WHOM, 
		  ED_DOC	= isnull(FD.NAME,''),
		  ED_DATE	= PERS.DOC_DATE,
		  
		  DOC_LINK= (SELECT doc_ref_foreign FROM dbo.G_PROV as GR WITH (NOLOCK) INNER JOIN dbo.G_PROV_REF GPR WITH (NOLOCK) ON GPR.DOC_REF_PRIMARY = G.LINK AND GPR.OBJECT=(select link from s_objects where code='RECEPTION_CASH_PKO')  AND GR.LINK = GPR.DOC_REF_FOREIGN),
		  
		  DATE_POD = CONVERT(DATETIME, (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_DATE_POD')), 104),
		  
		  CHEK_SER = CONVERT(VARCHAR (2), (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_CHEK_SERIA'))),
		  CHEK_NO = CONVERT(VARCHAR (15), (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_CHEK_NO'))),
		  CHEK_DATE = CONVERT(DATETIME, (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_CHEK_DATE')), 104),
		  CHEK_SROK = CONVERT(DATETIME, (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_CHEK_SROK')), 104),

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

		  DATE_NA = CONVERT(DATETIME, (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='RECEPTION_CASH_DATE_NA')), 104)
FROM dbo.G_PROV G WITH (NOLOCK)
inner join dbo.DEPARTMENTS D WITH (NOLOCK) on G.DEP = D.LINK
inner join dbo.DICTIONARY_ACCOUNTS DA WITH (NOLOCK) on G.ACC = DA.LINK
left join dbo.G_PROV_EMPL GPEM WITH (NOLOCK) on GPEM.DOC_LINK = G.LINK AND GPEM.OBJECT = (select link from s_objects where code='RECEPTION_CASH_EMP_LINK')
left join KU_EMPL_PLACING EM WITH (NOLOCK) on GPEM.EMPL = EM.LINK
left join PERSON PERS ON (PERS.LINK = EM.PERS_LINK)
left join dbo.FACE_DOCUMENT FD on FD.LINK = PERS.DOC_LINK 
left join dbo.DEPARTMENTS FO WITH (NOLOCK) on D.FO_LINK = FO.LINK
left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
left join dbo.DEPARTMENTS DD WITH (NOLOCK) on DA.REF_LINK_D = DD.link
left join dbo.DEPARTMENTS UCHR WITH (NOLOCK) on D.UCHR_LINK = UCHR.LINK

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



GO
grant all on dbo.DOCUMENTS_RECEPTION_CASH to public

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

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

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

		[OSNOV_LINK] = T.OSNOV,

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

	FROM dbo.G_AVANSE_TABLE T
		LEFT JOIN dbo.S_ACCOUNTS SA1 ON T.DTACCOUNT = SA1.LINK
		LEFT JOIN dbo.S_ACCOUNTS SA2 ON T.KTACCOUNT = SA2.LINK
		LEFT JOIN dbo.DICTIONARY_ITEM DID ON T.EKR_DT = DID.LINK
		LEFT JOIN dbo.DICTIONARY_ITEM DIK ON T.EKR_KT = DIK.LINK
		LEFT JOIN dbo.KU_EMPL_PLACING E ON T.EMP = E.LINK

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

GO

GRANT SELECT ON dbo.[BK_DOC_TABLE_AO_FN] TO PUBLIC

GO

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


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

GO
CREATE FUNCTION dbo.sa_ssch_empls_nzp_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 = sum( CONVERT(NUMERIC(18,2),ssch) ), Y = YEAR(s.DATE), M = MONTH(s.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
					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_ALL] TO PUBLIC

GO




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

GO

CREATE  FUNCTION dbo.PrintFSSRep_GetDpData(@varKSnLinkDep int)
RETURNS TABLE 
AS
	RETURN 
	SELECT 
		DD1.OKPO AS OKPO1, 
		DD1.INN AS INN1, DD1.KPP AS KPP1, DD1.FULL_NAME, DD1.NAME AS ORGNAME,
		DD2.NALOG AS IMNS_SONO, DD2.NAME AS IMNS_NAME, 
		DD2.NALOG AS SONO, 
		DD1.OGRN AS OGRN1,
		LTRIM(RTRIM(dbo.GetAddressBykladr(DD1.REF_LINK_A))) 
			+ CASE WHEN ISNULL(DD1.HOUSE, '') = '' THEN '' ELSE  ' ' + LTRIM(RTRIM(DD1.HOUSE)) END
			+ CASE WHEN ISNULL(DD1.FLAT, '') = '' THEN '' ELSE ' - ' + LTRIM(RTRIM(DD1.FLAT)) END
		AS ADDR_STR,
		CAST(NULL AS DATETIME) AS DATE_END,
		RTRIM(CHIEF.FM) + ' ' + LEFT(CHIEF.IM, 1) + '. ' + LEFT(CHIEF.OT,1) + '.' AS CHIEF_FIO,
		RTRIM(CHIEF.PHONE) AS CH_PHONE,
		RTRIM(GLBUH.FM) + ' ' + LEFT(GLBUH.IM, 1) + '. ' + LEFT(GLBUH.OT,1) + '.' AS GLBUH_FIO,
		RTRIM(GLBUH.PHONE) AS GL_PHONE,
		DD1.OGRN,
		(CASE WHEN dbo.SA_GET_OPTION_BY_CODE('NASTR_USE_OKATO_OKTMO') = 1 then DD1.OKATO ELSE '' END) AS OKATO,		DD1.OKTMO,
		DD1.OKVED,
		DD1.OKPO,
		DD1.FSS_REG_NUM, --Регистрационный номер (код) страхователя ТФОМС
		DD1.FSS_KOD_P, --Код подчиненности - код, состоящий из пяти цифр, указывающий на территориальный орган Фонда, в котором страхователь зарегистрирован в текущий момент;	
		DD1.FSS_KOD_DOP, --Дополнительный код предусмотрен для обособленных подразделений организаций
		DD1.OKOPF, --- код Общероссийского классификатора организационно-правовых форм;
		DD1.OKFS, --- код Общероссийского классификатора форм собственности;
		DD1.PFNUMBER,
		DA.PINDEX, DA.REGION, DA.REGCODE, DA.RAION, DA.GOROD, DA.NASEL, DA.STREET, DA.HOUSE, DA.KORP, DA.FLAT,
		TFOMS_RNUM = DD1.TFOMS_REG_NUM,
		TFOMS_KT = DD1.TFOMS_KT,
		DD1.FSS_KP_PC1, DD1.FSS_KP_PC2, DD1.FSS_KP_PC3
	FROM DICTIONARY_DEPARTMENT DD1 
		LEFT OUTER JOIN DICTIONARY_DEPARTMENT DD2 ON DD1.IMNS_LINK = DD2.LINK
		LEFT OUTER JOIN dbo.GetOtvFaceData(@varKSnLinkDep, 'Руководитель') chief on chief.link_dep = dd1.link
		LEFT OUTER JOIN dbo.GetOtvFaceData(@varKSnLinkDep, 'Главный бухгалтер') GLBUH ON GLBUH.link_dep = dd1.link
		LEFT JOIN DBO.DEP_ADRESS(@varKSnLinkDep) DA ON 1=1
	WHERE DD1.LINK = @varKSnLinkDep




GO


GRANT SELECT ON dbo.[PrintFSSRep_GetDpData] TO PUBLIC

GO


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

GO
CREATE PROCEDURE dbo.BK_EXPORT_F1152028_503
	(@iLINK_FORM INT)
AS
BEGIN
--перенос формы из архивной базы
	exec dbo.RN_MOVE_FORM_FROM_ARH @iLINK_FORM

	DECLARE
		@FNAME VARCHAR (254),
		@FNAME_ID VARCHAR (254),

		@PART_NAME_NNN VARCHAR (100),

		@DEP_LINK	INT,
		@INN	VARCHAR (12),
		@KPP VARCHAR (9),
		@IMNS VARCHAR (4),
		@OKVED VARCHAR (8),
		@TLF_GL_BUH	VARCHAR (10),
		@DEP_NAME VARCHAR (254),

		@C_PLACE	VARCHAR (3),
		@C_TYPE		VARCHAR (1),

		@NAME_RUK	VARCHAR (60),
		@FAM_RUK	VARCHAR (60),
		@OT_RUK		VARCHAR (60),

		@dDATE_FORM	DATETIME,
		@PERIOD_TYPE	INT,
		@PERIOD_NUM	INT,
		@cPERIOD_NUM	VARCHAR (2),

		@iLINK_TABLE	INT,
		@PROC_NAME	VARCHAR (254),

		--- Раздел 1 ---
		@KBK VARCHAR (20),
		@OKTMO VARCHAR (15),
		@OKTMO_DIC VARCHAR (15),
		@SUMMA	NUMERIC (15,0),

		--- Раздел 2 ---
		@ST_IMUSH	NUMERIC (15,0),
		@CODE_NL	VARCHAR (20),
		@ST_IMUSH_NO NUMERIC (15,0),
		@Dol_ST	VARCHAR (21),
		@CODE_LG_PNS VARCHAR (7),
		@NAL_STAV	NUMERIC (3,2),
		@NAL_BASE	NUMERIC (15,0),
		@SUM_NAL_PER	NUMERIC (15,0),

		@SumAV	NUMERIC (15),
		@CODE_LG_UM	VARCHAR (7),
		@SUM_LG_UM NUMERIC (15),

		@SUM_NAL_PRED	NUMERIC (15),
		@OST_SUM_ALL	NUMERIC (15,0),

		@strNUM_COR	VARCHAR (3),

		@strEXEC	VARCHAR (8000),

		@cREORG_CODE	VARCHAR (1),
		@cREORG_INN	VARCHAR (12),
		@cREORG_KPP	VARCHAR (12)

	--- ---
	SELECT
		@DEP_LINK = LINK_ORGANIZATION,
		@dDATE_FORM	= BEGIN_DATE,
		@PERIOD_TYPE = PERIOD_TYPE,
		@PERIOD_NUM	= PERIOD_NUMBER
	FROM dbo.REPORT_SAVED_FORMS RSF
	WHERE link_saved_form = @iLINK_FORM

	EXEC dbo.GetRandStr 36, @PART_NAME_NNN OUTPUT

	SELECT
		@INN	= CONVERT (VARCHAR (10), INN_LONG),
		@KPP = CONVERT (VARCHAR (9), KPP),
		@IMNS = CONVERT (VARCHAR (4), IMNS),
		@OKVED = CONVERT (VARCHAR (8), OKVED),
		@DEP_NAME = [NAME],
		@OKTMO_DIC = CONVERT (VARCHAR (11), REPLACE (OKTMO, ' ', ''))
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @DEP_LINK

	SELECT
		@TLF_GL_BUH = PHONE
	FROM dbo.DICTIONARY_OTV_FACE
	WHERE DEP_LINK = @DEP_LINK
		AND [NAME] = 'Главный бухгалтер'

	SELECT
		@NAME_RUK = IM,
		@FAM_RUK = FM,
		@OT_RUK = OT
	FROM dbo.KU_EMPL_PLACING 
	WHERE LINK = (SELECT FACE_LINK FROM dbo.DICTIONARY_OTV_FACE
					WHERE DEP_LINK = @DEP_LINK
						AND [NAME] = 'Руководитель')

	--- !!!РАСЧЕТ!!! ---
	-- Данные раздела 1 --
	SELECT 
		@iLINK_TABLE = RT.LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 1
		)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R1
		(
		CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (50),
		COL2 VARCHAR(254),	-- КБК
		FCOL2 VARCHAR (254),
		COL3 VARCHAR (100), 	-- ОКТМО
		FCOL3 VARCHAR (254),
		COL4 VARCHAR(100), 	-- Сумма к уплате
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Сумма к уменьшению
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- По месту нахождения
		FCOL6 VARCHAR (254),
		COL7 VARCHAR(100), 	-- Вид имущества
		FCOL7 VARCHAR (254),
		COL8 VARCHAR(100), 	-- Код налогового периода
		FCOL8 VARCHAR (254),
		COL9 VARCHAR(100), 	-- Форма реорганизации
		FCOL9 VARCHAR (254),
		COL10 VARCHAR(100), 	-- INN реорганизации
		FCOL10 VARCHAR (254),
		COL11 VARCHAR(100), 	-- KPP реорганизации
		FCOL11 VARCHAR (254),
		COL12 VARCHAR(100), 	-- Номер корректировки
		FCOL12 VARCHAR (254),
		ITOG NUMERIC (20)
		) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R1 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, FCOL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, COL7, FCOL7,
		COL8, FCOL8, COL9, FCOL9,
		COL10, FCOL10, COL11, FCOL11, COL12, FCOL12, ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

	SELECT
		@KBK = ISNULL (COL2, ''),
		@OKTMO = ISNULL (COL3, ''),
		@SUMMA = CONVERT (NUMERIC (15), COL4) - ISNULL (CONVERT (NUMERIC (15), COL5), 0),
		@C_PLACE = ISNULL (COL6, ''),
		@cPERIOD_NUM = ISNULL (COL8, ''),

		@cREORG_CODE = ISNULL (COL9, ''),
		@cREORG_INN = ISNULL (COL10, ''),
		@cREORG_KPP = ISNULL (COL11, ''),

		@strNUM_COR = ISNULL (COL12, ''),
		@C_TYPE = ISNULL (COL7, '')
	FROM #TAB_R1

	-- ДАННЫЕ РАЗДЕЛА 2 --
	-- Данные раздела 2.1 --
	--- Остаточная стоимость имущества по месяцам ---
	SELECT 
		@iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 2
		)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R21
		(
		CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(254),	
		COL3 NUMERIC (20), 	-- Сумма
		FCOL3 VARCHAR (254),
		COL4 NUMERIC (20), 	-- Налоговая ставка
		FCOL4 VARCHAR (254),
		ITOG NUMERIC (20)
		) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R21 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, COL3, FCOL3,
		COL4, FCOL4, ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

-- SELECT * FROM #TAB_R21

	-- Данные раздела 2.2 --
	-- !!!Расчет!!! --
	SELECT
		@iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 3
		)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R22
		(CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(254),	
		COL3 NUMERIC (20), 	-- Сумма
		FCOL3 VARCHAR (254),
		COL4 NUMERIC (20, 2), 	-- Налоговая ставка
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Код налоговой льготы 1
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- Код налоговой льготы 2
		FCOL6 VARCHAR (254),
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R22 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, 
		ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

-- SELECT * FROM #TAB_R22

	SELECT
		@ST_IMUSH = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '120'

	SELECT
		@CODE_NL = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '130'

	SELECT
		@ST_IMUSH_NO = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '140'

	SELECT
		@Dol_ST = CONVERT (VARCHAR (22), COL5)
	FROM #TAB_R22
	WHERE CODE = '150'

	SELECT
		@CODE_LG_PNS = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '160'

	SELECT
		@NAL_STAV = CONVERT (NUMERIC (4,2), COL4)
	FROM #TAB_R22
	WHERE CODE = '170'

	SELECT
		@SUM_NAL_PER = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '180'

	SELECT
		@CODE_LG_UM = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '190'

	SELECT
		@SUM_LG_UM = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '200'
	
	SELECT
		@OST_SUM_ALL = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '210'

	-- Данные раздела 3 --
	-- !!!Расчет!!! --
	SELECT 
		@iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 4
		)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R3
		(
		CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(254),	
		COL3 NUMERIC (20), 	-- Сумма
		FCOL3 VARCHAR (254),
		COL4 NUMERIC (20, 2), 	-- Налоговая ставка
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Код налоговой льготы 1
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- Код налоговой льготы 2
		FCOL6 VARCHAR (254),
		COL7 VARCHAR (100), 	-- Кадастровый номер
		FCOL7 VARCHAR (254),
		ITOG NUMERIC (20)
		) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R3 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, COL7, FCOL7, 
		ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

 -- SELECT * FROM #TAB_R3
	--- Формирование XML ---
	SELECT
		@FNAME_ID = 'NO_IMUR_' + ISNULL (RTRIM (@IMNS), '0000') + '_' + ISNULL (RTRIM (@IMNS), '0000') + '_'
		+ ISNULL (RTRIM (@INN), '0000000000') + ISNULL (RTRIM (@KPP), '000000000')
		+ '_' + CONVERT (VARCHAR (10), GETDATE (), 112) + '_'
		+ SUBSTRING (@PART_NAME_NNN, LEN (@PART_NAME_NNN) - 36, 36) 

	SELECT @FNAME = RTRIM (@FNAME_ID) + '.XML'

	DECLARE @OUTPUT TABLE
		(
		ID INT IDENTITY (1,1),
		F_NAME VARCHAR(254) DEFAULT (''),
		OUT_TEXT TEXT DEFAULT ('')
		)

	--Строка заголовка
	CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))

	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

	DECLARE @NAME_PROG VARCHAR(254),
		@VERS_PROG VARCHAR(254)

	SELECT @NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
		@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
		+ '.' + (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
		+ '.' + (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
	FROM dbo.DICTIONARY_TASK
	WHERE CODE = 'SMETA'

	SET @NAME_PROG = RTRIM (@NAME_PROG) + ' ' + @VERS_PROG

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'OEM')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<?xml version="1.0" encoding="windows-1251" ?>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Файл xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИдФайл="' + RTRIM (@FNAME_ID) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсПрог="' + RTRIM (LEFT (@NAME_PROG, 40)) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсФорм="5.03">')

	-- Документ
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Документ КНД="1152028"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ДатаДок="' + CONVERT (VARCHAR (10), GETDATE (), 104) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Период="' + @cPERIOD_NUM + '"')	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ОтчетГод="' + LTRIM (STR (YEAR (@dDATE_FORM))) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КодНО="' + ISNULL (@IMNS, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НомКорр="' + ISNULL (@strNUM_COR, '0') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ПоМесту="' + ISNULL (@C_PLACE, '') + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СвНП ОКВЭД="' + ISNULL (@OKVED, '') + '"')
	IF ISNULL (@TLF_GL_BUH, '') <> ''
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Тлф="' + RTRIM (ISNULL (@TLF_GL_BUH, '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НПЮЛ НаимОрг="'
			 + RTRIM (ISNULL (REPLACE (@DEP_NAME, '"', '&quot;'), '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИННЮЛ="' + ISNULL (@INN, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КПП="' + ISNULL (@KPP, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '>')

	-- Сведения о реорганизованной (ликвидированной) организации (СвРеоргЮЛ)
	IF LEN (@cREORG_CODE) > 0	
	BEGIN
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СвРеоргЮЛ ФормРеорг="'
			+ ISNULL (@cREORG_CODE, '') + '"')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИННЮЛ="' + ISNULL (@cREORG_INN, '') + '"')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КПП="' + ISNULL (@cREORG_KPP, '') + '"')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '/>')
	END

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</НПЮЛ>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СвНП>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Подписант ПрПодп="1">')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ФИО Фамилия="' + RTRIM (ISNULL (@FAM_RUK, '')) 
					+ '" Имя="' + RTRIM (@NAME_RUK) + '"'
					+ CASE WHEN ISNULL (@OT_RUK, '') <> '' THEN ' Отчество="' + RTRIM (ISNULL (@OT_RUK, '')) + '"'
							ELSE '' END
					+ '/>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Подписант>')

	-- Данные налога на имущество --
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ИмущАв>')

   	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СумНалПУ КБК="' + ISNULL (@KBK, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ОКТМО="' + CASE WHEN ISNULL (@OKTMO, '') = ''
											THEN ISNULL (@OKTMO_DIC, '')
											ELSE @OKTMO END + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + LTRIM (STR (ISNULL (@SUMMA, 0))) + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОбДеятРФ>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОб ВидИмущ="' + ISNULL (@C_TYPE, '') + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ДанРас СтИмущ="' + LTRIM (STR (ISNULL (@ST_IMUSH, 0))) + '"'
			+	CASE WHEN ISNULL (@CODE_NL, '') = '' THEN ''
					ELSE ' КодНалЛьг="' + @CODE_NL + '"'
				END
			+	CASE WHEN ISNULL (@ST_IMUSH_NO, 0) = 0 THEN ''
					ELSE ' СтИмущНеобл="' + LTRIM (STR (ISNULL (@ST_IMUSH_NO, 0))) + '"'
				END
			+	CASE WHEN ISNULL (@Dol_ST, '') = '' THEN ''
					ELSE ' ДолСт="' + @Dol_ST + '"'
				END
			+	CASE WHEN ISNULL (@CODE_LG_PNS, '') = '' THEN ''
					ELSE ' КодЛгПНС="' + @CODE_LG_PNS + '"'
				END
			+	' НалСтав="' + LTRIM (STR (ISNULL (@NAL_STAV, 0.0), 4, 2)) + '"'
			+ '>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СтоимМес>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) 
	SELECT @FNAME,
		CASE
			WHEN CODE = '141' THEN '<ВтчНедИм'
			ELSE '<ОстСтом' + REPLACE (RTRIM (COL1), '.', '')
		END
		+ CASE WHEN ISNULL (COL3, 0) = 0 THEN ''
				ELSE ' СтОст="' + LTRIM (STR (COL3)) +'"'
			END
		+ CASE WHEN ISNULL (COL4, 0) = 0 THEN ''
				ELSE ' СтЛьгИмущ="' + LTRIM (STR (COL4)) +'"'
			END
		+ '/>'
	FROM #TAB_R21

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СтОстВс>' + LTRIM (STR (ISNULL (@OST_SUM_ALL, 0))) + '</СтОстВс>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СтоимМес>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ДанРас>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ОтчПер СумАвИсчисл="' + LTRIM (STR (ISNULL (@SUM_NAL_PER, 0))) + '"'
			+ CASE WHEN ISNULL (@CODE_LG_UM, '') = '' THEN ''
					ELSE ' КодЛгУмен="' + RTRIM (@CODE_LG_UM) + '"'
			END
			+ CASE WHEN ISNULL (@SUM_LG_UM, 0) = 0 THEN ''
					ELSE ' СумЛгУмен="' + LTRIM (STR (ISNULL (@SUM_LG_UM, 0))) + '"'
			END
			+ '/>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОб>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОбДеятРФ>')

	-- Выгрузка 3 раздела --
	IF EXISTS (SELECT 1 FROM #TAB_R3 WHERE (CODE = '014' OR CODE = '015') AND ISNULL (COL7, '') <> '')
	BEGIN
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОБНедИО>')

		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОб>')
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ДанРас>')
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) 
		SELECT
			@FNAME,
			CASE
				WHEN CODE = '014' THEN '<НомКадЗдан>' + LTRIM (ISNULL (COL7, '')) + '</НомКадЗдан>'
				WHEN CODE = '015' AND (ISNULL (COL7, '')) <> '' THEN '<НомКадПом>' + LTRIM (COL7) + '</НомКадПом>'
				WHEN CODE = '020' THEN '<СтИмущК>' + CONVERT (VARCHAR (20), ISNULL (COL3, 0)) + '</СтИмущК>'
				WHEN CODE = '030' AND ISNULL (COL3, 0) <> 0 THEN '<СтИмущНеоблК>' + CONVERT (VARCHAR (20), COL3) + '</СтИмущНеоблК>'
				WHEN CODE = '040' AND (ISNULL (COL5, '')) <> '' THEN '<КодНалЛьг>' + LTRIM (COL5)
						+
						CASE
							WHEN ISNULL (COL6, '') = '' THEN ''
							ELSE '/' + LTRIM (COL6)
						END
						+ '</КодНалЛьг>'
				WHEN CODE = '050' AND (ISNULL (COL5, '')) <> '' THEN '<ДолСт>' + LTRIM (COL5) + '</ДолСт>'		
				WHEN CODE = '060' AND (ISNULL (COL5, '')) <> '' THEN '<КодЛгПНС>' + LTRIM (COL5)
						+
						CASE
							WHEN ISNULL (COL6, '') = '' THEN ''
							ELSE '/' + LTRIM (COL6)
						END
						+ '</КодЛгПНС>'
				WHEN CODE = '070' THEN '<НалСтав>' + CONVERT (VARCHAR (10), ISNULL (COL4, 0)) + '</НалСтав>'		
				WHEN CODE = '080' AND (ISNULL (COL5, '')) <> '' THEN '<КоэфК>' + LTRIM (COL5)
						+
						CASE
							WHEN ISNULL (COL6, '') = '' THEN ''
							ELSE '/' + LTRIM (COL6)
						END
						+ '</КоэфК>'
				ELSE ''
			END
		FROM #TAB_R3
		WHERE CODE = '014'
			OR CODE = '015'
			OR CODE = '020'
			OR CODE = '030' 
			OR CODE = '040'
			OR CODE = '050'
			OR CODE = '060'
			OR CODE = '070'
			OR CODE = '080'
		ORDER BY CODE	

		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ДанРас>')
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ОтчПер>')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT)
		SELECT
			@FNAME,
			CASE 
				WHEN CODE = '090' THEN '<СумАвИсчисл>' + CONVERT (VARCHAR (20), ISNULL (COL3, 0)) + '</СумАвИсчисл>'
				WHEN CODE = '100' AND (ISNULL (COL5, '')) <> '' THEN '<КодЛгУмен>' + LTRIM (COL5)
						+
						CASE
							WHEN ISNULL (COL6, '') = '' THEN ''
							ELSE '/' + LTRIM (COL6)
						END
						+ '</КодЛгУмен>'
				WHEN CODE = '110' AND ISNULL (COL3, 0) <> 0 THEN '<СумЛгУмен>' + CONVERT (VARCHAR (20), COL3) + '</СумЛгУмен>'
				ELSE ''
			END
		FROM #TAB_R3
		WHERE
			CODE = '090' 
			OR CODE = '100' 
			OR CODE = '110' 
		ORDER BY CODE	
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ОтчПер>')

		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОб>')
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОБНедИО>')
	END	-- Выгрузка 3 раздела --
	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СумНалПУ>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ИмущАв>')

	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Документ>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Файл>')

	SELECT * FROM @OUTPUT ORDER BY ID

	DROP TABLE #TAB_R1
	DROP TABLE #TAB_R21
	DROP TABLE #TAB_R22
	DROP TABLE #TAB_R3
	DROP TABLE #TASK_PROP

END 

GO

GRANT EXECUTE ON dbo.[BK_EXPORT_F1152028_503] TO PUBLIC

GO

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


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


create procedure dbo.BB_UVED_GET_DOC @iLinkDoc int

as
declare @cDocCode varchar(100), 
		@cDocName varchar(254),
		@iObjLink int


select	@cDocCode = SO.CODE, 
		@cDocName = OV.NAME,
		@iObjLink = SO.LINK
from dbo.G_PROV G  
inner join dbo.S_OBJECTS SO on G.OBJECT = SO.LINK  and G.LINK = @iLinkDoc
inner join dbo.OSNOV_VID OV on OV.OBJECT = SO.CODE 
					
		  

if @cDocCode = 'DOCUMENTS_RECEPTION_CASH'
	Select	CHECKED = 0, UPD = 1, DEL = 0, LINK = 0, LINK_UP = 0, 
			DOC_NUM = G.NUMBER, DOC_DATE = G.DATE, DOC_TYPE = @cDocName, DOC_CODE = @cDocCode, 
			DOC_NAME = @cDocName +' № '+ LTRIM(RTRIM(G.NUMBER))+' от ' + CONVERT(VARCHAR(10),G.DATE,104),
			DEP_CODE = D.CODE, DEP_NAME	= D.FULL_NAME, DEP_INN = rtrim(D.INN) + case when D.INN_DOP = '' then '' else '\' + D.INN_DOP end, DEP_KPP	= D.KPP, DEP_OKATO = D.OKTMO, 
			KBK_CODE = KBK.CODE, KBK_TYPE	= KBK.TYPE, SGU_CODE = SGU.CODE, DCL_CODE = DCL.CODE, SUMMA = T.SUMMA, 
			[TARGET] = coalesce(T.REASON,CONVERT(VARCHAR(210), (select GPV.VALUE from dbo.G_PROV_VALUE gpv where GPV.DOC_LINK = @iLinkDoc and GPV.OBJECT = @iObjLink)),''), 
			TITLE = '', 
			DOC_LINK = G.LINK, DEP_LINK = D.LINK, KBK_LINK = KBK.LINK, SGU_LINK = SGU.LINK, DCL_LINK = DCL.LINK 
	from dbo.G_PROV G  
	inner join dbo.RECEPTION_CASH_TABLE T on T.LINK_UP = G.LINK
	inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = G.ACC
	inner join dbo.DEPARTMENTS D on D.LINK = G.DEP
	inner join dbo.KL_KBK KBK on KBK.LINK = T.KBK
	inner join dbo.KOSGU  SGU on SGU.LINK = T.EKR
	left join dbo.DOP_CLASSIF DCL on DCL.LINK = T.DOP_CLASSIF
	where G.LINK = @iLinkDoc
	
else 
	if @cDocCode = 'BB_ZAYAVKA_KR'
		Select	CHECKED = 0, UPD = 1, DEL = 0, LINK = 0, LINK_UP = 0, 
				DOC_NUM = G.NUMBER, DOC_DATE = G.DATE, DOC_TYPE = @cDocName, DOC_CODE = @cDocCode, 
				DOC_NAME = @cDocName +' № '+ LTRIM(RTRIM(G.NUMBER))+' от ' + CONVERT(VARCHAR(10),G.DATE,104),
				DEP_CODE = D.CODE, DEP_NAME	= D.FULL_NAME, DEP_INN = rtrim(D.INN) + case when D.INN_DOP = '' then '' else '\' + D.INN_DOP end, DEP_KPP	= D.KPP, DEP_OKATO = D.OKTMO, 
				KBK_CODE = KBK.CODE, KBK_TYPE	= KBK.TYPE, SGU_CODE = SGU.CODE, DCL_CODE = DCL.CODE, SUMMA = T.SUMMA, 
				[TARGET] = coalesce(T.[TARGET],LEFT(Z.TARGETTEXT,210),''), 
				TITLE = '', 
				DOC_LINK = G.LINK, DEP_LINK = D.LINK, KBK_LINK = KBK.LINK, SGU_LINK = SGU.LINK, DCL_LINK = DCL.LINK 
		from dbo.G_PROV G  
		inner join dbo.FINANSE_PAYS Z on Z.LINK = G.LINK
		inner join dbo.ZAYAVKA_KR_TABLE T on T.LINK_UP = G.LINK
		inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = Z.D_ACC
		inner join dbo.DEPARTMENTS D on D.LINK = DA.LINK_UP
		inner join dbo.KL_KBK KBK on KBK.LINK = T.LINK_KBK
		inner join dbo.KOSGU  SGU on SGU.LINK = T.LINK_SGU
		left join dbo.DOP_CLASSIF DCL on DCL.LINK = T.LINK_DCL
		where G.LINK = @iLinkDoc

	else
		if @cDocCode = 'DOCUMENTS_PAY'
			Select	CHECKED = 0, UPD = 1, DEL = 0, LINK = 0, LINK_UP = 0, 
					DOC_NUM = G.NUMBER, DOC_DATE = G.DATE, DOC_TYPE = @cDocName, DOC_CODE = @cDocCode, 
					DOC_NAME = @cDocName +' № '+ LTRIM(RTRIM(G.NUMBER))+' от ' + CONVERT(VARCHAR(10),G.DATE,104),
					DEP_CODE = D.CODE, DEP_NAME	= D.FULL_NAME, DEP_INN = rtrim(D.INN) + case when D.INN_DOP = '' then '' else '\' + D.INN_DOP end, DEP_KPP	= D.KPP, DEP_OKATO = D.OKTMO, 
					KBK_CODE = KBK.CODE, KBK_TYPE	= KBK.TYPE, SGU_CODE = SGU.CODE, DCL_CODE = DCL.CODE, SUMMA = G2.SUMMA, 
					[TARGET] = isnull(LEFT(Z.TARGETTEXT,210),''), 
					TITLE = '', 
					DOC_LINK = G.LINK, DEP_LINK = D.LINK, KBK_LINK = KBK.LINK, SGU_LINK = SGU.LINK, DCL_LINK = DCL.LINK 
			from dbo.G_PROV G  
			inner join dbo.FINANSE_PAYS Z on Z.LINK = G.LINK
			inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = Z.D_ACC
			inner join dbo.DEPARTMENTS D on D.LINK = DA.LINK_UP
			inner join dbo.G_PROV1 G1 on G1.LINK_UP = G.LINK 
			inner join dbo.G_PROV2 G2 on G2.LINK_UP = G1.LINK 
			inner join dbo.G_PROV_AP GAP1 on GAP1.LINK_UP = G2.LINK and GAP1.DB_KR = 0 
			inner join dbo.G_PROV_AP GAP2 on GAP2.LINK_UP = G2.LINK and GAP2.DB_KR = 1 
			inner join dbo.KL_KBK KBK on KBK.LINK = isnull(GAP2.KBK,GAP1.KBK) 
			inner join dbo.KOSGU  SGU on SGU.LINK = isnull(GAP2.SGU,GAP1.SGU) 
			left join dbo.DOP_CLASSIF DCL on DCL.LINK = isnull(GAP2.AP2,GAP1.AP2) 
			where G.LINK = @iLinkDoc
			

		else
		Select	CHECKED = 0, UPD = 1, DEL = 0, LINK = 0, LINK_UP = 0, 
								LINK_G1 = G1.LINK, DOC_NUM = G.NUMBER, DOC_DATE = G.DATE,	DOC_TYPE = @cDocName, DOC_CODE = @cDocCode, 
								DOC_NAME = CONVERT(VARCHAR(50), case @cDocCode when 'DOCUMENTS_OPER' then dbo.JurnalProvGetDocKind (G.LINK, G.OBJECT) else @cDocName end +' № ' + LTRIM(RTRIM(G.NUMBER))+' от ' + CONVERT(VARCHAR(10),G.DATE,104)),
								DEP_CODE = D.CODE, DEP_NAME	= D.FULL_NAME, DEP_INN = rtrim(D.INN) + case when D.INN_DOP = '' then '' else '\' + D.INN_DOP end, DEP_KPP	= D.KPP, DEP_OKATO = D.OKTMO, 
								KBK_CODE = KBK.CODE, KBK_TYPE	= KBK.TYPE, SGU_CODE = SGU.CODE, DCL_CODE = DCL.CODE, SUMMA = G2.SUMMA, 
								[TARGET] = '', TITLE = '', 
								DOC_LINK = G.LINK, DEP_LINK = D.LINK, KBK_LINK = KBK.LINK, SGU_LINK = SGU.LINK, DCL_LINK = DCL.LINK 
							from dbo.G_PROV G  
							inner join dbo.G_PROV1 G1 on G1.LINK_UP = G.LINK 
							inner join dbo.G_PROV2 G2 on G2.LINK_UP = G1.LINK 
							inner join dbo.G_PROV_AP GAP1 on GAP1.LINK_UP = G2.LINK and GAP1.DB_KR = 0 
							inner join dbo.G_PROV_AP GAP2 on GAP2.LINK_UP = G2.LINK and GAP2.DB_KR = 1 
							left join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = isnull(GAP2.DEP_ACC,GAP1.DEP_ACC) 
							left join dbo.DEPARTMENTS D on D.LINK = coalesce(GAP2.DEP,GAP1.DEP,DA.LINK_UP) 
							inner join dbo.KL_KBK KBK on KBK.LINK = isnull(GAP2.KBK,GAP1.KBK) 
							inner join dbo.KOSGU  SGU on SGU.LINK = isnull(GAP2.SGU,GAP1.SGU) 
							left join dbo.DOP_CLASSIF DCL on DCL.LINK = isnull(GAP2.AP2,GAP1.AP2) 
							where G.LINK = @iLinkDoc
							
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_FORM_VIEW_DOCUMENT_TABLE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_FORM_VIEW_DOCUMENT_TABLE]

GO


CREATE   PROCEDURE dbo.BK_FORM_VIEW_DOCUMENT_TABLE
	@varKScCode varchar(30)
AS
	DECLARE 
		@varKSnLink		int,
		@varKSCurLINK	int,
		@varKSCurLINK2	int,
		@varKSFirst		int,
		@varKSCurCODE	varchar(30),
		@varKSRefDict	varchar(30),
		@varKSRefField	varchar(300),
		@varKSShortCode	varchar(30),
		@varKSInALIAS	varchar(10),
		@varKSType		varchar(30),
		@varKSStorage	varchar(30),
		@varKSSel_Str	varchar(7000),
		@varKSCur_Str	varchar(1000),
		@varKSEMP		varchar(1),
		@varKSRefLINK	int,
		@varKSintval		int,
		@varKShostTypeObject	varchar(30)
--	
	SELECT @varKSnLink = LINK FROM S_OBJECTS WHERE CODE = @varKScCode
IF @varKSnLink is null OR @varKSnLink=0
BEGIN
	print 'Произошла неустранимая ошибка при формировании запроса.
     Попробуйте обратиться в службу поддержки.
    Или просто задайте правильное имя объекта!'
	Return
END

	DECLARE SEL_CURSOR  CURSOR STATIC LOCAL
	FOR SELECT DISTINCT LINK, CODE 
	FROM S_OBJECTS WHERE LINK_SELF=@varKSnLink 


print '---------------------------------------'+@varKScCode+'(таблица)'
	SET @varKSSel_Str=
'
--Процедура сформирована с помощью BK_FORM_VIEW_DOCUMENT_TABLE 
--'+LTRIM(convert(char, getdate()))+'
VIEW dbo.' + LTRIM (@varKScCode) + ' AS
SELECT 
	OTR.LINK,
	OTR.LINK_UP,
	OTR.ORDERS,
	OTR.LINK_OPER'

	
	OPEN SEL_CURSOR
	FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXECUTE X_GET_PROP @varKSCurCODE, 'FIELD_IN_ALIAS', @varKSInALIAS OUTPUT
		EXECUTE X_GET_PROP @varKSCurCODE, 'STORAGE', @varKSStorage OUTPUT
		
		IF Convert(int, @varKSInALIAS) = 1 AND @varKSStorage<>''
		BEGIN
			EXECUTE X_GET_PROP  @varKSCurCODE, 'REFERENCE_TO_DICT', @varKSRefDict OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'REFERENCE_TO_FIELD', @varKSRefField OUTPUT
			SET @varKSRefField = RTRIM(LTRIM(@varKSRefField))
			EXECUTE X_GET_PROP  @varKSCurCODE, 'SHORT_CODE_OBJ', @varKSShortCode OUTPUT
			SET @varKSCurCODE = RTRIM(LTRIM(@varKSCurCODE))
			IF LEN(@varKSShortCode)>10
				print 'ПРЕДУПРЕЖДЕНИЕ: Длина поля SHORT_CODE_OBJ больше 10 символов!!!'

			SET @varKShostTypeObject = @varKSCurCODE
			IF @varKSStorage IN('DICTION', 'SUBDIV') AND @varKSRefField <> 'LINK'
			BEGIN
				Declare @varKSOVHValue varchar(254)
				Select @varKSOVHValue = RTRIM(Value)
				From OBJECT_VALUES OVH
				Where OVH.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_DICT')
					AND OVH.OBJECT = (select LINK from s_objects where code = @varKSRefDict)

				SELECT @varKShostTypeObject = SO.CODE
					FROM S_OBJECTS SO, OBJECT_VALUES OVF,
						OBJECT_VALUES OVS, S_OBJECTS SOH
					WHERE SOH.CODE = @varKSOVHValue
						AND SO.LINK_SELF = SOH.LINK

						AND OVF.OBJECT = SO.LINK AND OVF.PROPERTY = (select LINK from S_PROPERTY where CODE = 'SHORT_CODE_OBJ') AND OVF.VALUE = @varKSRefField
						AND OVS.OBJECT = SO.LINK AND OVS.PROPERTY = (select LINK from S_PROPERTY where CODE = 'STORAGE') AND OVS.VALUE = 'DICTION'
				IF @@ROWCOUNT = 0
					print '******* Ошибка! Не найден базовый тип данных!'
			END
			IF @varKSStorage = 'DICTION_APP'
				SET @varKShostTypeObject = @varKSRefField

			EXECUTE X_GET_PROP @varKShostTypeObject, 'TYPE_FIELD_DICT', @varKSType OUTPUT

			SET @varKSType = UPPER(LTRIM(@varKSType))
DECLARE	@varKSCNE	varchar(40), @varKSCSE varchar(40), @varKSTITLE varchar(40), @varKSED varchar(2), @varKSVIS varchar(2), @varKSINFO varchar(200)
			EXECUTE X_GET_PROP  @varKSCurCODE, 'CONTROL_NAME_EDIT', @varKSCNE OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'CONTROL_SOURCE_EDIT', @varKSCSE OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'TITLE', @varKSTITLE OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'EDITABLE', @varKSED OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'VISIBLE', @varKSVIS OUTPUT
			
			SET @varKSINFO='	'+convert(char(10),@varKSCNE)+convert(char(20),@varKSCSE)+convert(char(20),@varKSTITLE)+convert(varchar(2),@varKSED)+' '+convert(varchar(2),@varKSVIS)

			IF LTRIM(@varKSShortCode)='' OR @varKSShortCode is null
				print '****ОШИБКА!    Нет свойства SHORT_CODE_OBJ. Объект: '+@varKSCurCODE
			
 			IF @varKSStorage  ='DICTION_REF'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
				IF @@ROWCOUNT=0
					print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
				SELECT @varKSintval = CHARINDEX(',', @varKSRefField)
				SELECT @varKSRefLINK = LINK FROM S_OBJECTS WHERE CODE = RTRIM(SUBSTRING(@varKSRefField, 1, @varKSintval-1))
				IF @@ROWCOUNT=0
					print '****ОШИБКА!    REFERENCE_TO_FIELD не определено или ошибочно. Объект: '+@varKSCurCODE
				SELECT @varKSRefField = RTRIM(LTRIM(SUBSTRING(@varKSRefField, @varKSintval + 1, LEN(@varKSRefField) - @varKSintval)))
				IF @varKSRefField=''
					print '****ОШИБКА!    REFERENCE_TO_FIELD не определено или ошибочно. Объект: '+@varKSCurCODE
				IF @varKSRefField <> 'LINK'
				BEGIN
					SELECT @varKShostTypeObject = SO.CODE
						FROM S_OBJECTS SO, 
							OBJECT_VALUES OVH, S_OBJECTS SOH
						WHERE OVH.OBJECT = @varKSRefLINK
							AND OVH.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_DICT') 
							AND SOH.CODE = RTRIM(OVH.VALUE)
							AND SO.LINK_SELF = SOH.LINK
							AND exists(select * from OBJECT_VALUES OVF where OVF.OBJECT = SO.LINK AND OVF.PROPERTY = (select LINK from S_PROPERTY where CODE = 'REFERENCE_TO_FIELD') AND OVF.VALUE = @varKSRefField)
							AND exists(select * from OBJECT_VALUES OVS where OVS.OBJECT = SO.LINK AND OVS.PROPERTY = (select LINK from S_PROPERTY where CODE = 'STORAGE') AND OVS.VALUE = 'DICTION')
					IF @@ROWCOUNT = 0
						print '******* Ошибка! Не найден базовый тип данных!'
				END
				print 'WAS '+@varKSType
				EXECUTE X_GET_PROP @varKShostTypeObject, 'TYPE_FIELD_DICT', @varKSType OUTPUT
				print 'IS '+@varKSType
				IF @varKSType='' OR @varKSType is null
					print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				SET @varKSCur_Str=@varKSCur_Str+ 'Convert('+@varKSType+', (SELECT D.'+@varKSRefField
					SET @varKSCur_Str=@varKSCur_Str+
						' FROM DICTION_REF DR, DICTION D, OUT_TABLE_DICTION OTD'+
						' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND DR.REF_PRIMARY=OTD.DICTION AND DR.OBJECT = '+LTRIM(STR(@varKSRefLINK))+' AND D.LINK = DR.REF_FOREIGN)'

					IF @varKSType='DATETIME'
						SET @varKSCur_Str=@varKSCur_Str+',104'

				SET @varKSCur_Str=@varKSCur_Str + ')'

				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END
 			IF @varKSStorage  ='DICTION_APP'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
				IF @@ROWCOUNT=0
					print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
				SELECT @varKSRefLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefField
				IF @@ROWCOUNT=0
					print '****ОШИБКА!    REFERENCE_TO_FIELD не определено или ошибочно. Объект: '+@varKSCurCODE
				IF @varKSType='' OR @varKSType is null
					print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+', DA.VALUE'
					IF @varKSType='DATETIME'
						SET @varKSCur_Str=@varKSCur_Str+',104'
					SET @varKSCur_Str=@varKSCur_Str+')'+
						' FROM DICTION_APP DA, OUT_TABLE_DICTION OTD'+
						' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND DA.LINK_UP = OTD.DICTION AND DA.OBJECT = '+LTRIM(STR(@varKSRefLINK))+')'
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  ='DICTION'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT DICTION FROM OUT_TABLE_DICTION OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM DICTION D, OUT_TABLE_DICTION OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND D.LINK=OTD.DICTION)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END
 			IF @varKSStorage  ='ACCOUNT'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT ACCOUNT FROM dbo.OUT_TABLE_ACCOUNT OTA'+
							' WHERE OTA.LINK_UP=OTR.LINK AND OTA.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str= @varKSCur_Str+'(SELECT Convert (' +@varKSType + ', ' + @varKSRefField +
						CASE
							WHEN @varKSType = 'DATETIME' THEN ', 104'
							ELSE ''
						END +
					') FROM dbo.S_ACCOUNTS SA, dbo.OUT_TABLE_ACCOUNT OTA'+
							' WHERE OTA.LINK_UP=OTR.LINK AND OTA.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND SA.LINK=OTA.ACCOUNT)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END


 			IF @varKSStorage  ='DEPARTMENTS'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT DEPARTMENT FROM OUT_TABLE_DEPARTMENT OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.DEPARTMENTS D, dbo.OUT_TABLE_DEPARTMENT OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND D.LINK=OTD.DEPARTMENT)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  ='SUBDIV'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null

						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT SUBDIV FROM OUT_TABLE_SUBDIV OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.SUBDIV D, dbo.OUT_TABLE_SUBDIV OTD'+
							' WHERE OTD.LINK_UP=OTR.LINK AND OTD.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND D.LINK=OTD.SUBDIV)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END


			IF @varKSCurCODE <> @varKShostTypeObject
				print '-------->' + @varKShostTypeObject + ' ' + @varKSType

			IF @varKSStorage IN ('SUMMA', 'DATE', 'STRING')
			BEGIN
				IF @varKSType = ''
					SET @varKSCur_Str = '['+@varKSShortCode+'] = (SELECT '+@varKSStorage+' FROM dbo.OUT_TABLE_'+@varKSStorage+' WHERE LINK_UP=OTR.LINK AND OBJECT='+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
					SET @varKSCur_Str = '['+@varKSShortCode+'] = CONVERT('+@varKSType+', (SELECT '+@varKSStorage+' FROM dbo.OUT_TABLE_'+@varKSStorage+' WHERE LINK_UP=OTR.LINK AND OBJECT='+LTRIM(STR(@varKSCurLINK))+'))'
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),' - ') +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),' - ')+@varKSINFO
			END

 			IF @varKSStorage  = 'INVENTORY'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT INVENTORY FROM dbo.OUT_TABLE_INVENTORY OTI'+
							' WHERE OTI.LINK_UP=OTR.LINK AND OTI.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.INVENTORY INV, dbo.OUT_TABLE_INVENTORY OTI'+
							' WHERE OTI.LINK_UP=OTR.LINK AND OTI.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND INV.LINK=OTI.INVENTORY)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  = 'NOMENCLATURE'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT NOMENCLATURE FROM dbo.OUT_TABLE_NOMENCLATURE OTN'+
							' WHERE OTN.LINK_UP=OTR.LINK AND OTN.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.NOMENCLATURE INV, dbo.OUT_TABLE_NOMENCLATURE OTN'+
							' WHERE OTN.LINK_UP=OTR.LINK AND OTN.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND INV.LINK=OTN.NOMENCLATURE)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  = 'EMPL'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT EMPL FROM dbo.OUT_TABLE_EMPL OTE'+
							' WHERE OTE.LINK_UP=OTR.LINK AND OTE.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','
					IF @varKSRefField = 'NAME_EMPL'
					BEGIN
						SET @varKSCur_Str=@varKSCur_Str+' dbo.sd_GetEmplName (OTE.EMPL))'+ 
							' FROM dbo.OUT_TABLE_EMPL OTE'+
							' WHERE OTE.LINK_UP=OTR.LINK AND OTE.OBJECT= '+LTRIM(STR(@varKSCurLINK))+ ')'
					END
					ELSE
					BEGIN						
						SET @varKSCur_Str=@varKSCur_Str + @varKSRefField
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						ELSE	
							SET @varKSCur_Str=@varKSCur_Str+')'+
								' FROM dbo.EMPL EMP, dbo.OUT_TABLE_EMPL OTE'+
								' WHERE OTE.LINK_UP=OTR.LINK AND OTE.OBJECT= '+LTRIM(STR(@varKSCurLINK))+
								' AND EMP.LINK=OTE.EMPL)'
					END

				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  = 'KL_KBK'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT KBK FROM dbo.OUT_TABLE_KBK OTKBK'+
							' WHERE OTKBK.LINK_UP=OTR.LINK AND OTKBK.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.KL_KBK KBK, dbo.OUT_TABLE_KBK OTKBK'+
							' WHERE OTKBK.LINK_UP=OTR.LINK AND OTKBK.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND KBK.LINK=OTKBK.KBK)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

 			IF @varKSStorage  = 'KOSGU'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT KOSGU FROM dbo.OUT_TABLE_KOSGU OTSGU'+
							' WHERE OTSGU.LINK_UP=OTR.LINK AND OTSGU.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.KOSGU KSGU, dbo.OUT_TABLE_KOSGU OTSGU'+
							' WHERE OTSGU.LINK_UP=OTR.LINK AND OTSGU.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND KSGU.LINK = OTSGU.KOSGU)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

			IF @varKSStorage  = 'G_PROV'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT G_PROV FROM dbo.OUT_TABLE_G_PROV OTGP'+
							' WHERE OTGP.LINK_UP=OTR.LINK AND OTGP.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.G_PROV GP, dbo.OUT_TABLE_G_PROV OTGP'+
							' WHERE OTGP.LINK_UP=OTR.LINK AND OTGP.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND GP.LINK = OTGP.G_PROV)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

			IF @varKSStorage  = 'FIN_SOURCE'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT FIN_SOURCE FROM dbo.OUT_TABLE_FIN_SOURCE OTFS'+
							' WHERE OTFS.LINK_UP=OTR.LINK AND OTFS.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						IF @varKSType='DATETIME'
							SET @varKSCur_Str=@varKSCur_Str+',104'
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.FIN_SOURCE FS, dbo.OUT_TABLE_FIN_SOURCE OTFS' +
							' WHERE OTFS.LINK_UP=OTR.LINK AND OTFS.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND FS.LINK = OTFS.FIN_SOURCE)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

			IF @varKSStorage  = 'PERSON_ECARDS'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT ECARD FROM dbo.OUT_TABLE_ECARD OTEC'+
							' WHERE OTEC.LINK_UP=OTR.LINK AND OTEC.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
						SET @varKSCur_Str=@varKSCur_Str+')'+
							' FROM dbo.PERSON_ECARDS PE, dbo.OUT_TABLE_ECARD OTEC' +
							' WHERE OTEC.LINK_UP=OTR.LINK AND OTEC.OBJECT= '+LTRIM(STR(@varKSCurLINK))+' AND PE.LINK = OTEC.ECARD)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END

			IF @varKSStorage  = 'OSNOV'
			BEGIN
				SET @varKSCur_Str = '['+@varKSShortCode+'] = '
				IF @varKSRefField<>'LINK'
				BEGIN
					SELECT @varKSCurLINK = LINK FROM S_OBJECTS WHERE CODE = @varKSRefDict
					IF @@ROWCOUNT=0
						print '****ОШИБКА!    REFERENCE_TO_DICTION не определено или ошибочно. Объект: '+@varKSCurCODE
					
					IF @varKSType='' OR @varKSType is null
						print '****ОШИБКА!    Нет свойства TYPE_FIELD_DICT. Объект: '+@varKSCurCODE
				END
				ELSE
				BEGIN
					SET @varKSType=' - '
					SET @varKSRefDict=' - '
				END
				IF LTRIM(@varKSRefField)='' OR @varKSRefField is null
					print '****ОШИБКА!    Нет свойства REFERENCE_TO_FIELD. Объект: '+@varKSCurCODE
				IF @varKSRefField = 'LINK'
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT OSNOV FROM dbo.OUT_TABLE_OSNOV OTOSN'+
							' WHERE OTOSN.LINK_UP=OTR.LINK AND OTOSN.OBJECT= '+LTRIM(STR(@varKSCurLINK))+')'
				ELSE
				BEGIN
					SET @varKSCur_Str=@varKSCur_Str+'(SELECT Convert('+@varKSType+','+@varKSRefField
						
					IF @varKSType='DATETIME'
						SET @varKSCur_Str=@varKSCur_Str+',104'

					SET @varKSCur_Str = @varKSCur_Str+')'
						+
						CASE
							WHEN @varKSRefField = 'DATE_PROV' THEN
								' FROM dbo.G_PROV G, dbo.OSNOV GP, dbo.OUT_TABLE_OSNOV OTOSN'+
								' WHERE G.LINK = GP.LINK_G_PROV AND OTOSN.LINK_UP = OTR.LINK AND OTOSN.OBJECT= '
							ELSE
								' FROM dbo.BD_OSNOV GP, dbo.OUT_TABLE_OSNOV OTOSN'+
								' WHERE OTOSN.LINK_UP=OTR.LINK AND OTOSN.OBJECT= '
						END
						+ LTRIM(STR(@varKSCurLINK))+' AND GP.LINK = OTOSN.OSNOV)'
				END
				print convert(char(10),@varKSShortCode)+'	 '+ convert(char(35),@varKSRefDict) +'	'+convert(char(20),@varKSType)+'	'+convert(char(10),@varKSStorage)+'	'+convert(char(30),@varKSRefField)+@varKSINFO
			END
			
			IF @varKSStorage NOT IN ('SUMMA', 'DATE', 'STRING', 'DICTION', 'DICTION_APP', 'DICTION_REF',
					'ACCOUNT', 'DEPARTMENTS', 'SUBDIV',
					'INVENTORY', 'NOMENCLATURE', 'EMPL', 'KL_KBK', 'KOSGU', 'G_PROV',
					'FIN_SOURCE', 'PERSON_ECARDS', 'OSNOV')
			BEGIN
				SET @varKSCur_Str=''
				Print '***Свойство STORAGE ошибочно или отсутствует! Объект:'+@varKSCurCODE

			END 
			
			IF @varKSCur_Str is null
				SET @varKSCur_Str=''
			IF @varKSCur_Str<>''
			BEGIN
				SET  @varKSSel_Str=@varKSSel_Str+',
	'+@varKSCur_Str
			END
		END
		FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE
	END		
	
	CLOSE SEL_CURSOR
	DEALLOCATE SEL_CURSOR
	IF RIGHT(@varKSSel_Str,1)=','
		SET @varKSSel_Str=LEFT(@varKSSel_Str,LEN(@varKSSel_Str)-1)
	SET  @varKSSel_Str=@varKSSel_Str+'
	FROM dbo.OUT_TABLE_ROW OTR
	WHERE OTR.OBJECT = '+LTRIM(STR(@varKSnLink))
	
	IF EXISTS(SELECT * From sysobjects Where name=@varKScCode)
		SET @varKSSel_Str='ALTER ' + @varKSSel_Str
	ELSE
		SET @varKSSel_Str='CREATE ' + @varKSSel_Str
	
	EXECUTE (@varKSSel_Str)

print @varKSSel_Str

	DECLARE @varKSscriptstr varchar(7000)
	SET @varKSscriptstr = 'EXECUTE BK_FORM_VIEW_DOCUMENT_TABLE '''+@varKScCode+''''
	EXEC U_UPDATE_SCRIPT_PROPERTY @varKScCode, @varKSscriptstr

	UPDATE S_DBObjects SET Rights = 0x11 WHERE Object=@varKSnLink AND DBObject=@varKScCode
	IF @@ROWCOUNT = 0
		INSERT INTO S_DBObjects(Object, DBObject, Rights)
			VALUES (@varKSnLink, @varKScCode, 0x11)

GO

GRANT EXECUTE ON dbo.[BK_FORM_VIEW_DOCUMENT_TABLE] TO PUBLIC

GO


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


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





CREATE     
PROCEDURE dbo.X_SAVE_DET_RETURN
	@varKSpLINK		int	OUTPUT,
	@varKSpNUMBER		char(25) = null,
	@varKSpDATE		datetime = null,
	@varKSpDATE_PROV	datetime = null,
	@varKSpSumma		numeric(19,2) = 0,
	@varKSpComment		varchar(254) = null,
	@varKSpDEP_LINK       INT = null,
	@varKSpACC_LINK       INT = null,
	@varKSpCARD_LINK       INT = null,
	@iVid int = 1
	



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

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	--Проверка рабочего периода
	IF @varKSpDATE_PROV is not null and not exists(Select * from admin_info Where @varKSpDATE_PROV BETWEEN BEGINDATE AND ENDDATE)
	BEGIN
		ROLLBACK
		RETURN 15
	END


	SELECT @varKSLinkObj = LINK FROM S_OBJECTS WHERE CODE = 'BB_DET_RETURN'

	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV @varKSpLINK OUTPUT, @varKSpNUMBER, @varKSpDATE, 
											  @varKSLinkObj, @varKSpDATE_PROV, @varKSpSumma, @varKSpComment,0,@varKSpDEP_LINK,@varKSpACC_LINK

	SELECT @varKS_param = LINK FROM S_OBJECTS WHERE CODE = 'BB_DET_RETURN_CARD_LINK'
	--карта
	EXECUTE @varKSERROR = dbo.BK_UPDATE_G_PROV_ECARD @varKSpLINK, @varKS_param, @varKSpCARD_LINK
	IF @varKSERROR <> 0
		RETURN @varKSERROR

	SELECT @varKS_param = LINK FROM S_OBJECTS WHERE CODE = 'BB_DET_RETURN_VID'
	--Вид операции
	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV_VALUE @varKSpLINK, @varKS_param, @iVid
	IF @varKSERROR <> 0
		RETURN @varKSERROR

	
	--Событие системного журнала
	SET @varKSEventText = 'Расшифровка сумм неиспользованных средств' + ' №' + RTRIM(@varKSpNUMBER) + ' от ' + convert(varchar, @varKSpDATE, 104)
	EXECUTE WF_GENERATEEVENT 'Сохранение документа', @varKSEventText, @varKSLinkObj, 'G_PROV', @varKSpLINK

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO

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

GO


CREATE     PROCEDURE dbo.MK_FORM_T9A
	@varKSnMode INT
AS BEGIN
	DECLARE @varKSnLink INT

	SELECT TOP 1 @varKSnLink = 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='SQL_REP_T_9A_MAIN_PARAM')


	DECLARE 
		@varKSORGNAME VARCHAR(254), @varKSOKPO VARCHAR(40), 
		@varKSDOC_NUM VARCHAR(30), @varKSDOC_DATE DATETIME
	SELECT 
		@varKSORGNAME = D.FULL_NAME, @varKSOKPO = D.OKPO,
		@varKSDOC_NUM = O.NUMBER, @varKSDOC_DATE = O.DATE 
	FROM ORDERS O INNER JOIN DICTIONARY_DEPARTMENT D ON O.DEP_LINK = D.LINK
	WHERE O.LINK = @varKSnLink
	
	DECLARE @varKSCHIEF VARCHAR(254), @varKSCHIEF_POST VARCHAR(254)
	SET @varKSCHIEF = 
		(SELECT TOP 1 FACE_NAME 
		FROM DICTIONARY_OTV_FACE DOTF, USER_DEP UI
		WHERE DOTF.NAME='РУКОВОДИТЕЛЬ' AND DOTF.DEP_LINK = UI.DEP_LINK)

	SET @varKSCHIEF_POST = 
		(SELECT KEP.POST_NAME
		FROM DICTIONARY_OTV_FACE DOTF, USER_DEP UI, ku_empl_placing KEP
		WHERE 
			DOTF.NAME='РУКОВОДИТЕЛЬ' AND 
			DOTF.DEP_LINK = UI.DEP_LINK 
			AND KEP.LINK = DOTF.FACE_LINK
		)

	IF @varKSnMode = 1 BEGIN

		CREATE TABLE #TMP(
			ORGNAME VARCHAR(254), OKPO VARCHAR(40),
			DOC_NUM VARCHAR(15), DOC_DATE DATETIME,
			iii INT, 
			FIO1 VARCHAR(254), FIO2 VARCHAR(254), FIO3 VARCHAR(254),
			TN1 VARCHAR(15), TN2 VARCHAR(15), TN3 VARCHAR(15),
			SUBDIV1 VARCHAR(254), SUBDIV2 VARCHAR(254), SUBDIV3 VARCHAR(254),
			POST1 VARCHAR(254), POST2 VARCHAR(254), POST3 VARCHAR(254), 
			PLACE1 VARCHAR(254), PLACE2 VARCHAR(254), PLACE3 VARCHAR(254), 
			ORG1 VARCHAR(254), ORG2 VARCHAR(254), ORG3 VARCHAR(254), 
			DATE_BEG1 DATETIME, DATE_BEG2 DATETIME,  DATE_BEG3 DATETIME, 
			DATE_END1 DATETIME, DATE_END2 DATETIME, DATE_END3 DATETIME, 
			DURATION1 INT, DURATION2 INT, DURATION3 INT, 
			TARGET1 VARCHAR(254), TARGET2 VARCHAR(254), TARGET3 VARCHAR(254), 
			PAYER1 VARCHAR(254), PAYER2 VARCHAR(254), PAYER3 VARCHAR(254), 
			REASON1 VARCHAR(254), REASON2 VARCHAR(254), REASON3 VARCHAR(254)
		)

		
		DECLARE @varKSI INT, @varKSJ INT
		SELECT @varKSI = 1, @varKSJ = 1
	
		DECLARE 
			@varKSFIO1 VARCHAR(254), @varKSFIO2 VARCHAR(254), @varKSFIO3 VARCHAR(254),
			@varKSTN1 VARCHAR(15), @varKSTN2 VARCHAR(15), @varKSTN3 VARCHAR(15),
			@varKSSUBDIV1 VARCHAR(254), @varKSSUBDIV2 VARCHAR(254), @varKSSUBDIV3 VARCHAR(254),
			@varKSPOST1 VARCHAR(254), @varKSPOST2 VARCHAR(254), @varKSPOST3 VARCHAR(254), 
			@varKSPLACE1 VARCHAR(254), @varKSPLACE2 VARCHAR(254), @varKSPLACE3 VARCHAR(254), 
			@varKSORG1 VARCHAR(254), @varKSORG2 VARCHAR(254), @varKSORG3 VARCHAR(254), 
			@varKSDATE_BEG1 DATETIME, @varKSDATE_BEG2 DATETIME,  @varKSDATE_BEG3 DATETIME, 
			@varKSDATE_END1 DATETIME, @varKSDATE_END2 DATETIME, @varKSDATE_END3 DATETIME, 
			@varKSDURATION1 INT, @varKSDURATION2 INT, @varKSDURATION3 INT, 
			@varKSTARGET1 VARCHAR(254), @varKSTARGET2 VARCHAR(254), @varKSTARGET3 VARCHAR(254), 
			@varKSPAYER1 VARCHAR(254), @varKSPAYER2 VARCHAR(254), @varKSPAYER3 VARCHAR(254), 
			@varKSREASON1 VARCHAR(254), @varKSREASON2 VARCHAR(254), @varKSREASON3 VARCHAR(254),
	
			@varKSFIO VARCHAR(254), @varKSTAB_NUM VARCHAR(15), 
			@varKSSUBDIV  VARCHAR(254), @varKSPOST VARCHAR(254), 
			@varKSPLACE VARCHAR(254), 
			@varKSORG VARCHAR(254), 
			@varKSDATE_BEGIN DATETIME, @varKSDATE_END DATETIME, 
			@varKSDURATION INT,
			@varKSTARGET VARCHAR(254), @varKSPAYER VARCHAR(254), @varKSREASON VARCHAR(254),
			
			@varKSHAS_DATA BIT

			DECLARE #TMP_CUR CURSOR FOR
			SELECT 
				FIO, TAB_NUM, SUBDIV, POST, PLACE, ORG, DATE_BEGIN, 
				DATE_END, DATEDIFF(D, DATE_BEGIN, DATE_END) + 1 AS DURATION,
				TARGET , PAYER, REASON
			FROM TRAVEL WHERE ORDER_LINK = @varKSnLink

		SET @varKSHAS_DATA = 0
		OPEN #TMP_CUR 
		FETCH #TMP_CUR INTO
			@varKSFIO, @varKSTAB_NUM, @varKSSUBDIV, @varKSPOST, @varKSPLACE, @varKSORG, 
			@varKSDATE_BEGIN, @varKSDATE_END, @varKSDURATION,
			@varKSTARGET, @varKSPAYER, @varKSREASON
	
	
		WHILE @@FETCH_STATUS = 0 BEGIN
			SET @varKSHAS_DATA = 1
			IF @varKSJ = 1 BEGIN
				SELECT 	
					@varKSFIO1 = '', @varKSFIO2 = '', @varKSFIO3 = '',
					@varKSTN1 = '', @varKSTN2 = '', @varKSTN3 = '',
					@varKSSUBDIV1  = '', @varKSSUBDIV2 = '', @varKSSUBDIV3 = '',
					@varKSPOST1 = '', @varKSPOST2 = '', @varKSPOST3 = '', 
					@varKSPLACE1 = '', @varKSPLACE2 = '', @varKSPLACE3 = '', 
					@varKSORG1 = '', @varKSORG2 = '', @varKSORG3 = '', 
					@varKSDATE_BEG1 = NULL, @varKSDATE_BEG2 = NULL,  @varKSDATE_BEG3 = NULL, 
					@varKSDATE_END1 = NULL, @varKSDATE_END2 = NULL, @varKSDATE_END3 = NULL, 
					@varKSDURATION1 = 0, @varKSDURATION2 = 0, @varKSDURATION3 = 0, 
					@varKSTARGET1 = '', @varKSTARGET2 = '', @varKSTARGET3 = '', 
					@varKSPAYER1 = '', @varKSPAYER2 = '', @varKSPAYER3 = '', 
					@varKSREASON1 = '', @varKSREASON2 = '', @varKSREASON3 = ''
			END
	
	
			IF @varKSJ = 1 BEGIN
				SELECT 
				@varKSFIO1 = @varKSFIO, 
				@varKSTN1 = @varKSTAB_NUM, 
				@varKSSUBDIV1 = @varKSSUBDIV, 
				@varKSPOST1 = @varKSPOST, 
				@varKSPLACE1 = @varKSPLACE, 
				@varKSORG1 = @varKSORG, 
				@varKSDATE_BEG1 = @varKSDATE_BEGIN, 
				@varKSDATE_END1 = @varKSDATE_END, 
				@varKSDURATION1 = @varKSDURATION,
				@varKSTARGET1 = @varKSTARGET, 
				@varKSPAYER1 = @varKSPAYER, 
				@varKSREASON1 = @varKSREASON
			END
	
			IF @varKSJ = 2 BEGIN
				SELECT 
				@varKSFIO2 = @varKSFIO, 
				@varKSTN2 = @varKSTAB_NUM, 
				@varKSSUBDIV2 = @varKSSUBDIV, 
				@varKSPOST2 = @varKSPOST, 
				@varKSPLACE2 = @varKSPLACE, 
				@varKSORG2 = @varKSORG, 
				@varKSDATE_BEG2 = @varKSDATE_BEGIN, 
				@varKSDATE_END2 = @varKSDATE_END, 
				@varKSDURATION2 = @varKSDURATION,
				@varKSTARGET2 = @varKSTARGET, 
				@varKSPAYER2 = @varKSPAYER, 
				@varKSREASON2 = @varKSREASON
			END
	
			IF @varKSJ = 3 BEGIN
				SELECT 
				@varKSFIO3 = @varKSFIO, 
				@varKSTN3 = @varKSTAB_NUM, 
				@varKSSUBDIV3 = @varKSSUBDIV, 
				@varKSPOST3 = @varKSPOST, 
				@varKSPLACE3 = @varKSPLACE, 
				@varKSORG3 = @varKSORG, 
				@varKSDATE_BEG3 = @varKSDATE_BEGIN, 
				@varKSDATE_END3 = @varKSDATE_END, 
				@varKSDURATION3 = @varKSDURATION,
				@varKSTARGET3 = @varKSTARGET, 
				@varKSPAYER3 = @varKSPAYER, 
				@varKSREASON3 = @varKSREASON
			END
	
			IF @varKSJ = 3 BEGIN
				SET @varKSJ = 1
				INSERT INTO #TMP
				SELECT 
					@varKSORGNAME, @varKSOKPO,
					@varKSDOC_NUM, @varKSDOC_DATE,
					@varKSI, 
					@varKSFIO1, @varKSFIO2, @varKSFIO3 ,
					@varKSTN1, @varKSTN2, @varKSTN3,
					@varKSSUBDIV1, @varKSSUBDIV2, @varKSSUBDIV3 ,
					@varKSPOST1, @varKSPOST2, @varKSPOST3 , 
					@varKSPLACE1, @varKSPLACE2, @varKSPLACE3 , 
					@varKSORG1, @varKSORG2, @varKSORG3 , 
					@varKSDATE_BEG1, @varKSDATE_BEG2, @varKSDATE_BEG3, 
					@varKSDATE_END1, @varKSDATE_END2, @varKSDATE_END3, 
					@varKSDURATION1, @varKSDURATION2, @varKSDURATION3, 
					@varKSTARGET1, @varKSTARGET2, @varKSTARGET3, 
					@varKSPAYER1, @varKSPAYER2, @varKSPAYER3, 
					@varKSREASON1, @varKSREASON2, @varKSREASON3 
				SET @varKSI = @varKSI + 1
			END
			ELSE BEGIN
				SET @varKSJ = @varKSJ + 1
			END		
	
	
			FETCH #TMP_CUR INTO
				@varKSFIO, @varKSTAB_NUM, @varKSSUBDIV, @varKSPOST, @varKSPLACE, @varKSORG, 
				@varKSDATE_BEGIN, @varKSDATE_END, @varKSDURATION,
				@varKSTARGET, @varKSPAYER, @varKSREASON
	
		END
	
		IF @varKSHAS_DATA = 1 AND @varKSJ <> 1 BEGIN
			INSERT INTO #TMP
			SELECT 
				@varKSORGNAME, @varKSOKPO,
				@varKSDOC_NUM, @varKSDOC_DATE,
				@varKSI, 
				@varKSFIO1, @varKSFIO2, @varKSFIO3 ,
				@varKSTN1, @varKSTN2, @varKSTN3,
				@varKSSUBDIV1, @varKSSUBDIV2, @varKSSUBDIV3 ,
				@varKSPOST1, @varKSPOST2, @varKSPOST3 , 
				@varKSPLACE1, @varKSPLACE2, @varKSPLACE3 , 
				@varKSORG1, @varKSORG2, @varKSORG3 , 
				@varKSDATE_BEG1, @varKSDATE_BEG2, @varKSDATE_BEG3, 
				@varKSDATE_END1, @varKSDATE_END2, @varKSDATE_END3, 
				@varKSDURATION1, @varKSDURATION2, @varKSDURATION3, 
				@varKSTARGET1, @varKSTARGET2, @varKSTARGET3, 
				@varKSPAYER1, @varKSPAYER2, @varKSPAYER3, 
				@varKSREASON1, @varKSREASON2, @varKSREASON3 
		END
	
		CLOSE #TMP_CUR 
		DEALLOCATE #TMP_CUR 
	
		SELECT *, @varKSCHIEF AS CHIEF, @varKSCHIEF_POST AS CHIEF_POST FROM #TMP
		EXEC KIR_GET_OTV_FACES

	END

	IF @varKSnMode = 2  OR @varKSnMode = 4 BEGIN
		SELECT 
			@varKSORGNAME AS ORGNAME, @varKSOKPO AS OKPO,
			@varKSDOC_NUM AS DOC_NUM, @varKSDOC_DATE AS DOC_DATE,
			@varKSCHIEF AS CHIEF, @varKSCHIEF_POST AS CHIEF_POST,
			FIO, TAB_NUM AS TN, SUBDIV, POST, PLACE, ORG, DATE_BEGIN, 
			DATE_END, DATEDIFF(D, DATE_BEGIN, DATE_END) + 1 AS DURATION,
			TARGET,TARGET_DOP, PAYER, REASON,
			UDOST_DATE AS UD_DATE, UDOST_NUM AS UD_NUM,
			(SELECT TOP 1 P.DOC_NUM FROM EMPL INNER JOIN PERSON P ON EMPL.PERS_LINK = P.LINK AND EMPL.LINK = T.EMPL_LINK) AS PASP_NUM
		FROM TRAVEL T WHERE ORDER_LINK = @varKSnLink
		
		
	END

	IF @varKSnMode = 3 BEGIN
		DECLARE @DEP_LINK INT
		SET @DEP_LINK = (SELECT DEP_LINK FROM USER_DEP)
		DECLARE @DEP_ADR VARCHAR(1000)
		SET @DEP_ADR = DBO.GetAddressByDepLink(@DEP_LINK,1)
		DECLARE @DEP_BANK VARCHAR(1000)
		SET @DEP_BANK = (
				SELECT CASE WHEN DA.TYPE = 1 THEN 'р/с ' + RTRIM(DA.CODE) + ' в ' + RTRIM(DA.BANK_NAME) + ', корсчет ' + RTRIM(B.KS) + ' БИК ' + RTRIM(B.BIK) ELSE DA.ANAME END
				FROM DICTIONARY_ACCOUNTS DA LEFT JOIN BANKS B ON DA.REF_LINK_B = B.LINK
				WHERE DA.LINK = (SELECT MAIN_LINK FROM DEPARTMENTS WHERE LINK = @DEP_LINK)
				)
		DECLARE @INN VARCHAR(20), @KPP VARCHAR(20)
		SELECT @INN = INN, @KPP = KPP FROM DEPARTMENTS WHERE LINK = @DEP_LINK
		SELECT	[DATE_BEGIN] = T.DATE,
			[POST] = T.POST,
			[FIO] = T.FIO,
			[OKPO] = @varKSOKPO,
			[DEP_ADR] = @DEP_ADR,
			[NUM_DOC] = 'серия ' + LEFT(P.DOC_NUM,5) + ' № ' + RIGHT(P.DOC_NUM,6),
			[WHOM_DOC] = P.DOC_WHOM,
			[DATE_DOC] = P.DOC_DATE,
			[DEP_BANK] = @DEP_BANK,
			[INN] = @INN,
			[KPP] =@KPP
		FROM	TRAVEL T LEFT JOIN EMPL E
			ON T.EMPL_LINK = E.LINK LEFT JOIN PERSON P
			ON E.PERS_LINK = P.LINK
		WHERE ORDER_LINK = @varKSnLink
	END

END




GO


GRANT EXECUTE ON dbo.[MK_FORM_T9A] TO PUBLIC

GO


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

GO

CREATE  PROCEDURE DBO.SA_SET_STATIC_NASTR @CODE VARCHAR(20)
AS
---ЗАРПЛАТА-КС: ОБНОВЛЕНИЕ СТАВОК
BEGIN

	DECLARE @TITLE VARCHAR(254)
	SET @TITLE = 'Установлены статические настройки Зарплата-КС'

	DECLARE	@TD_LINK INT

	DELETE FROM DBO.SAL_WORNINGS WHERE TASK = 'SALARY' AND SID = SUSER_SID()

	IF @CODE = '2012' BEGIN

		SET @TITLE = @TITLE + ' на 01 ЯНВАРЯ 2012г.'

		--Мин. размер пособия по уходу за 1 ребенком
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT1', 0, '2326.00'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Мин. размер пособия по уходу за 1 ребенком = 2326.00', '', 'SALARY'


		--Мин. размер пособия по уходу за 2 и более дет.          
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT2', 0, '4651.99'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Мин. размер пособия по уходу за 2 и более дет. = 4651.99', '', 'SALARY'


		--Макс. размер пособия по уходу за 1 ребенком                                                                                                              
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT3', 0, '14625.32'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Макс. размер пособия по уходу за 1 ребенком = 9303.99', '', 'SALARY'


		--Макс.  размер пособия по уходу за 2 и более дет.                                                                                                                                                                 
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT4', 0, '14625.32'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Макс.  размер пособия по уходу за 2 и более дет. = 9303.99', '', 'SALARY'


		--Предельный размер пособия по нетрудоспособности                                                                                                                                                                
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT1', 0, '42666.66'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Предельный размер пособия по нетрудоспособности = 42666.66', '', 'SALARY'

		--Максимальный размер пособия по беременности и родам                                                                                                                                                             
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT6', 0, '42666.66'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Максимальный размер пособия по беременности и родам = 42666.66', '', 'SALARY'
		
		--Предельный размер пособия по нетрудоспособности в минувшем году                                                                                                                                                        
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT7', 0, '38583.33'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Предельный размер пособия по нетрудоспособности в минувшем году = 38583.33', '', 'SALARY'

		--Максимальный размер пособия по беременности и родам в минувшем году                                                                                                                                                      
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT8', 0, '38583.33'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Максимальный размер пособия по беременности и родам в минувшем году = 38583.33', '', 'SALARY'		

		-- УДАЛЕНИЕ ВСЕХ ПРАЗДНИКОВ 
		DELETE	FROM HOLIDAYS

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРАЗДНИЧНЫХ ДНЕЙ
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL)
			SELECT	'1 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 1, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'2 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 2, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'3 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 3, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'4 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 4, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'5 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 5, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'7 ЯНВАРЯ (РОЖДЕСТВО ХРИСТОВО)', 7, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'23 ФЕВРАЛЯ (ДЕНЬ ЗАЩИТНИКА ОТЕЧЕСТВА)', 23, 2, @TD_LINK, 1
			UNION ALL
			SELECT	'8 МАРТА (МЕЖДУНАРОДНЫЙ ЖЕНСКИЙ ДЕНЬ)', 8, 3, @TD_LINK, 1
			UNION ALL
			SELECT	'1 МАЯ (ПРАЗДНИК ВЕСНЫ И ТРУДА)', 1, 5, @TD_LINK, 1
			UNION ALL
			SELECT	'9 МАЯ (ДЕНЬ ПОБЕДЫ)', 9, 5, @TD_LINK, 1
			UNION ALL
			SELECT	'12 ИЮНЯ (ДЕНЬ РОССИИ)', 12, 6, @TD_LINK, 1
			UNION ALL
			SELECT	'4 НОЯБРЯ (ДЕНЬ НАРОДНОГО ЕДИНСТВА)', 4, 11, @TD_LINK, 1

		SET @TITLE = 'Установлены праздничные дни'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 1 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРЕДПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB = 'П')
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРЕДПРАЗДНИЧНЫХ ДНЕЙ ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'22 ФЕВРАЛЯ', 22, 2, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'7 МАРТА', 7, 3, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'28 АПРЕЛЯ (предпраздничный день за 30 апреля)', 28, 4, @TD_LINK, 2, 30, 4
			UNION ALL
			SELECT	'9 ИЮНЯ (предпраздничный день за 11 июня)', 9, 6, @TD_LINK, 2, 11, 6
			UNION ALL
			SELECT	'29 ДЕКАБРЯ (предпраздничный день за 31 декабря)', 29, 12, @TD_LINK, 2, 31, 12
			UNION ALL
			SELECT	'12 МАЯ (предпраздничный день за 8 мая)', 12, 5, @TD_LINK, 2, 8, 5

		SET @TITLE = 'Установлены предпраздничные дни'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 2 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ ДОПОЛНИТЕЛЬНЫХ ДНЕЙ ОТДЫХА ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'6 ЯНВАРЯ (перенос выходного с 1 января)', 6, 1, @TD_LINK, 3, 1, 1
			UNION ALL
			SELECT	'9 ЯНВАРЯ (перенос выходного с 7 января)', 9, 1, @TD_LINK, 3, 7, 1
			UNION ALL
			SELECT	'9 МАРТА (перенос выходного с 11 марта)', 9, 3, @TD_LINK, 3, 11, 3
			UNION ALL
			SELECT	'30 АПРЕЛЯ (перенос выходного с 28 апреля)', 30, 4, @TD_LINK, 3, 28, 4			
			UNION ALL
			SELECT	'7 МАЯ (перенос выходного с 5 мая)', 7, 5, @TD_LINK, 3, 5, 5			
			UNION ALL
			SELECT	'8 МАЯ (перенос выходного с 12 мая)', 8, 5, @TD_LINK, 3, 12, 5			
			UNION ALL			
			SELECT	'11 ИЮНЯ (перенос выходного с 9 июня)', 11, 6, @TD_LINK, 3, 9, 6									
			UNION ALL
			SELECT	'5 НОЯБРЯ (перенос выходного с 4 ноября)', 5, 11, @TD_LINK, 3, 4, 11
			UNION ALL
			SELECT	'31 ДЕКАБРЯ (перенос выходного с 29 декабря)', 31, 12, @TD_LINK, 3, 29, 12			

		SET @TITLE = 'Установлены дополнительные дни отдыха (перенос выходных)'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 3 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА РАБОЧИЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB IN ('Я','Ф'))
		IF COALESCE(@TD_LINK,0) > 0
		BEGIN
			-- ДОБАВЛЕНИЕ ПЕРЕНЕСЁННЫХ РАБОЧИХ ДНЕЙ
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'11 МАРТА (рабочий день за 9 марта)', 11, 3, @TD_LINK, 3, 9, 3

			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'5 МАЯ (рабочий день за 7 мая)', 5, 5, @TD_LINK, 3, 7, 5

		END
		
		SET @TITLE = 'Установлены переносы рабочих дней'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '11 МАРТА (рабочий день за 9 марта)', '', 'SALARY'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '28 АПРЕЛЯ (рабочий день за 30 апреля)', '', 'SALARY'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, '5 МАЯ (рабочий день за 7 мая)', '', 'SALARY'

	END --IF @CODE = '2012' BEGIN	

	IF @CODE = '2013' BEGIN

		SET @TITLE = @TITLE + ' на 01 ЯНВАРЯ 2013г.'

		--Мин. размер пособия по уходу за 1 ребенком
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT1', 0, '2453.93'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Мин. размер пособия по уходу за 1 ребенком = 2453.93', '', 'SALARY'


		--Мин. размер пособия по уходу за 2 и более дет.          
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT2', 0, '4907.85'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Мин. размер пособия по уходу за 2 и более дет. = 4907.85', '', 'SALARY'


		--Макс. размер пособия по уходу за 1 ребенком                                                                                                              
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT3', 0, '15429.71'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Макс. размер пособия по уходу за 1 ребенком = 15429.71', '', 'SALARY'


		--Макс.  размер пособия по уходу за 2 и более дет.                                                                                                                                                                 
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT4', 0, '15429.71'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Макс.  размер пособия по уходу за 2 и более дет. = 15429.71', '', 'SALARY'


		----Предельный размер пособия по нетрудоспособности                                                                                                                                                                
		--EXEC dbo.X_SET_OPTION 'ARCHE_OPT1', 0, '42666.66'

		--INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		--SELECT @TITLE, 'Предельный размер пособия по нетрудоспособности = 42666.66', '', 'SALARY'

		----Максимальный размер пособия по беременности и родам                                                                                                                                                             
		--EXEC dbo.X_SET_OPTION 'ARCHE_OPT6', 0, '42666.66'

		--INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		--SELECT @TITLE, 'Максимальный размер пособия по беременности и родам = 42666.66', '', 'SALARY'
		
		----Предельный размер пособия по нетрудоспособности в минувшем году                                                                                                                                                        
		--EXEC dbo.X_SET_OPTION 'ARCHE_OPT7', 0, '38583.33'

		--INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		--SELECT @TITLE, 'Предельный размер пособия по нетрудоспособности в минувшем году = 38583.33', '', 'SALARY'

		----Максимальный размер пособия по беременности и родам в минувшем году                                                                                                                                                      
		--EXEC dbo.X_SET_OPTION 'ARCHE_OPT8', 0, '38583.33'

		--INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		--SELECT @TITLE, 'Максимальный размер пособия по беременности и родам в минувшем году = 38583.33', '', 'SALARY'		

		-- УДАЛЕНИЕ ВСЕХ ПРАЗДНИКОВ 
		DELETE	FROM HOLIDAYS

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРАЗДНИЧНЫХ ДНЕЙ
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL)
			SELECT	'1 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 1, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'2 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 2, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'3 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 3, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'4 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 4, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'5 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 5, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'6 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 6, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'7 ЯНВАРЯ (РОЖДЕСТВО ХРИСТОВО)', 7, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'8 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 8, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'23 ФЕВРАЛЯ (ДЕНЬ ЗАЩИТНИКА ОТЕЧЕСТВА)', 23, 2, @TD_LINK, 1
			UNION ALL
			SELECT	'8 МАРТА (МЕЖДУНАРОДНЫЙ ЖЕНСКИЙ ДЕНЬ)', 8, 3, @TD_LINK, 1
			UNION ALL
			SELECT	'1 МАЯ (ПРАЗДНИК ВЕСНЫ И ТРУДА)', 1, 5, @TD_LINK, 1
			UNION ALL
			SELECT	'9 МАЯ (ДЕНЬ ПОБЕДЫ)', 9, 5, @TD_LINK, 1
			UNION ALL
			SELECT	'12 ИЮНЯ (ДЕНЬ РОССИИ)', 12, 6, @TD_LINK, 1
			UNION ALL
			SELECT	'4 НОЯБРЯ (ДЕНЬ НАРОДНОГО ЕДИНСТВА)', 4, 11, @TD_LINK, 1

		SET @TITLE = 'Установлены праздничные дни'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 1 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРЕДПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB = 'П')
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРЕДПРАЗДНИЧНЫХ ДНЕЙ ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'22 ФЕВРАЛЯ', 22, 2, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'7 МАРТА', 7, 3, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'30 АПРЕЛЯ', 30, 4, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'8 МАЯ', 8, 5, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'11 ИЮНЯ', 11, 6, @TD_LINK, 2, null, null
			UNION ALL
			SELECT	'31 ДЕКАБРЯ', 31, 12, @TD_LINK, 2, null, null
		SET @TITLE = 'Установлены предпраздничные дни'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 2 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ ДОПОЛНИТЕЛЬНЫХ ДНЕЙ ОТДЫХА ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'2 МАЯ (перенос выходного с 5 января)', 2, 5, @TD_LINK, 3, 5, 1
			UNION ALL
			SELECT	'3 МАЯ (перенос выходного с 6 января)', 3, 5, @TD_LINK, 3, 6, 1			
			UNION ALL
			SELECT	'10 МАЯ (перенос выходного с 25 февраля)', 10, 5, @TD_LINK, 3, 25, 2			

		SET @TITLE = 'Установлены дополнительные дни отдыха (перенос выходных)'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 3 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА РАБОЧИЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB IN ('Я','Ф'))
		IF COALESCE(@TD_LINK,0) > 0
		BEGIN
			-- ДОБАВЛЕНИЕ ПЕРЕНЕСЁННЫХ РАБОЧИХ ДНЕЙ
			/*	INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
				SELECT	'11 МАРТА (рабочий день за 9 марта)', 11, 3, @TD_LINK, 3, 9, 3

				INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
				SELECT	'5 МАЯ (рабочий день за 7 мая)', 5, 5, @TD_LINK, 3, 7, 5
			*/
			/*перенесенных рабочих дней за 2013 год нет */
		
		
			SET @TITLE = 'Установлены переносы рабочих дней'

			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			SELECT @TITLE, 'перенесенных рабочих дней за 2013 год нет', '', 'SALARY'
		end
	END --IF @CODE = '2013' BEGIN	

	IF @CODE = '2014' BEGIN

		SET @TITLE = @TITLE + ' на 01 ЯНВАРЯ 2014г.'

		--Мин. размер пособия по уходу за 1 ребенком
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT1', 0, '2576.63'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Мин. размер пособия по уходу за 1 ребенком = 2576.63', '', 'SALARY'


		--Мин. размер пособия по уходу за 2 и более дет.          
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT2', 0, '5153.24'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Мин. размер пособия по уходу за 2 и более дет. = 5153.24', '', 'SALARY'


		--Макс. размер пособия по уходу за 1 ребенком                                                                                                              
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT3', 0, '17990.11'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Макс. размер пособия по уходу за 1 ребенком = 17990.11', '', 'SALARY'

		--Макс.  размер пособия по уходу за 2 и более дет.                                                                                                                                                                 
		EXEC dbo.X_SET_OPTION 'VAC_CHILD_OPT4', 0, '17990.11'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Макс.  размер пособия по уходу за 2 и более дет. = 17990.11', '', 'SALARY'


		----Предельный размер пособия по нетрудоспособности                                                                                                                                                                
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT1', 0, '52000.00'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Предельный размер пособия по нетрудоспособности = 52000.00', '', 'SALARY'

		--Максимальный размер пособия по беременности и родам                                                                                                                                                             
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT6', 0, '52000.00'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Максимальный размер пособия по беременности и родам = 52000.00', '', 'SALARY'
		
		--Предельный размер пособия по нетрудоспособности в минувшем году                                                                                                                                                        
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT7', 0, '47333.33'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Предельный размер пособия по нетрудоспособности в минувшем году = 47333.33', '', 'SALARY'

		--Максимальный размер пособия по беременности и родам в минувшем году                                                                                                                                                      
		EXEC dbo.X_SET_OPTION 'ARCHE_OPT8', 0, '47333.33'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, 'Максимальный размер пособия по беременности и родам в минувшем году = 47333.33', '', 'SALARY'		

		-- УДАЛЕНИЕ ВСЕХ ПРАЗДНИКОВ 
		DELETE	FROM HOLIDAYS

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРАЗДНИЧНЫХ ДНЕЙ
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL)
			SELECT	'1 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 1, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'2 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 2, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'3 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 3, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'4 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 4, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'5 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 5, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'6 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 6, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'7 ЯНВАРЯ (РОЖДЕСТВО ХРИСТОВО)', 7, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'8 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 8, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'23 ФЕВРАЛЯ (ДЕНЬ ЗАЩИТНИКА ОТЕЧЕСТВА)', 23, 2, @TD_LINK, 1
			UNION ALL
			SELECT	'8 МАРТА (МЕЖДУНАРОДНЫЙ ЖЕНСКИЙ ДЕНЬ)', 8, 3, @TD_LINK, 1
			UNION ALL
			SELECT	'1 МАЯ (ПРАЗДНИК ВЕСНЫ И ТРУДА)', 1, 5, @TD_LINK, 1
			UNION ALL
			SELECT	'9 МАЯ (ДЕНЬ ПОБЕДЫ)', 9, 5, @TD_LINK, 1
			UNION ALL
			SELECT	'12 ИЮНЯ (ДЕНЬ РОССИИ)', 12, 6, @TD_LINK, 1
			UNION ALL
			SELECT	'4 НОЯБРЯ (ДЕНЬ НАРОДНОГО ЕДИНСТВА)', 4, 11, @TD_LINK, 1

		SET @TITLE = 'Установлены праздничные дни'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 1 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРЕДПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB = 'П')
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРЕДПРАЗДНИЧНЫХ ДНЕЙ ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'7 МАРТА', 7, 3, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'30 АПРЕЛЯ', 30, 4, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'8 МАЯ', 8, 5, @TD_LINK, 2, NULL, NULL
			UNION ALL
			SELECT	'11 ИЮНЯ', 11, 6, @TD_LINK, 2, null, null
			UNION ALL
			SELECT	'31 ДЕКАБРЯ', 31, 12, @TD_LINK, 2, null, NULL
			UNION ALL
			SELECT	'24 ФЕВРАЛЯ', 24, 2, @TD_LINK, 2,null, NULL

		SET @TITLE = 'Установлены предпраздничные дни'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 2 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ ДОПОЛНИТЕЛЬНЫХ ДНЕЙ ОТДЫХА ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
			SELECT	'10 МАРТА (перенос выходного с 8 марта)', 10, 3, @TD_LINK, 3, 8, 3
			UNION ALL
			SELECT	'2 МАЯ (перенос выходного с 4 января)', 2, 5, @TD_LINK, 3, 4, 1
			UNION ALL
			SELECT	'13 ИЮНЯ (перенос выходного с 5 января)', 13, 6, @TD_LINK, 3, 5, 1
			UNION ALL
			SELECT	'3 НОЯБРЯ (перенос выходного с 24 февраля)', 3, 11, @TD_LINK, 3, 24, 2			

		SET @TITLE = 'Установлены дополнительные дни отдыха (перенос выходных)'

		INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
		SELECT @TITLE, NAME, '', 'SALARY' FROM dbo.HOLIDAYS WHERE TYPE_HOL = 3 ORDER BY [MONTH], [DAY] 

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА РАБОЧИЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB IN ('Я','Ф'))
		IF COALESCE(@TD_LINK,0) > 0
		BEGIN
			-- ДОБАВЛЕНИЕ ПЕРЕНЕСЁННЫХ РАБОЧИХ ДНЕЙ
			/*	INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
				SELECT	'11 МАРТА (рабочий день за 9 марта)', 11, 3, @TD_LINK, 3, 9, 3

				INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1)
				SELECT	'5 МАЯ (рабочий день за 7 мая)', 5, 5, @TD_LINK, 3, 7, 5
			*/
			/*перенесенных рабочих дней за 2014 год нет */
		
		
			SET @TITLE = 'Установлены переносы рабочих дней'

			INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
			SELECT @TITLE, 'перенесенных рабочих дней за 2014 год нет', '', 'SALARY'
		end
	END --IF @CODE = '2014' BEGIN				

END



GO


GRANT EXECUTE ON dbo.[SA_SET_STATIC_NASTR] TO PUBLIC

GO



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

GO


CREATE   PROCEDURE dbo.SD_BASE_SUM_PAY_DIF_PERIODS
---Расчет базовых сумм для расчета отпускных по общей инструкции
 @varKSRefPay 	int,
 @varKSlinkEmpl	 int,
 @varKSdDate1	datetime,
 @varKSdDate2	datetime,	--Конец расчетного периода	 
 @ObjCode	varchar(254) = NULL,
 @varKSdDate3	datetime = NULL, --Начало отпуска 
 @varKSdDate4	datetime = NULL  --Конец расчетного периода
AS  

declare @nFURLOUGH_OPT1  Int	-- Мат. помощь учитывать как премию
Set @nFURLOUGH_OPT1 = [dbo].[sa_get_option_by_code]('FURLOUGH_OPT1')

Set @ObjCode = COALESCE(@ObjCode,'')
Set @varKSdDate3 = COALESCE(@varKSdDate3,'30000101')
Set @varKSdDate4 = COALESCE(@varKSdDate4,'30000101')

declare @FURLOUGH_OPT5  Int
Set @FURLOUGH_OPT5 = [dbo].[sa_get_option_by_code]('FURLOUGH_OPT5')
Set @FURLOUGH_OPT5 = case when @FURLOUGH_OPT5 = 0 then 12 else @FURLOUGH_OPT5 end

DECLARE @DOCUMENTS_RECALC_OPT1 INT --Суммы перерасчёта учитывать в месяце
SET @DOCUMENTS_RECALC_OPT1 = dbo.SA_GET_OPTION_BY_CODE('DOCUMENTS_RECALC_OPT1')
IF ISNULL(@DOCUMENTS_RECALC_OPT1,0) NOT IN (1,2) 
	SET @DOCUMENTS_RECALC_OPT1 = 1

CREATE TABLE #tmpCJ (
	LINK_EMPL INT, 
	LINK_PAYS INT, 
	CODE_PAYS VARCHAR(10),
	NAME_PAYS VARCHAR(60),
	WAY_CALC INT,
	SUMMA NUMERIC(18,2),
	LINK_VKR INT,
	PERIOD_BEGIN DATETIME,
	PERIOD_END DATETIME,
	DATE1 DATETIME, 
	DATE2 DATETIME, 
	Option_CV INT
)


INSERT INTO #tmpCJ 
Select SJ.LINK_EMPL, SJ.LINK_PAYS, P.CODE, P.NAME, P.WAY_CALC, SJ.SUMMA, SJ.LINK_VKR, 
	PERIOD_BEGIN = CASE WHEN COALESCE(R.LINK_UP,0) <> 0 AND @DOCUMENTS_RECALC_OPT1 = 1 THEN SJ.DATE_BEGIN ELSE SJ.PERIOD_BEGIN END, 
	PERIOD_END = CASE WHEN COALESCE(R.LINK_UP,0) <> 0 AND @DOCUMENTS_RECALC_OPT1 = 1 THEN SJ.DATE_END ELSE SJ.PERIOD_END END, 
	SJ.DATE_BEGIN, SJ.DATE_END, Option_CV
FROM
	dbo.CALCULATE_JURNAL SJ 
	INNER JOIN dbo.PAYS P ON SJ.LINK_PAYS = P.LINK
	--Сыммы по перерасчету будем учитывать в месяце, за который перерасчитвали
	LEFT JOIN dbo.SDOC_AREC R ON SJ.LINK_DOC = R.LINK_UP 
	--Сыммы по начислению процентом учитывать в месяце, в котором рассчитвали
	LEFT JOIN dbo.SDOC_APER AP ON SJ.LINK_DOC = AP.LINK_UP 
where 
	SJ.LINK_EMPL = @varKSlinkEmpl
	AND
	SJ.PERIOD_BEGIN >= @varKSdDate1

---
declare @mat_period table (period datetime)

IF @FURLOUGH_OPT5 <> 12 
--Определим, за какие месяцы надо брать мат помощь.
Begin
	Set rowcount @FURLOUGH_OPT5
	
		insert into @mat_period (period)
		SELECT SJ.PERIOD_BEGIN
		FROM #tmpCJ SJ INNER JOIN dbo.group_pays(@varKSRefPay) T ON SJ.link_PAYS=T.PAY_LINK
		WHERE 
			SJ.LINK_EMPL = @varKSlinkEmpl AND SJ.PERIOD_BEGIN>=dbo.DateBeginOfMonth(DATEADD(Month,-12,@varKSdDate2))
			and SJ.PERIOD_END <= dbo.DateEndOfMonth(@varKSdDate3) AND SJ.WAY_CALC = 12
		order by SJ.PERIOD_BEGIN desc
	
	Set rowcount 0
END

DECLARE @E_FIN TABLE (LINK_EMPL INT, LINK_KBK INT)
INSERT INTO @E_FIN (LINK_EMPL,LINK_KBK)
SELECT TOP 1 empl_link, LINK_KBK FROM DBO.SA_EMPLS_INFO(@varKSdDate3, @varKSlinkEmpl)

/*промежуточный результат*/
declare @tbl table (PERIOD_BEGIN DATETIME, CODE_PAY varchar(10), NAME_PAY varchar(60), WAY_CALC tinyint, LINK_PAY int, summa numeric(18,2), LINK_VKR INT, DATE1 DATETIME, DATE2 DATETIME)
insert into @tbl(PERIOD_BEGIN, CODE_PAY,NAME_PAY,WAY_CALC,LINK_PAY,summa, LINK_VKR, DATE1, DATE2)
SELECT 			CONVERT(VARCHAR(8),((YEAR(PERIOD_BEGIN) * 100 + MONTH(PERIOD_BEGIN)) * 100 + 1)),
			[CODE_PAY]		= CODE_PAYS, 
			[NAME_PAY]		= NAME_PAYS, 
			[WAY_CALC]		= (Case when @nFURLOUGH_OPT1 = 1 and RTRIM(LTRIM(@ObjCode)) = 'DOCUMENTS_ADD_FURLOUGH' and WAY_CALC = 12 then 7 else WAY_CALC end), 
			[LINK_PAY]		= SJ.link_PAYS ,
			[SUMMA]			= SUM(SJ.summa), 
			LINK_VKR 		= COALESCE(LINK_VKR,DEF.LINK_KBK), 
			DATE1, 
			DATE2	

FROM #tmpCJ SJ 
	LEFT JOIN @E_FIN DEF ON DEF.LINK_EMPL = SJ.LINK_EMPL
WHERE 
	SJ.LINK_EMPL = @varKSlinkEmpl
	AND EXISTS (SELECT * FROM dbo.group_pays(@varKSRefPay) T WHERE SJ.link_PAYS=T.PAY_LINK) 
	AND SJ.PERIOD_BEGIN>=@varKSdDate1
	AND
	(	SJ.PERIOD_END<=@varKSdDate2 
		OR /*В начислении отпускных при определении заработка за последний расчетный месяц 
			брать метериальную помощь с признаком также из месяца начала отпуска*/
		RTRIM(LTRIM(@ObjCode)) = 'DOCUMENTS_ADD_FURLOUGH' AND WAY_CALC = 12 
				and Year(@varKSdDate2) = Year(@varKSdDate2) and Month(@varKSdDate2) = Month(@varKSdDate2)
				and Year(SJ.PERIOD_END) = Year(@varKSdDate3) and Month(SJ.PERIOD_END) = Month(@varKSdDate3)
	)
	AND
	(
		@FURLOUGH_OPT5 <> 12 and RTRIM(LTRIM(@ObjCode)) = 'DOCUMENTS_ADD_FURLOUGH' AND WAY_CALC = 12 
			and SJ.PERIOD_BEGIN in (Select period from @mat_period)
		OR
		NOT (@FURLOUGH_OPT5 <> 12 AND RTRIM(LTRIM(@ObjCode)) = 'DOCUMENTS_ADD_FURLOUGH' AND WAY_CALC = 12 )
	)

GROUP BY  
	CONVERT(VARCHAR(8),((YEAR(PERIOD_BEGIN) * 100 + MONTH(PERIOD_BEGIN)) * 100 + 1)), SJ.link_PAYS, CODE_PAYS, NAME_PAYS, WAY_CALC, COALESCE(LINK_VKR,DEF.LINK_KBK), DATE1, DATE2	 

/*Перечень сотрудников, которым НЕ нужно индексировать*/
DECLARE @NO_INDEX_EMPL table (link int)
INSERT INTO @NO_INDEX_EMPL (link)
SELECT LINK_EMPL FROM dbo.GROUPS_EMPL G inner join dbo.GROUPS_EMPL_REF E on E.LINK_GROUP = G.LINK
WHERE G.LINK = [dbo].[sa_get_option_by_code]('DICTIONARY_INDEX_OPT4')

/*Перечень надбавок, которые НЕ нужно индексировать*/
DECLARE @NO_INDEX_PAY table (link int)
INSERT INTO @NO_INDEX_PAY (link)
SELECT P.link
FROM dbo.PAY_GROUPS G inner join PAYS_REF PR on PR.LINK_GROUPS = G.LINK
	inner join  dbo.PAYS P on P.LINK = PR.LINK_PAYS
WHERE G.LINK = [dbo].[sa_get_option_by_code]('DICTIONARY_INDEX_OPT3')

/*Перечень надбавок, которые нужно индексировать*/
DECLARE @nadbavki table (link int)
INSERT INTO @nadbavki (link)
SELECT P.link 
FROM dbo.PAY_GROUPS G inner join PAYS_REF PR on PR.LINK_GROUPS = G.LINK
	inner join  dbo.PAYS P on P.LINK = PR.LINK_PAYS
WHERE G.LINK = [dbo].[sa_get_option_by_code]('DICTIONARY_INDEX_OPT1')
	AND P.link NOT IN (SELECT LINK FROM @NO_INDEX_PAY)

DECLARE @TI numeric(18,4)
DECLARE @INDEX_OPT2 int
Set @INDEX_OPT2 = [dbo].[sa_get_option_by_code]('DICTIONARY_INDEX_OPT2')

/*Заготовки для вычисления коэффициентов*/
declare @pn3 table (link_pay int, way_calc int, summa numeric(18,2))
declare @pn2 table (link_pay int, period datetime, summa numeric(18,2))
declare @koef table (link_pay int, period datetime, koef numeric(18,4))
/*Здесь коэффициенты тарифных ставок*/
declare @koef_ts table (link_pay int, period datetime, koef numeric(18,4))

IF (@INDEX_OPT2 = 2 OR @INDEX_OPT2 = 3 OR EXISTS (Select * from @nadbavki)) 
	AND @varKSlinkEmpl NOT IN (SELECT LINK FROM @NO_INDEX_EMPL)
BEGIN
	IF @INDEX_OPT2 = 3
		insert into @nadbavki (link) 
		Select distinct PE.link_pays from dbo.PAYS_EMPL PE 
		where PE.LINK_EMPL = @varKSlinkEmpl and PE.link_pays not in (select link from @nadbavki)

	--Размер постоянных начислений на конец расчетного периода @varKSdDate2 /*момент начала отпуска @varKSdDate3*/
	insert into @pn3 (link_pay, way_calc, summa)
	--Select link_pays, way_calc, sum(summa *ndays/wdays) from dbo.sa_all_pays_all(@varKSlinkEmpl,@varKSdDate2,null,DEFAULT,DEFAULT) 
	select link_pay, P.way_calc, SUM(summa) from dbo.SA_ALL_PAYS_ALL_DATE0(@varKSlinkEmpl, @varKSdDate2, DEFAULT,DEFAULT) A INNER JOIN dbo.PAYS P ON P.LINK = A.link_pay
	where  ISNULL(LINK_SOVM,0) = 0 and @varKSdDate2 between date_begin and coalesce(date_end,@varKSdDate2) and wdays <> 0
	group by link_pay, P.way_calc

	-- Для месяцев расчетного периода рассчитаем коеффициенты индексации
	DECLARE @Cur1 CURSOR, @PER DATETIME
	SET @Cur1 = CURSOR FORWARD_ONLY
	FOR Select DATE_BEGIN FROM dbo.months_ex(@varKSdDate1, @varKSdDate2)
	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @PER
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			insert into @pn2 (link_pay, period, summa)
			Select link_pay, @PER, sum(summa) 
			from --dbo.SA_ALL_PAYS_ALL0(@varKSlinkEmpl, @PER,null, DEFAULT,DEFAULT)
				dbo.SA_ALL_PAYS_ALL_DATE0(@varKSlinkEmpl, @PER, DEFAULT,DEFAULT)
				WHERE ISNULL(LINK_SOVM,0) = 0
			group by link_pay
		END
		FETCH NEXT FROM @Cur1 INTO @PER
	END
	
	CLOSE @Cur1 
	DEALLOCATE @Cur1

	--Здесь коэффициенты индексации оклада
	insert into @koef_ts (link_pay, period, koef)
	select D1.LINK_PAY, D2.period, Koef = Sum(coalesce(D1.summa,0) / coalesce(D2.summa,coalesce(D1.summa,0.0000001)))
	from  @pn3 D1 inner join @pn2 D2 on D1.LINK_PAY = D2.LINK_PAY 
		inner join dbo.WAY_CALC WC ON WC.CODE = D1.WAY_CALC AND WC.TYPE = 1 AND WC.OKLAD = 1
	where	@INDEX_OPT2 = 2 and coalesce(D2.summa,0) <> 0 and (coalesce(D1.SUMMA,0) / coalesce(D2.summa,coalesce(D1.SUMMA,0.0000001))) > 1 
	group by D1.LINK_PAY, D2.period 

	--Здесь коэффициенты индексации надбавок
	insert into @koef (link_pay, period, koef)
	select D1.LINK_PAY, d2.period, Koef = coalesce(D1.SUMMA,0) / coalesce(D2.summa,coalesce(D1.SUMMA,0.0000001))
	from  @pn3 D1 inner join @pn2 D2 on D1.LINK_PAY = D2.LINK_PAY inner join @nadbavki N on D1.LINK_PAY = N.link
	where	coalesce(D2.summa,0) <> 0 and (coalesce(D1.SUMMA,0) / coalesce(D2.summa,coalesce(D1.SUMMA,0.0000001))) > 1 

	--Здесь коэффициенты индексации прочих видов оплат, не являющихся постоянными начислениями
	IF @INDEX_OPT2 = 3
	BEGIN
		DECLARE @Cur2 CURSOR, @LINK_PAY INT
		SET @Cur2 = CURSOR FORWARD_ONLY
	
		FOR select distinct link from dbo.Pays P inner join @tbl J on P.LINK = J.LINK_PAY INNER JOIN dbo.WAY_CALC WC ON P.WAY_CALC = WC.CODE where object = 1 AND WC.TYPE = 1 AND isPercent = 1 AND P.LINK not in (select link from @nadbavki)
		
		OPEN @Cur2
		FETCH NEXT FROM @Cur2 INTO @LINK_PAY
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN

				insert into @koef (link_pay, period, koef)
				select @LINK_PAY, PERIOD_BEGIN,
					CASE WHEN SUM(coalesce(summa,0)) <> 0 THEN 
						SUM(convert(numeric(18,6),coalesce(summa,0)) * (case when coalesce(K.Koef,1) > 1 then coalesce(K.Koef,1) else 1 end)) / SUM(coalesce(summa,0.0000001))
					ELSE 1 END
				FROM @tbl T inner join (Select distinct PAY_LINK from dbo.group_pays(@LINK_PAY) ) BASE ON BASE.PAY_LINK = T.link_pay
					LEFT join @koef K on T.link_pay = K.link_pay AND Year(K.Period) = Year(T.DATE1) AND Month(K.Period) = Month(T.DATE1)
				WHERE	NOT EXISTS (Select * from @koef where link_pay = @LINK_PAY AND period = PERIOD_BEGIN)
				GROUP BY PERIOD_BEGIN
				ORDER BY PERIOD_BEGIN
			END
		
			FETCH NEXT FROM @Cur2 INTO @LINK_PAY
		END
		
		CLOSE @Cur2
		DEALLOCATE @Cur2
	END
	

END 

IF @INDEX_OPT2 = 1 AND @varKSlinkEmpl NOT IN (SELECT LINK FROM @NO_INDEX_EMPL)
	insert into @koef_ts (link_pay, period, koef)
	Select distinct link, M.DATE_BEGIN, dbo.SA_TARIF_INDEX(dbo.DateEndOfMonth(M.DATE_BEGIN), @varKSdDate2)  
	from dbo.pays, dbo.months_ex(@varKSdDate1, @varKSdDate2) M 
	where object = 1 
		AND @INDEX_OPT2 = 1
		AND link NOT IN (SELECT LINK_PAY FROM @koef)

/*вывод базовых начислений с учетом индексации тарифных ставок*/
select 
	PERIOD_BEGIN, 0 as Nadb, T.CODE_PAY, T.NAME_PAY, T.WAY_CALC, T.LINK_PAY, 
	summa= Convert(numeric(18,4),coalesce(summa,0)) * case when coalesce(K.Koef,1) > 1 and coalesce(NI.LINK,0) = 0 then coalesce(K.Koef,1) else 1 end, 
	sum0= coalesce(summa,0), 
	Koef= case when coalesce(K.Koef,1) > 1  and coalesce(NI.LINK,0) = 0 then coalesce(K.Koef,1) else 1 end, 
	COALESCE(Option_CV,0) CV, LINK_VKR, DATE1, DATE2
into #tmp
from 
	@tbl T inner join dbo.PAYS P on T.link_pay = P.link
	left join (SELECT PERIOD, MAX(KOEF) AS KOEF FROM @koef_ts GROUP BY PERIOD) K on YEAR(T.PERIOD_BEGIN) = YEAR(K.PERIOD) and MONTH(T.PERIOD_BEGIN) = MONTH(K.PERIOD)
	left join @NO_INDEX_PAY NI ON NI.LINK = P.LINK
where	
	not exists (Select K1.link_pay from @koef K1 where K1.link_pay = T.link_pay and coalesce(K1.Koef,1) > (coalesce(K.Koef,1)))

--Результат
CREATE TABLE #OUT_TABLE (
	PERIOD DATETIME,
	NADB NUMERIC(18,2),
	CODE_PAY VARCHAR(254),
	NAME_PAY VARCHAR(254), 
	WAY_CALC INT,
	LINK_PAY INT,
	SUMMA NUMERIC(18,2),
	SUM0 NUMERIC(18,2),
	KOEF  NUMERIC(18,4),
	CV	NUMERIC(18,2),
	LINK_VKR INT,
	DATE1 DATETIME,
	DATE2 DATETIME
)

--вывод базовых начислений с учетом индексации спец. надбавок (премии и т.д.)
INSERT INTO #OUT_TABLE (PERIOD, NADB, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, SUM0, KOEF, CV, LINK_VKR, DATE1, DATE2)
Select PERIOD_BEGIN, Nadb,CODE_PAY,NAME_PAY,WAY_CALC,LINK_PAY,summa,sum0,Koef,CV, LINK_VKR, DATE1, DATE2
from #tmp

--union all 
--Оклад и др. постоянные начисления
INSERT INTO #OUT_TABLE (PERIOD, NADB, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, SUM0, KOEF, CV, LINK_VKR, DATE1, DATE2)
select PERIOD_BEGIN, 1 as Nadb, T.CODE_PAY,T.NAME_PAY,T.WAY_CALC, T.LINK_PAY, 
	summa= convert(numeric(18,4),coalesce(summa,0)) * (case when coalesce(K.Koef,1) > 1 and coalesce(NI.LINK,0) = 0 then coalesce(K.Koef,1) else 1 end), 
	sum0= coalesce(summa,0),
	Koef= (case when coalesce(K.Koef,1) > 1 and coalesce(NI.LINK,0) = 0 then coalesce(K.Koef,1) else 1 end), 
	0 CV, LINK_VKR, DATE1, DATE2
from 
	@tbl T LEFT join @koef K on T.link_pay = K.link_pay AND Year(K.Period) = Year(T.PERIOD_BEGIN) AND Month(K.Period) = Month(T.PERIOD_BEGIN)
	left join @NO_INDEX_PAY NI ON NI.LINK = T.link_pay
where	
	T.link_pay not in (Select link_pay from #tmp where #tmp.PERIOD_BEGIN = T.PERIOD_BEGIN)
order by PERIOD_BEGIN, CODE_PAY, LINK_VKR

--Расчёт коэффициента индексации для районного и северного
DECLARE 
	@LINK_RAYON INT, 
	@LINK_SEVER INT, 
	@REGION_VAL NUMERIC(18,4), 
	@REGION_SUM NUMERIC(18,2), 
	@Y INT, 
	@M INT, 
	@LINK_SFIN INT,  
	@TMP_DATE DATETIME

SET @LINK_RAYON = dbo.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPTIONS3_1')
SET @LINK_SEVER = dbo.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPTIONS3_2')

SET @Cur1 = CURSOR FORWARD_ONLY

FOR SELECT DISTINCT Y = YEAR(DATE1), M = MONTH(DATE1) FROM #OUT_TABLE ORDER BY YEAR(DATE1), MONTH(DATE1)

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @Y, @M
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN
	
		SET @TMP_DATE = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@M,@Y))
		
		----Пересчёт для коэф индексации для районного			
		SET @REGION_VAL = DBO.SA_GET_REGION(@varKSlinkEmpl,@TMP_DATE,1)
		
		IF @REGION_VAL > 0 
		BEGIN
		
			SET @Cur2 = CURSOR FORWARD_ONLY

			FOR SELECT DISTINCT LINK_VKR FROM #OUT_TABLE WHERE YEAR(PERIOD) =  @Y AND MONTH(PERIOD) = @M ORDER BY LINK_VKR
			
			OPEN @Cur2
			FETCH NEXT FROM @Cur2 INTO @LINK_SFIN
			WHILE (@@fetch_status <> -1)
			BEGIN
				IF (@@fetch_status <> -2)
				BEGIN

					IF EXISTS (SELECT * FROM #OUT_TABLE WHERE YEAR(PERIOD) = @Y AND MONTH(PERIOD) = @M AND LINK_VKR = @LINK_SFIN AND LINK_PAY = @LINK_RAYON AND KOEF > 1)
					BEGIN

	--					SET @REGION_SUM = ISNULL((SELECT SUM(SUM0) FROM #BASE1 S WHERE YEAR(PERIOD) = @Y AND MONTH(PERIOD) = @M AND LINK_VKR = @LINK_SFIN AND S.LINK_PAY = @LINK_RAYON),0)
	--					ROUND(SUM(S.SUM0) * @REGION_VAL / (@REGION_SUM * 100),4) --Коэффициент соответствия рассчётного районного коэффицента фактическому
						SET @REGION_VAL = ISNULL(
							(
								SELECT 
									CASE WHEN SUM(S.SUM0) <> 0 THEN
										ROUND(SUM(S.SUMMA) / SUM(S.SUM0),4) --расчётный коэф индексации
									ELSE 0 END	
								FROM #OUT_TABLE S INNER JOIN dbo.group_pays(@LINK_RAYON) B ON S.LINK_PAY = B.PAY_LINK
								WHERE YEAR(S.PERIOD) = @Y AND MONTH(S.PERIOD) = @M AND LINK_VKR = @LINK_SFIN
							),1)
						
						UPDATE #OUT_TABLE
						SET KOEF = @REGION_VAL, SUMMA = SUM0 * @REGION_VAL
						WHERE YEAR(PERIOD) = @Y AND MONTH(PERIOD) = @M AND LINK_VKR = @LINK_SFIN AND LINK_PAY = @LINK_RAYON
					END	
					
				END
			
				FETCH NEXT FROM @Cur2 INTO @LINK_SFIN
			END
			
			CLOSE @Cur2
			DEALLOCATE @Cur2
		END	--IF @REGION_VAL > 0

		----Пересчёт для коэф индексации для северного			
		SET @REGION_VAL = DBO.SA_GET_REGION(@varKSlinkEmpl,@TMP_DATE,2)
	
		IF @REGION_VAL > 0 
		BEGIN
		
			SET @Cur2 = CURSOR FORWARD_ONLY

			FOR SELECT DISTINCT LINK_VKR FROM #OUT_TABLE WHERE YEAR(PERIOD) =  @Y AND MONTH(PERIOD) = @M ORDER BY LINK_VKR
			
			OPEN @Cur2
			FETCH NEXT FROM @Cur2 INTO @LINK_SFIN
			WHILE (@@fetch_status <> -1)
			BEGIN
				IF (@@fetch_status <> -2)
				BEGIN

					IF EXISTS (SELECT * FROM #OUT_TABLE WHERE YEAR(PERIOD) = @Y AND MONTH(PERIOD) = @M AND LINK_VKR = @LINK_SFIN AND LINK_PAY = @LINK_SEVER AND KOEF > 1)
					BEGIN

						SET @REGION_VAL = ISNULL(
							(
								SELECT 
									CASE WHEN SUM(S.SUM0) <> 0 THEN
										ROUND(SUM(S.SUMMA) / SUM(S.SUM0),4) --расчётный коэф индексации
									ELSE 0 END	
								FROM #OUT_TABLE S INNER JOIN dbo.group_pays(@LINK_SEVER) B ON S.LINK_PAY = B.PAY_LINK
								WHERE YEAR(S.PERIOD) = @Y AND MONTH(S.PERIOD) = @M AND LINK_VKR = @LINK_SFIN
							),1)
						
						UPDATE #OUT_TABLE
						SET KOEF = @REGION_VAL, SUMMA = SUM0 * @REGION_VAL
						WHERE YEAR(PERIOD) = @Y AND MONTH(PERIOD) = @M AND LINK_VKR = @LINK_SFIN AND LINK_PAY = @LINK_SEVER
					END
					
				END
			
				FETCH NEXT FROM @Cur2 INTO @LINK_SFIN
			END
			
			CLOSE @Cur2
			DEALLOCATE @Cur2
		END	--IF @REGION_VAL > 0			
		
	END  

	FETCH NEXT FROM @Cur1 INTO @Y, @M
END

CLOSE @Cur1
DEALLOCATE @Cur1

------------------
SELECT PERIOD, NADB, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, SUM0, KOEF, CV, LINK_VKR, DATE1, DATE2 FROM #OUT_TABLE

Return 0

GO


GRANT EXECUTE ON dbo.[SD_BASE_SUM_PAY_DIF_PERIODS] TO PUBLIC

GO

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

GO


CREATE     PROCEDURE dbo.BK_FORM_SAVE_DOCUMENT_TABLE
	@varKScCode varchar(30)
AS
BEGIN
	DECLARE
		@varKSnLink		int,
		@varKSCurLINK	int,
		@varKSRefLINK	int,
		@varKSCurCODE	varchar(30),
		@varKSShortCode	varchar(30),
		@varKSInALIAS	varchar(10),
		@varKSType	varchar(100),
		@varKSStorage	varchar(30),
		@varKSSel_Str	varchar(8000),
		@varKSCur_Str	varchar(8000),
		@varKSADDTYPE	varchar(100),
		@varKScResCode	varchar(100),
		@varKSchrNAME	varchar(100)
--
	DECLARE 
		@varKSpartParams	varchar(8000),
		@varKSpartDiction	varchar(8000),
		@varKSpartDepartment	varchar(8000),
		@varKSpartSubdiv	varchar(8000),
		@varKSpartAccount	varchar(8000),
		@varKSpartSumma		varchar(8000),
		@varKSpartDate		varchar(8000),
		@varKSpartString	varchar(8000),
		@varKSSaveMethod	varchar(8000),
		@varKSchrCodeType	varchar(100),
		@varKSchrNameType	varchar(100),
		@varKSchrRefField	varchar(100),

		@varKSpartEmpl	varchar(8000),
		@varKSpartKBK	varchar(8000),
		@varKSpartKOSGU	varchar(8000),
		@varKSpartG_PROV varchar(8000),
		@varKSpartINVENTORY	varchar(8000),
		@varKSpartNOMENCLATURE varchar(8000),
		@varKSpartFIN_SOURCE	varchar(8000),
		@varKSpartPERSON_ECARDS varchar(8000),
		@partOSNOV varchar(8000)

	SELECT @varKSnLink = LINK FROM S_OBJECTS WHERE CODE = @varKScCode

PRINT '---------------'+@varKScCode
IF @varKSnLink is null OR @varKSnLink=0
BEGIN
	print 'Произошла неустранимая ошибка при формировании запроса.
     Попробуйте обратиться в службу поддержки.
    Или просто задайте правильное имя объекта!'
	Return
END
	Select @varKSType=NAME FROM S_OBJECTS WHERE CODE=@varKScCode
	print '('+@varKSType+')'

	DECLARE SEL_CURSOR CURSOR STATIC LOCAL
	FOR SELECT LINK, CODE, NAME
		FROM S_OBJECTS SO
		WHERE LINK_SELF=@varKSnLink AND (SELECT CODE FROM S_OBJECTS WHERE LINK=SO.LINK_CLASS)='EDIT_FIELD_CLASS'
		ORDER BY ORDERS

SET	@varKSpartParams		= ''
SET	@varKSpartDiction	= ''
SET	@varKSpartDepartment	= ''
SET @varKSpartSubdiv 	= ''
SET	@varKSpartAccount	= ''
SET	@varKSpartSumma		= ''
SET	@varKSpartString		= ''
SET	@varKSpartDate		= ''
SET	@varKSchrCodeType	= ''
SET	@varKSchrNameType	= ''
SET	@varKSSaveMethod		= 'SQLNULL(LINK_UP), ORDERS'

SET	@varKSpartEmpl	= ''
SET	@varKSpartKBK	= ''
SET	@varKSpartKOSGU	= ''
SET	@varKSpartINVENTORY	= ''
SET	@varKSpartNOMENCLATURE	= ''
set @varKSpartG_PROV = ''
SET	@varKSpartFIN_SOURCE	= ''
set @varKSpartPERSON_ECARDS = ''
SET	@partOSNOV = ''

	SET @varKSSel_Str=
'
--Процедура сформирована с помощью BK_FORM_SAVE_DOCUMENT_TABLE 
--'+LTRIM(convert(char, getdate(), 120))+'
PROCEDURE dbo.X_SAVE_'+@varKScCode
	
	OPEN SEL_CURSOR
	FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE, @varKSchrNAME
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXECUTE X_GET_PROP  @varKSCurCODE, 'FIELD_IN_ALIAS', @varKSInALIAS OUTPUT
		EXECUTE X_GET_PROP  @varKSCurCODE, 'STORAGE', @varKSStorage OUTPUT
		SET @varKSStorage=UPPER(LTRIM(RTRIM(@varKSStorage)))
		IF Convert(int, @varKSInALIAS) = 1
		BEGIN
			EXECUTE X_GET_PROP  @varKSCurCODE, 'SHORT_CODE_OBJ', @varKSShortCode OUTPUT
			EXECUTE X_GET_PROP  @varKSCurCODE, 'TYPE_FIELD_DICT', @varKSType OUTPUT
			SET @varKSType = UPPER(LTRIM(RTRIM(@varKSType)))
			EXECUTE X_GET_PROP  @varKSCurCODE, 'REFERENCE_TO_FIELD', @varKSchrRefField OUTPUT
			print @varKSStorage + '	' + @varKSShortCode + '	' + @varKSType + '	' + @varKSchrRefField
			IF @varKSType = 'DATETIME'
				SET @varKSADDTYPE=',104'
			ELSE
				SET @varKSADDTYPE=''
			
		
			IF @varKSStorage IN ('SUMMA', 'STRING', 'DATE')
				OR (@varKSStorage IN('DICTION', 'DEPARTMENTS', 'ACCOUNT', 'SUBDIV',
						'EMPL', 'INVENTORY', 'KL_KBK', 'NOMENCLATURE', 'KOSGU', 'G_PROV', 'FIN_SOURCE', 'PERSON_ECARDS',
						'OSNOV')
					AND @varKSchrRefField = 'LINK') 
			BEGIN
				IF @varKSStorage IN('DICTION', 'ACCOUNT', 'DEPARTMENTS', 'SUBDIV',
						'EMPL', 'INVENTORY', 'KL_KBK', 'NOMENCLATURE', 'KOSGU', 'G_PROV', 'FIN_SOURCE', 'PERSON_ECARDS',
						'OSNOV')
					SET @varKSType = 'INT'
				SET @varKSpartParams = @varKSpartParams + ',' + CHAR(13) + CHAR(10) + '	@varKSp' + @varKSShortCode + SPACE(15-LEN(@varKSShortCode)) + @varKSType + ' = null'
				IF @varKSStorage = 'DATE' OR @varKSStorage IN('DICTION', 'DEPARTMENTS') AND @varKSchrRefField = 'LINK' OR @varKSType = 'DATETIME'
					SET @varKSSaveMethod = @varKSSaveMethod + ', SQLNULL(' + @varKSShortCode + ')'
				ELSE
					SET @varKSSaveMethod = @varKSSaveMethod + ', ' + @varKSShortCode
			END

			IF @varKSShortCode is null OR LTRIM(@varKSShortCode)=''
				print '****ОШИБКА!    Нет свойства SHORT_CODE_OBJ. Объект: '+@varKSCurCODE
			ELSE
			BEGIN
				IF @varKSStorage = 'DICTION' AND @varKSchrRefField = 'LINK'
				SET @varKSpartDiction = @varKSpartDiction + '
	EXEC @varKSERROR = dbo.x_UPDATE_OUT_TABLE_DICTION @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'


				IF @varKSStorage = 'DEPARTMENTS' AND @varKSchrRefField = 'LINK'
				SET @varKSpartDepartment = @varKSpartDepartment + '
	EXEC @varKSERROR = dbo.x_UPDATE_OUT_TABLE_DEPARTMENT @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR

'

				IF @varKSStorage = 'SUBDIV' AND @varKSchrRefField = 'LINK'
				SET @varKSpartSubdiv = @varKSpartSubdiv + '
	EXEC @varKSERROR = dbo.x_UPDATE_OUT_TABLE_SUBDIV @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'


				IF @varKSStorage = 'ACCOUNT' AND @varKSchrRefField = 'LINK'
				SET @varKSpartAccount = @varKSpartAccount + '
	EXEC @varKSERROR = dbo.x_UPDATE_OUT_TABLE_ACCOUNT @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'SUMMA'
				SET @varKSpartSumma = @varKSpartSumma + '
	EXEC @varKSERROR = dbo.x_UPDATE_OUT_TABLE_SUMMA @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'STRING'
				SET @varKSpartString = @varKSpartString + '
	EXEC @varKSERROR = dbo.x_UPDATE_OUT_TABLE_STRING @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'DATE'
				SET @varKSpartDate = @varKSpartDate + '
	EXEC @varKSERROR = dbo.x_UPDATE_OUT_TABLE_DATE @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'EMPL' AND @varKSchrRefField = 'LINK'
				SET @varKSpartEmpl = @varKSpartEmpl + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_EMPL @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'KL_KBK' AND @varKSchrRefField = 'LINK'
				SET @varKSpartKBK = @varKSpartKBK + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_KBK @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'INVENTORY' AND @varKSchrRefField = 'LINK'
				SET @varKSpartINVENTORY = @varKSpartINVENTORY + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_INVENTORY @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'NOMENCLATURE' AND @varKSchrRefField = 'LINK'
				SET @varKSpartNOMENCLATURE = @varKSpartNOMENCLATURE + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_NOMENCLATURE @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'KOSGU' AND @varKSchrRefField = 'LINK'
				SET @varKSpartKOSGU = @varKSpartKOSGU + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_KOSGU @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'G_PROV' AND @varKSchrRefField = 'LINK'
				SET @varKSpartG_PROV = @varKSpartG_PROV + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_G_PROV @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'FIN_SOURCE' AND @varKSchrRefField = 'LINK'
				SET @varKSpartFIN_SOURCE = @varKSpartFIN_SOURCE + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_FIN_SOURCE @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
				IF @varKSStorage = 'PERSON_ECARDS' AND @varKSchrRefField = 'LINK'
				SET @varKSpartPERSON_ECARDS = @varKSpartPERSON_ECARDS + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_ECARDS @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'

				IF @varKSStorage = 'OSNOV' AND @varKSchrRefField = 'LINK'
				SET @partOSNOV = @partOSNOV + '
	EXEC @varKSERROR = dbo.BK_UPDATE_OUT_TABLE_OSNOV @varKSpLINK, ' + LTRIM(STR(@varKSCurLINK)) + ', @varKSp' + @varKSShortCode +'
	IF @varKSERROR <> 0
		RETURN @varKSERROR
'
			END
			IF @varKSStorage NOT IN ('SUMMA', 'DATE', 'STRING', 'DICTION', 'DICTION_APP', 'DICTION_REF', 'ACCOUNT', 'DEPARTMENTS', 'SUBDIV',
						'EMPL', 'INVENTORY', 'KL_KBK', 'NOMENCLATURE', 'KOSGU', 'G_PROV', 'FIN_SOURCE', 'PERSON_ECARDS',
						'OSNOV')
				Print '***Свойство STORAGE ошибочно или отсутствует! Объект:'+@varKSCurCODE

		END
		FETCH NEXT FROM SEL_CURSOR INTO @varKSCurLINK, @varKSCurCODE, @varKSchrNAME
	END
	
	CLOSE SEL_CURSOR
	DEALLOCATE SEL_CURSOR

	
	SET @varKScResCode = 'X_SAVE_' + @varKScCode
	IF object_id(@varKScResCode) is not null
		SET @varKSSel_Str='ALTER ' + @varKSSel_Str
	ELSE
		SET @varKSSel_Str='CREATE ' + @varKSSel_Str

	SET @varKSSel_Str = @varKSSel_Str + 
'
	@varKSpLINK		int	OUTPUT,
	@varKSpLINK_UP	int,
	@varKSpORDERS	int'
	SET @varKSSel_Str = @varKSSel_Str + @varKSpartParams + 
'
AS
DECLARE @varKSERROR	tinyint,
		@varKSstrVALUE	varchar(7000),
		@varKStrancount	int
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
	--Вставка/обновление G_PROV
	EXECUTE @varKSERROR = dbo.X_UPDATE_OUT_TABLE_ROW @varKSpLINK OUTPUT, @varKSpLINK_UP, ' + LTRIM(STR(@varKSnLink)) + ', @varKSpORDERS
	IF @varKSERROR <> 0
		RETURN @varKSERROR
	--Вставка/обновление OUT_TABLE_DICTION'
 + @varKSpartDiction + 
'
	--Вставка/обновление OUT_TABLE_DEPARTMENT'

 + @varKSpartDepartment + 
'
	--Вставка/обновление OUT_TABLE_SUBDIV'

 + @varKSpartSubdiv + 
'
	--Вставка/обновление OUT_TABLE_ACCOUNT'
 + @varKSpartAccount + 
'
	--Вставка/обновление OUT_TABLE_SUMMA'
 + @varKSpartSumma + 
'
	--Вставка/обновление OUT_TABLE_STRING'
 + @varKSpartString + 
'
	--Вставка/обновление OUT_TABLE_DATE'
 + @varKSpartDate + 
'

	--Вставка/обновление OUT_TABLE_EMPL'
 + @varKSpartEmpl + 
'

	--Вставка/обновление OUT_TABLE_INVENTORY'
 + @varKSpartINVENTORY + 
'

	--Вставка/обновление OUT_TABLE_NOMENCLATURE'
 + @varKSpartNOMENCLATURE + 
'

	--Вставка/обновление OUT_TABLE_KBK'
 + @varKSpartKBK + 
'

	--Вставка/обновление OUT_TABLE_KOSGU'
 + @varKSpartKOSGU + 
'

	--Вставка/обновление OUT_TABLE_G_PROV'
 + @varKSpartG_PROV + 
'

	--Вставка/обновление OUT_TABLE_FIN_SOURCE'
 + @varKSpartFIN_SOURCE + 
'
	--Вставка/обновление OUT_TABLE_PERSON_ECARDS'
 + @varKSpartPERSON_ECARDS + 
'

	--Вставка/обновление OUT_TABLE_OSNOV'
 + @partOSNOV + 
'

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0
'
PRINT @varKSSel_Str

	EXECUTE (@varKSSel_Str)
	DECLARE @varKSprocname varchar(254), @varKSmakeby varchar(254)
	SELECT @varKSprocname = 'X_SAVE_'+@varKScCode, @varKSmakeby = 'EXECUTE BK_FORM_SAVE_DOCUMENT_TABLE ''' + @varKScCode+''''
	EXEC U_UPDATE_SCRIPT_PROPERTY @varKSprocname, @varKSmakeby
	
	UPDATE OBJECT_VALUES
	SET VALUE = 'X_SAVE(''X_SAVE_'+@varKScCode+''', m.cAlias,'''+@varKSSaveMethod+''',"'+@varKScCode+'")',
		INHERITED = 0
	WHERE OBJECT = @varKSnLink
			AND PROPERTY = (SELECT LINK FROM S_PROPERTY WHERE CODE = 'SAVE_OBJECT_METHOD')
			AND (VALUE IS NULL OR VALUE = '')

	UPDATE S_DBObjects SET Rights = 0xA WHERE Object=@varKSnLink AND DBObject=@varKScResCode
	IF @@ROWCOUNT = 0	
		INSERT INTO S_DBObjects(Object, DBObject, Rights)
			VALUES (@varKSnLink, @varKScResCode, 0xA)
END



GO


GRANT EXECUTE ON dbo.[BK_FORM_SAVE_DOCUMENT_TABLE] TO PUBLIC

GO


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


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

GO

CREATE  PROCEDURE dbo.[SD_REP_SVOD]

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


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

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

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

	end
	else
		insert into #ekr (link)
		select link from dbo.kosgu order by CODE
	-----
	DECLARE @SALARY_PROV_OPT4 TINYINT
	SET @SALARY_PROV_OPT4 = dbo.sa_get_option_by_code('SALARY_PROV_OPT4')
	-----
	
	IF OBJECT_ID('tempdb..#s_j_c') IS NOT NULL
		DROP TABLE #s_j_c
	
	create table #s_j_c (LINK_EMPL int, TAB_NUM varchar(10), FIO varchar(100), LINK_FACE int, LINK_PAYS int,CODE_PAYS varchar(10),
						 NAME_PAYS varchar(60),TYP_PER tinyint,MONTH_BEGIN int,YEAR_BEGIN int,PERIOD_BEGIN datetime,MONTH_END int ,
						 YEAR_END int,PERIOD_END datetime,[HOURS] numeric(7,2),[DAYS] int,SUMMA_BASE numeric(15,2),PROCENT numeric(15,2),
						 SUMMA numeric(15,2),SUBDIV_HEAD int ,NAME_SUBDIV varchar(254),CODE_SUBDIV varchar(5), 
						 TYP_OPER tinyint, PERS_LINK int ,LINK_VKR int,NAME_VKR varchar(20), LINK_EKR int,CODE_EKR char(3),NAME_EKR varchar(250),
						 LINK_INC int, LINK_DEP int,name_dep varchar(254),link_kateg int,kateg_name varchar(50),razr int,num_stake numeric(5,2),link_type int,
						 code_type varchar(4))

	insert into #s_j_c (LINK_EMPL,TAB_NUM,FIO,LINK_FACE,LINK_PAYS,CODE_PAYS,
						NAME_PAYS,TYP_PER,MONTH_BEGIN,YEAR_BEGIN,PERIOD_BEGIN,MONTH_END,
						YEAR_END,PERIOD_END,HOURS,DAYS,SUMMA_BASE,PROCENT,SUMMA,SUBDIV_HEAD,NAME_SUBDIV,CODE_SUBDIV,
						TYP_OPER,PERS_LINK,LINK_VKR,NAME_VKR,LINK_EKR,CODE_EKR,NAME_EKR,
						LINK_INC,LINK_DEP,name_dep,link_kateg,kateg_name,razr,num_stake,link_type,code_type)
	SELECT LINK_EMPL,TAB_NUM,FIO,LINK_FACE,LINK_PAYS,CODE_PAYS,
			NAME_PAYS,TYP_PER,MONTH_BEGIN,YEAR_BEGIN,PERIOD_BEGIN,MONTH_END,
			YEAR_END,PERIOD_END,HOURS,DAYS,SUMMA_BASE,PROCENT,SUMMA,SUBDIV_HEAD,NAME_SUBDIV,CODE_SUBDIV,
			TYP_OPER,PERS_LINK,LINK_VKR,NAME_VKR,LINK_EKR,
			CODE_EKR , 
			NAME_EKR,LINK_INC,
			LINK_DEP,name_dep,link_kateg,kateg_name,razr,num_stake,link_type,code_type
	FROM 
		dbo.SALARY_JURNAL_CALCULAT 
	WHERE 
		period_begin between @varKSdDate1 and @varKSdDate2 
	----
	----
	CREATE TABLE #T1 (SUBDIV VARCHAR(254), link_face INT, link_pays INT, name_pays VARCHAR(254), code_pays VARCHAR(10), typ_oper TINYINT, link_inc int, name_vkr VARCHAR(254), code_ekr VARCHAR(10), summa NUMERIC(18,2), [hours] NUMERIC(18,2), [days] NUMERIC(18,2))

	INSERT INTO #T1	(SUBDIV, LINK_FACE, LINK_PAYS, NAME_PAYS, CODE_PAYS, TYP_OPER, link_inc, NAME_VKR, CODE_EKR, SUMMA, [HOURS], [DAYS])
	SELECT 
		s_j_c.NAME_SUBDIV AS SUBDIV, s_j_c.LINK_FACE, LINK_PAYS, NAME_PAYS, CODE_PAYS, TYP_OPER, link_inc, NAME_VKR, 
		CODE_EKR = CASE WHEN TYP_OPER = 3 THEN
							CASE WHEN @SALARY_PROV_OPT4 = 0 THEN 
									CASE WHEN ISNULL(s_j_c.CODE_EKR,'213') = '211' THEN '213' ELSE ISNULL(s_j_c.CODE_EKR,'213') END
								ELSE 
									CASE WHEN ISNULL(s_j_c.CODE_EKR,'213') IN ('211', '212') THEN '213' ELSE ISNULL(s_j_c.CODE_EKR,'213') END
							END
						ELSE s_j_c.CODE_EKR
					END, 
		SUMMA, [HOURS], [DAYS] 
	FROM 
		#s_j_c as s_j_c 
		inner join dbo.KS_OPTIONS_ZB zb on s_j_c.LINK_DEP = zb.ZB_LINK 
		LEFT JOIN DBO.SA_EMPLS_INFO(DEFAULT, DEFAULT) D ON s_j_c.LINK_EMPL = D.EMPL_LINK
	WHERE 
		period_begin between @varKSdDate1 and @varKSdDate2 
		and (LEN(@varKScVal1) <> 0 and s_j_c.LINK_VKR in (select LINK_VKR from #VKR) or LEN(@varKScVal1) = 0 )
		and (LEN(@varKScVal2) <> 0 and s_j_c.LINK_EKR in (Select link from #ekr) or LEN(@varKScVal2) = 0)
		and (LEN(@cVal3) = 0
			OR
				( s_j_c.SUBDIV_HEAD IN (select RECORD from dbo.OBJECT_VAR_SUBDIV_HEAD WHERE LINK_UP = @nOtborLink3)
				)
			)
 		AND (	--ОТБОР КАТЕГОРИЙ ДОЛЖНОСТЕЙ
			@CVAL4 <> '' AND ((s_j_c.LINK_KATEG <> 0 and  s_j_c.LINK_KATEG IN (SELECT RECORD FROM DBO.OBJECT_VAR_KATEG WHERE LINK_UP = @NOTBORLINK4))
								OR ( s_j_c.LINK_KATEG = 0 and  (select distinct st.KAT_LINK 
																from sa_item_move sm 
																	left join staff st on st.LINK_up = sm.STAFF_LINK and st.link = (SELECT MAX(link) from  staff where LINK_up = sm.STAFF_LINK)
																	left join SUBDIV su on su.link_up = st.SUBDIV_LINK and su.link = (SELECT MAX(link) from  SUBDIV where LINK_up = st.SUBDIV_LINK)
																where sm.EMPL_LINK = s_j_c.LINK_EMPL and sm.date_end >= @varKSdDate2
																) IN (SELECT RECORD FROM DBO.OBJECT_VAR_KATEG WHERE LINK_UP = @NOTBORLINK4)
									)
							  )
			
			OR
			@CVAL4 = '' )
		AND
			(@STATUS3 = 0 or @STATUS3 = 1 AND ISNULL(D.STATUS,0) <> 3)

	-- Проверка
	IF NOT EXISTS (SELECT * FROM #T1 WHERE typ_oper = 1)
		INSERT INTO #T1 (typ_oper) VALUES (1)
	IF NOT EXISTS (SELECT * FROM #T1 WHERE typ_oper = 2)
		INSERT INTO #T1 (typ_oper) VALUES (2)
	IF NOT EXISTS (SELECT * FROM #T1 WHERE typ_oper = 3)
		INSERT INTO #T1 (typ_oper) VALUES (3)

------------****************** Необлагаемые суммы по НДФЛ
;WITH 
	T1 AS 
	(
	SELECT DLINK = D.LINK, SK.LINK_EMPL, SUMMA = SUM(SK.SUMMA), SK.LINK_VKR, sf.code as code_vkr_N , SK.LINK_EKR , kg.code as code_ekr_n
	FROM
		dbo.SAL_DED_MONTH SK
		INNER JOIN dbo.DICTIONARY_TYP_INCOMS D ON D.REF_DEDUCT = SK.REF_DED
		Inner join  dbo.SAL_SFIN sf on sf.link = sk.link_vkr
		inner join dbo.kosgu  kg on kg.link = sk.link_ekr
	WHERE
		SK.DATE_DED BETWEEN @varKSdDate1 AND @varKSdDate2	
	GROUP BY
		D.LINK, SK.LINK_EMPL, SK.LINK_VKR, SK.LINK_EKR, sf.code	, kg.code
	),
	
	T2 AS 
	(
	SELECT 
		CJ.LINK_EMPL, DLINK = P.LINK_INC, CJ.LINK_VKR, CODE_VKR_n = CJ.NAME_VKR, CJ.LINK_EKR,  code_ekr_n = CJ.CODE_EKR, SUMMA = SUM(CJ.SUMMA)
	FROM
		#s_j_c CJ
		INNER JOIN dbo.PAYS P ON P.LINK = CJ.LINK_PAYS
		INNER JOIN dbo.DICTIONARY_TYP_INCOMS D ON D.LINK = P.LINK_INC
		inner join DICTIONARY_MROT_TABLE1 dm1 on  dm1.ref_pay = D.REF_DEDUCT 
		inner join DICTIONARY_MROT dm on dm.LINK = dm1.LINK_MINROT
	WHERE
		P.OBJECT = 1
		AND PERIOD_BEGIN BETWEEN @varKSdDate1 AND @varKSdDate2
		and dm.PERIOD between '20130101' AND '20131231'
		AND D.REF_DEDUCT IS NOT NULL
	GROUP BY
		CJ.LINK_EMPL, P.LINK_INC, CJ.LINK_VKR, CJ.LINK_EKR, CJ.NAME_VKR, CJ.CODE_EKR
	HAVING 
		SUM(CJ.SUMMA) <> 0	
	)	

	SELECT 
		PLINK = P.LINK, LINK_INC = P.LINK_INC, LINK_VKR= CJ.LINK_VKR,CODE_VKR_N = CJ.NAME_VKR, 
		LINK_EKR = CJ.LINK_EKR, CODE_EKR_N = CJ.CODE_EKR, SUM_NDFL = SUM(T1.SUMMA * CJ.SUMMA/T2.SUMMA)
	INTO #NO_NDFL_TMP
	FROM
		#s_j_c CJ
		INNER JOIN dbo.PAYS P ON P.LINK = CJ.LINK_PAYS
		INNER JOIN dbo.DICTIONARY_TYP_INCOMS D ON D.LINK = P.LINK_INC
		INNER JOIN T1 ON T1.LINK_EMPL = CJ.LINK_EMPL AND T1.DLINK = P.LINK_INC AND T1.LINK_VKR = CJ.LINK_VKR AND T1.LINK_EKR = CJ.LINK_EKR
		INNER JOIN T2 ON T2.LINK_EMPL = CJ.LINK_EMPL AND T2.DLINK = P.LINK_INC AND T2.LINK_VKR = CJ.LINK_VKR AND T2.LINK_EKR = CJ.LINK_EKR
	WHERE
		P.OBJECT = 1
		AND PERIOD_BEGIN BETWEEN @varKSdDate1 AND @varKSdDate2
		AND D.REF_DEDUCT IS NOT NULL
	GROUP BY
		P.LINK, P.LINK_INC, CJ.LINK_VKR, CJ.LINK_EKR, CJ.NAME_VKR, CJ.CODE_EKR
	ORDER BY  
		P.LINK, P.LINK_INC, CJ.LINK_VKR, CJ.LINK_EKR	


	SELECT PLINK,  LINK_VKR,CODE_VKR_N ,LINK_EKR , CODE_EKR_N, sum(Sum_NDFL) AS Sum_NDFL
	INTO #NO_NDFL
	FROM #NO_NDFL_TMP 
	GROUP BY PLINK, link_vkr , code_vkr_N, link_ekr,  code_ekr_n 

	DROP TABLE #NO_NDFL_tmp

	--- ************************** Не облагаемые суммы по Страховым взносам  
;WITH 
	T1 AS 
	(
	SELECT SE.LINK_EMPL, SUMMA = SUM(se.ded_m), SE.LINK_VKR  , sf.code as code_vkr_S, SE.LINK_EKR, kg.code as code_ekr_S
	from	dbo.SDOC_ESN_TABLE SE    
		  INNER JOIN 	pays p  ON p.link = se.LINK_PAY  AND p.way_calc = 6
		--INNER JOIN dbo.DICTIONARY_TYP_INCOMS D ON D.REF_DEDUCT = SK.REF_DED
		--inner join DICTIONARY_DEDUCT_SALARY_table dd on dd.LINK_TAX = se.link_pay
		
		INNER JOIN sdoc s on  s.link = SE.link_up 
		Inner join  dbo.SAL_SFIN sf on sf.link = SE.link_vkr
		inner join dbo.kosgu  kg on kg.link = SE.link_ekr
	WHERE isnull(se.ded_m,0) <> 0 
		and s.[OBJECT] = (SELECT link FROM s_objects WHERE code = 'DOCUMENTS_DEDUCT_ESN_G') 
		and s.[date] BETWEEN '20130101' AND '20131231'	
	GROUP BY
		 SE.LINK_EMPL, SE.LINK_VKR, SE.LINK_EKR, sf.code, kg.code	
	),

	T2 AS 
	(
	SELECT 
		/*PLINK= P.LINK,*/ CJ.LINK_EMPL/*, DLINK = P.LINK_INC*/, CJ.LINK_VKR, CODE_VKR_S = CJ.NAME_VKR, CJ.LINK_EKR, CODE_EKR_S = CJ.CODE_EKR , SUMMA = SUM(CJ.SUMMA)
	FROM #s_j_c  CJ
		INNER JOIN dbo.PAYS P ON P.LINK = CJ.LINK_PAYS
		INNER JOIN dbo.DICTIONARY_TYP_INCOMS D ON D.LINK = P.LINK_INC
		inner join DICTIONARY_MROT_TABLE2 dm2 on  dm2.ref_pay = D.REF_DEDUCT 
		inner join DICTIONARY_MROT dm on dm.LINK = dm2.LINK_MINROT
	WHERE
		P.OBJECT = 1
		AND PERIOD_BEGIN BETWEEN '20130101' AND '20131231'
		and dm.PERIOD between '20130101' AND '20131231'
		AND D.REF_DEDUCT IS NOT NULL
	GROUP BY
		 CJ.LINK_EMPL/*,P.LINK*/, P.LINK_INC, CJ.LINK_VKR, CJ.LINK_EKR,CJ.NAME_VKR,CJ.CODE_EKR
	HAVING 
		SUM(CJ.SUMMA) <> 0	
	)	

	SELECT 
		PLINK = P.LINK,LINK_VKR= CJ.LINK_VKR, LINK_EKR= CJ.LINK_EKR, CODE_VKR_S = CJ.NAME_VKR, CODE_EKR_S = CJ.CODE_EKR, SUM_STR= SUM(T1.SUMMA * CJ.SUMMA/T2.SUMMA)
	INTO #NO_STR
	FROM
		#s_j_c CJ
		INNER JOIN dbo.PAYS P ON P.LINK = CJ.LINK_PAYS
		INNER JOIN dbo.DICTIONARY_TYP_INCOMS D ON D.LINK = P.LINK_INC
		INNER JOIN T1 ON T1.LINK_EMPL = CJ.LINK_EMPL AND T1.LINK_VKR = CJ.LINK_VKR AND T1.LINK_EKR = CJ.LINK_EKR
		INNER JOIN T2 ON T2.LINK_EMPL = CJ.LINK_EMPL AND /*T2.DLINK = P.LINK_INC AND*/ T2.LINK_VKR = CJ.LINK_VKR AND T2.LINK_EKR = CJ.LINK_EKR
	WHERE
		P.OBJECT = 1
		AND PERIOD_BEGIN between '20130101' AND '20131231'
		AND D.REF_DEDUCT IS NOT NULL
	GROUP BY
		P.LINK, CJ.LINK_VKR, CJ.LINK_EKR,CJ.NAME_VKR, CJ.CODE_EKR
	ORDER BY  
		P.LINK, CJ.LINK_VKR, CJ.LINK_EKR	

--*************************************************


	-- Удаление временной таблицы #s_j_c
	DROP TABLE #s_j_c

	----
	IF LEN(@CVAL4) <> 0 BEGIN

		set @varKScOtbor4 = 'Отбор Категорий: '

		select distinct RECORD INTO #T2 FROM dbo.OBJECT_VAR_KATEG WHERE LINK_UP = @NOTBORLINK4

		update A set @varKScOtbor4 = @varKScOtbor4 + ltrim(rtrim(B.NAME)) + ','
		from #T2 A inner join dbo.KATEG B on A.RECORD = B.LINK

		set @varKScOtbor4 = left(@varKScOtbor4,len(@varKScOtbor4)-1)
	END

	if not exists (Select typ_oper from #T1 where typ_oper = 1)
		insert into #T1 (SUBDIV, link_face, link_pays, name_pays, code_pays, typ_oper, name_vkr, code_ekr, summa, hours, days) values ('', 0,0,'','',1,'','',0,0,0)
	if not exists (Select typ_oper from #T1 where typ_oper = 2)
		insert into #T1 (SUBDIV, link_face, link_pays, name_pays, code_pays, typ_oper, name_vkr, code_ekr, summa, hours, days) values ('', 0,0,'','',2,'','',0,0,0)
	if not exists (Select typ_oper from #T1 where typ_oper = 3)
		insert into #T1 (SUBDIV, link_face, link_pays, name_pays, code_pays, typ_oper, name_vkr, code_ekr, summa, hours, days) values ('', 0,0,'','',3,'','',0,0,0)
	
	----
	IF LEN(@CVAL3) <> 0 BEGIN
		set @varKScOtbor3 = 'Отбор Подразделений: '
		update A set @varKScOtbor3 = @varKScOtbor3 + ltrim(rtrim(B.NAME)) + ','
		from dbo.OBJECT_VAR_SUBDIV_HEAD A inner join dbo.subdiv B on A.RECORD = B.LINK_UP
		where A.LINK_UP = @nOtborLink3

		set @varKScOtbor3 = left(@varKScOtbor3,len(@varKScOtbor3)-1)
	END

	----	
	set @varKSCountEmpl = (select count(link_face) from (select distinct link_face from #T1)T2)
	set @varKSPeriodStr = ''+ rtrim(convert(varchar(10),@varKSdDate1,104))+' - ' + rtrim(convert(varchar(10),@varKSdDate2,104))

	select 	[count] =  ltrim(rtrim(convert(varchar(10), coalesce(@varKSCountEmpl,0)))),
			[PERIOD] = coalesce(@varKSPeriodStr,''),
			[OTBOR] = ltrim(rtrim(coalesce(@varKScOtbor,''))),
			[OTBOR2] = coalesce(@varKScOtbor2,''),
			[OTBOR3] = coalesce(@varKScOtbor3,''),
			[OTBOR4] = coalesce(@varKScOtbor4,''),
			[OTBOR5] = (case when @status3 = 1 then 'Без учёта внешних совместителей' else '' end)


	DECLARE @Script varchar(8000)

	SET @Script = 
	'	
	select
		[typ_name] =  + (case when typ_oper = 1 then ''Начислено'' when typ_oper = 2 then ''Удержано'' else ''Отчислено'' end),
		* 
	from 
	(select
		' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV' ELSE '''''' END + ' AS SUBDIV,
		link_pays,
		name_pays,
		code_pays, 
		typ_oper, 
		name_vkr ' + case when coalesce(@detailed_SFIN,0) = 1 then '' else '=''Все''' end + ', 
		code_ekr ' + case when coalesce(@detailed_EKR,0) = 1 then '' else '=''Все''' end + ', 
		sum(summa) as summa,sum(hours) as hours, sum(days) as days,
		nn.sum_nDFL as sum_nDFL,
		ns.sum_STR as sum_STR
	from #T1 t
	left join  #NO_NDFL nn on nn.PLINK = t.link_pays and nn.code_vkr_n = t.name_vkr and   nn.code_ekr_n = t.code_ekr
	left join  #NO_STR ns on ns.PLINK = t.link_pays and ns.code_vkr_s = t.name_vkr and   ns.code_ekr_s = t.code_ekr
	where typ_oper = 1
	group by ' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV,' ELSE '' END + ' link_pays, typ_oper,name_pays,code_pays ' 
	+ case when coalesce(@detailed_SFIN,0) = 1 then ',t.name_vkr, nn.code_vkr_n, ns.code_vkr_s' else '' end  
	+ case when coalesce(@detailed_EKR,0) = 1 then ',t.code_ekr, nn.code_ekr_n, ns.code_ekr_s'  else '' end + ' , nn.sum_ndfl, ns.sum_STR
	) T2
	 order by ' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV,' ELSE '' END + 'typ_oper,code_pays' + case when coalesce(@detailed_SFIN,0) = 1 then ',name_vkr' else '' end + case when coalesce(@detailed_EKR,0) = 1 then ',code_ekr' else '' end

exec( @Script)



	SET @Script = 
	'	
	select
		[typ_name] =  + (case when typ_oper = 1 then ''Начислено'' when typ_oper = 2 then ''Удержано'' else ''Отчислено'' end),
		* 
	from 
	(select
		' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV' ELSE '''''' END + ' AS SUBDIV,
		link_pays,
		name_pays,
		code_pays, 
		typ_oper, 
		name_vkr ' + case when coalesce(@detailed_SFIN,0) = 1 then '' else '=''Все''' end + ', 
		code_ekr ' + case when coalesce(@detailed_EKR,0) = 1 then '' else '=''Все''' end + ', 
		sum(summa) as summa,sum(hours) as hours, sum(days) as days
	from #T1
	where typ_oper = 2
	group by ' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV,' ELSE '' END + ' link_pays, typ_oper,name_pays,code_pays ' 
	+ case when coalesce(@detailed_SFIN,0) = 1 then ',name_vkr' else '' end  
	+ case when coalesce(@detailed_EKR,0) = 1 then ',code_ekr' else '' end + '
	) T2
	 order by ' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV,' ELSE '' END + 'typ_oper,code_pays' + case when coalesce(@detailed_SFIN,0) = 1 then ',name_vkr' else '' end + case when coalesce(@detailed_EKR,0) = 1 then ',code_ekr' else '' end

	exec( @Script)

	SET @Script = 
	'	
	select
		[typ_name] =  + (case when typ_oper = 1 then ''Начислено'' when typ_oper = 2 then ''Удержано'' else ''Отчислено'' end),
		* 
	from 
	(select 
		' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV' ELSE '''''' END + ' AS SUBDIV,
		link_pays,
		name_pays,
		code_pays, 
		typ_oper, 
		name_vkr ' + case when coalesce(@detailed_SFIN,0) = 1 then '' else '=''Все''' end + ', 
		code_ekr ' + case when coalesce(@detailed_EKR,0) = 1 then '' else '=''Все''' end + ', 
		sum(summa) as summa,sum(hours) as hours, sum(days) as days
	from #T1
	where typ_oper = 3
	group by ' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV,' ELSE '' END + ' link_pays, typ_oper,name_pays,code_pays ' 
	+ case when coalesce(@detailed_SFIN,0) = 1 then ',name_vkr' else '' end  
	+ case when coalesce(@detailed_EKR,0) = 1 then ',code_ekr' else '' end + '
	) T2
	 order by ' + CASE WHEN @detailed_SUBDIV = 1 THEN 'SUBDIV,' ELSE '' END + 'typ_oper,code_pays' + case when coalesce(@detailed_SFIN,0) = 1 then ',name_vkr' else '' end + case when coalesce(@detailed_EKR,0) = 1 then ',code_ekr' else '' end

	exec( @Script)



	IF coalesce(@detailed_SFIN,0) = 1 and coalesce(@detailed_EKR,0) = 1
		SELECT 'Итого по группе' as TITLE,
			typ_oper, name_vkr, code_ekr, summa = sum(summa), sum_nDFL , sum_STR
		FROM #T1 t 
		left join (SELECT code_vkr_n , code_ekr_n, sum_nDFL = sum(sum_nDFL) from  #NO_NDFL  GROUP BY code_vkr_n , code_ekr_n) n on n.code_vkr_n = t.name_vkr and   n.code_ekr_n = t.code_ekr and typ_oper = 1
		left join  (SELECT code_vkr_s , code_ekr_s, sum_STR = sum(sum_STR) from  #NO_STR  GROUP BY code_vkr_s , code_ekr_s) s on s.code_vkr_s = t.name_vkr and   s.code_ekr_s = t.code_ekr and typ_oper = 1
		GROUP BY t.typ_oper, t.name_vkr, code_ekr, sum_nDFL , sum_STR
		ORDER BY typ_oper, name_vkr, code_ekr

	IF coalesce(@detailed_SFIN,0) = 1 and coalesce(@detailed_EKR,0) = 0
		SELECT 'Итого по группе' as TITLE,
			typ_oper, name_vkr, code_ekr = '', summa = sum(summa) , sum_nDFL , sum_STR
		FROM #T1 t 
		left join (SELECT code_vkr_n , sum_nDFL = sum(sum_nDFL) from  #NO_NDFL  GROUP BY code_vkr_n ) n on n.code_vkr_n = t.name_vkr  and typ_oper = 1
		left join  (SELECT code_vkr_s , sum_STR = sum(sum_STR) from  #NO_STR  GROUP BY code_vkr_s ) s on s.code_vkr_s = t.name_vkr  and typ_oper = 1
		GROUP BY t.typ_oper, t.name_vkr,sum_nDFL, sum_STR
		ORDER BY typ_oper, name_vkr


	IF coalesce(@detailed_SFIN,0) = 0 and coalesce(@detailed_EKR,0) = 1
		SELECT 'Итого по группе' as TITLE,
			typ_oper, name_vkr = '', code_ekr, summa = sum(summa),sum_nDFL, sum_STR
		FROM #T1 t 
		left join (SELECT code_ekr_n , sum_nDFL = sum(sum_nDFL) from  #NO_NDFL  GROUP BY code_ekr_n ) n on n.code_ekr_n = t.code_ekr  and typ_oper = 1
		left join  (SELECT code_ekr_s , sum_STR = sum(sum_STR) from  #NO_STR  GROUP BY code_ekr_s ) s on s.code_ekr_s = t.code_ekr  and typ_oper = 1
		GROUP BY typ_oper, code_ekr, sum_nDFL, sum_STR
		ORDER BY typ_oper, code_ekr


DROP TABLE #NO_NDFL
DROP TABLE #NO_STR

	IF coalesce(@detailed_SFIN,0) = 0 and coalesce(@detailed_EKR,0) = 0
		SELECT DISTINCT '' as TITLE, typ_oper, name_vkr = '', code_ekr = '', summa = 0,sum_nDFL = 0, sum_STR = 0 FROM #T1 GROUP BY typ_oper 

end









GO


GRANT EXECUTE ON dbo.[SD_REP_SVOD] TO PUBLIC

GO




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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE         PROCEDURE [dbo].SD_N_VACATION_TABLE1_SAVE
	@varKSparLINK			int,
	@varKSparORDERS		numeric(5,0),
	@varKSparSumma		numeric(12,2),
	@varKSparDATA1		datetime = null,
	@varKSparDATA2		datetime = null,
	@varKSparHOUR		numeric(10,2),
	@varKSparDAY		numeric(6,2),
	@LINK_KBK		INT,
	@SR_ZP			numeric(18,2),
	@KOEF_KBK		NUMERIC(18,4),
	@SUMMA_OLD		numeric(18,2),
	@SUMMA_NEW		numeric(18,2),
	@KOEF_IDX		NUMERIC(18,4)
AS
DECLARE @varKSERROR	tinyint, @varKStrancount	int,  @varKSSQLError int

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


IF @varKSparLINK IS NULL OR @varKSparLINK =0 OR  @varKSparORDERS IS NULL  OR  @varKSparDATA1 IS NULL or @varKSparDATA2 is null
BEGIN
	ROLLBACK
	RETURN 5
END

INSERT INTO SDOC_AVAC_TABLE1 WITH (ROWLOCK) (LINK_UP,ORDERS,DATE1,DATE2,DAYS,HOURS, SUMMA, LINK_KBK, SR_ZP, KOEF_KBK, SUMMA_OLD, SUMMA_NEW, KOEF_IDX) 
				VALUES (@varKSparLINK, @varKSparORDERS,@varKSparDATA1,@varKSparDATA2,@varKSparDAY,@varKSparHOUR,@varKSparSumma, @LINK_KBK, @SR_ZP, @KOEF_KBK, @SUMMA_OLD, @SUMMA_NEW, @KOEF_IDX)

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

WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0



GO


GRANT EXECUTE ON dbo.[SD_N_VACATION_TABLE1_SAVE] TO PUBLIC

GO


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


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

GO

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

SET NOCOUNT ON

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

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

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

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

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

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

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


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

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

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

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

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

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

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

declare @DEP_LINK int
exec dbo.xd_whats_zb @DEP_LINK output

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

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

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

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

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

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

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

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

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

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

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	END

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

CLOSE @CURSOR_EKR
DEALLOCATE @CURSOR_EKR

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

exec X_SALDO_CommitChanges

SET NOCOUNT OFF
Return 0
END

GO


GRANT EXECUTE ON dbo.[SA_CREATE_PP] TO PUBLIC

GO

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

GO

CREATE   PROCEDURE [dbo].[SD_REP_SVOD1]
	@varKSstart_date DATETIME, 
 	@varKSEND_DATE DATETIME,	
	@varKScVal1 char(1), @varKSnOtborLink1 int,		
	@varKScVal2 char(1), @varKSnOtborLink2 int,
	@varKScVal3 char(1), @varKSnOtborLink3 int,
	@CVAL4 CHAR(1), @NOTBORLINK4 INT	/* ОТБОР КАТЕГОРИЙ ДОЛЖНОСТЕЙ */,
	@Sort1 tinyint, @Sort2 tinyint,
	@ALL_DEP tinyint = NULL,
	@nCheck1 int = 1	/* Показывать начисления */,
	@nCheck2 int = 1	/* Показывать удержания */,
	@nCheck3 int = 1	/* Показывать отчисления */,
	@detailed_SFIN int = 0	/* Детализация по источникам финансирования */,
	@detailed_EKR int = 0	/* Детализация по ЭКР */,
	@AS_SALARY TINYINT = 0 /*Рассчитывать как ведомость на выплату*/	
AS
BEGIN

	--DECLARE @AS_SALARY TINYINT
	--SET @AS_SALARY = 0

	SET @Sort1 = COALESCE(@Sort1,0)
	SET @Sort2 = COALESCE(@Sort2,0)
	SET @ALL_DEP = COALESCE(@ALL_DEP,0)

	DECLARE @varKSSTART_YEAR DATETIME
	SELECT @varKSSTART_YEAR = dbo.DateBeginOfYear(@varKSstart_date)


	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output

	EXEC BufferClear
	DECLARE @varKSVKR_ID VARCHAR(100), @varKScWhere VARCHAR(1000)
	IF LEN(@varKScVal2) = 0 BEGIN
		SET @varKSVKR_ID = NULL
	END	 
	ELSE BEGIN
		SET @varKSVKR_ID = 'SALARY_SVOD1_VKR'
		SET @varKScWhere = 'LINK_UP = ' + STR(@varKSnOtborLink2)
		EXEC BufferPushTable 'OBJECT_VAR_SAL_SFIN', @varKSVKR_ID, 'RECORD', @varKScWhere
	END

	---
	create table #otbor_ekr (link int)
	insert into #otbor_ekr (link)
	select RECORD from dbo.OBJECT_VAR_KOSGU WHERE LEN(@varKScVal3) = 0 OR LINK_UP = @varKSnOtborLink3

	---
	DECLARE @varKSnYear INT
	SET @varKSnYear = YEAR(@varKSSTART_YEAR)

	CREATE TABLE #varKSEMPLS (LINK_EMPL INT)
	CREATE TABLE #varKSEMPLS1 (LINK_EMPL INT, LINK_VKR INT, LINK_EKR INT)
	CREATE TABLE #varKSEMPLS2 (LINK_EMPL INT, LINK_VKR INT, LINK_EKR INT)
	
	IF LEN(@varKScVal1) <> 0 
		INSERT INTO #varKSEMPLS (LINK_EMPL)
		SELECT DISTINCT RECORD 
		FROM
			dbo.OBJECT_VAR_EMPL A 
			LEFT JOIN DBO.SA_EMPLS_INFO(@varKSEND_DATE, DEFAULT) K ON K.empl_link = A.RECORD
		WHERE 
			LINK_UP = @varKSnOtborLink1
			AND
			(	
				LEN(@CVAL4) = 0 
				OR 
				K.KAT_LINK IN (SELECT RECORD FROM DBO.OBJECT_VAR_KATEG WHERE LINK_UP = @NOTBORLINK4)
			)
	ELSE
		INSERT INTO #varKSEMPLS (LINK_EMPL)
		SELECT DISTINCT E.LINK
		FROM 
			dbo.EMPL E 
			LEFT JOIN DBO.SA_EMPLS_INFO(@varKSEND_DATE, DEFAULT) K ON K.empl_link = E.LINK
		WHERE 
			((DEP_LINK = @DEP_LINK AND @ALL_DEP = 0) OR @ALL_DEP = 1)
			AND
			(	
				LEN(@CVAL4) = 0 
				OR 
				K.KAT_LINK IN (SELECT RECORD FROM DBO.OBJECT_VAR_KATEG WHERE LINK_UP = @NOTBORLINK4)
			)		

	CREATE CLUSTERED INDEX #varKSEMPLS_INDEX1 ON #varKSEMPLS (LINK_EMPL)
	---

	--	
	DECLARE @varKSDATE_01 DATETIME
	SET @varKSDATE_01 = DATEADD(DAY, -1, @varKSstart_date)

	--Временная рамка с начала года
	DECLARE @DATE_BEG DATETIME, @DATE_END DATETIME, @DATE_BEG_PREV_YEAR DATETIME
	SET @DATE_BEG = CASE WHEN @varKSSTART_YEAR < @varKSstart_date THEN @varKSSTART_YEAR ELSE @varKSstart_date END
	SET @DATE_END = (CASE WHEN @varKSDATE_01 > @varKSEND_DATE THEN @varKSDATE_01 ELSE @varKSEND_DATE END)
	SET @DATE_BEG_PREV_YEAR = dbo.DateBeginOfYear(@varKSSTART_YEAR-1)

	--Ведомости на выплату зарплаты
	CREATE TABLE #VEDOM_ZP (LINK INT)
	
	INSERT INTO #VEDOM_ZP (LINK)
	SELECT 
		D.LINK 
	FROM 
		dbo.SDOC D 
		INNER JOIN dbo.SDOC_VEDOM V ON V.LINK_UP = D.LINK 
	WHERE 
		LINK_DEP = @DEP_LINK
		AND @AS_SALARY = 1 
		AND TYP_PAYMENT = 1
		AND D.DATE_CALC BETWEEN @DATE_BEG_PREV_YEAR AND @DATE_END

	DECLARE @SALARY_PROV_OPT4 TINYINT
	SET @SALARY_PROV_OPT4 = dbo.sa_get_option_by_code('SALARY_PROV_OPT4')
	
	DECLARE @LINK_EKR_211 INT, @LINK_EKR_212 INT, @LINK_EKR_213 INT
	SET @LINK_EKR_211 = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '211')
	SET @LINK_EKR_212 = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '212')
	SET @LINK_EKR_213 = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '213')

	--Кусок журнала операций
	CREATE TABLE #SJC (LINK_EMPL INT, LINK_PAYS INT, SNAME VARCHAR(15), [NAME] VARCHAR(254), TYP_OPER TINYINT, WAY_CALC TINYINT, LINK_VKR INT, LINK_EKR INT, summa NUMERIC(20,2), PERIOD_BEGIN DATETIME, PERIOD_END DATETIME, LINK_DEP INT, [DAYS] INT)
	INSERT INTO #SJC 
		(LINK_EMPL, LINK_PAYS, SNAME, [NAME], TYP_OPER, WAY_CALC, LINK_VKR, LINK_EKR, summa, PERIOD_BEGIN, PERIOD_END, LINK_DEP, [DAYS])
	SELECT 
		SJC.LINK_EMPL,  SJC.LINK_PAYS, 
		P.SNAME, P.[NAME] + CASE WHEN ISNULL(A.LINK,0) > 0 AND (YEAR(PERIOD_BEGIN)* 100 + MONTH(PERIOD_BEGIN)) <> (YEAR(DATE_BEGIN)* 100 + MONTH(DATE_BEGIN)) THEN ' (в. ' + CONVERT(VARCHAR(4),YEAR(PERIOD_BEGIN)) + '/' +  + RIGHT(CONVERT(VARCHAR(3),100 + MONTH(PERIOD_BEGIN)),2) + ' за ' + CONVERT(VARCHAR(4),YEAR(DATE_BEGIN)) + '/' +  + RIGHT(CONVERT(VARCHAR(3),100 + MONTH(DATE_BEGIN)),2) + ')' ELSE '' END, 
		P.[OBJECT], P.WAY_CALC, 
		SJC.LINK_VKR, 
		--ISNULL(SJC.LINK_EKR,P.LINK_EKR), 
		CASE WHEN P.[OBJECT] = 3 THEN 
				CASE WHEN @SALARY_PROV_OPT4 = 0 THEN 
					CASE WHEN COALESCE(SJC.LINK_EKR,P.LINK_EKR,@LINK_EKR_213) = @LINK_EKR_211 THEN @LINK_EKR_213 ELSE COALESCE(SJC.LINK_EKR,P.LINK_EKR,@LINK_EKR_213) END
				ELSE 
					CASE WHEN COALESCE(SJC.LINK_EKR,P.LINK_EKR,@LINK_EKR_213) IN (@LINK_EKR_211, @LINK_EKR_212) THEN @LINK_EKR_213 ELSE COALESCE(SJC.LINK_EKR,P.LINK_EKR,@LINK_EKR_213) END				
				END
			ELSE COALESCE(SJC.LINK_EKR,P.LINK_EKR)
		END,	
		SJC.summa, 
		CASE WHEN COALESCE(A.LINK,0) = 0 THEN SJC.PERIOD_BEGIN ELSE (CASE WHEN SJC.DATE_BEGIN < SJC.PERIOD_BEGIN THEN SJC.DATE_BEGIN ELSE SJC.PERIOD_BEGIN END) END, 
		CASE WHEN COALESCE(A.LINK,0) = 0 THEN SJC.PERIOD_END ELSE (CASE WHEN SJC.DATE_END < SJC.PERIOD_END THEN SJC.DATE_END ELSE SJC.PERIOD_END END) END, 
		SJC.LINK_DEP, SJC.[DAYS]
	FROM
		dbo.PAYS P
		INNER JOIN dbo.CALCULATE_JURNAL SJC ON SJC.LINK_PAYS = P.LINK
		LEFT JOIN #VEDOM_ZP A ON A.LINK = SJC.LINK_DOC
	WHERE
		((SJC.LINK_DEP = @DEP_LINK AND @ALL_DEP = 0) OR @ALL_DEP = 1)
		AND -- отбор по источникам
		(
			@varKSVKR_ID IS NULL
			OR SJC.LINK_VKR IN (SELECT LINK FROM dbo.BufferGetTableByID(@varKSVKR_ID))
		)
		AND -- отбор по статьям
		( LEN(@varKScVal3) = 0 OR SJC.LINK_EKR IN (SELECT LINK FROM #otbor_ekr))
		AND
		(

			(
			--P.[OBJECT] = 2 AND COALESCE(A.LINK,0) = 0 AND YEAR(SJC.PERIOD_BEGIN) = YEAR(SJC.DATE_BEGIN) AND SJC.PERIOD_BEGIN >= @DATE_BEG AND SJC.PERIOD_END <= @DATE_END
			-- удержания. так красивей, но с остатком не стыкуется
			--всё, кроме выплаты зарплаты берем только по дате расчёта
			NOT (P.[OBJECT] = 2 AND COALESCE(A.LINK,0) > 0) AND SJC.PERIOD_BEGIN >= @DATE_BEG AND SJC.PERIOD_END <= @DATE_END			
			OR 
			--удержания. ДЛЯ ВЕДОМОСТЕЙ ОПЕРАЦИИ БЕРЕМ ПО ПЕРИОДУ РАСЧЕТА
			P.[OBJECT] = 2 AND COALESCE(A.LINK,0) > 0 AND (SJC.DATE_BEGIN >= @DATE_BEG AND SJC.DATE_BEGIN <= @DATE_END)
			)
		OR
			(	
				P.[OBJECT] = 2 AND COALESCE(A.LINK,0) > 0
				AND
				YEAR(SJC.DATE_BEGIN) = YEAR(@DATE_BEG)-1 --Выплаты зарплаты за прошлый год, сделанные в этом году
				AND 
				YEAR(SJC.PERIOD_BEGIN) = YEAR(@DATE_BEG) AND MONTH(SJC.PERIOD_BEGIN) <= MONTH(@DATE_BEG)			
			)
		)	

	--
	CREATE CLUSTERED INDEX #SJC_INDEX1 ON #SJC (LINK_EMPL)	

	--
	CREATE TABLE #T1( Link_Empl INT, TYP_OPER INT, WAY_CALC INT, LINK_VKR INT, LINK_EKR INT, summa NUMERIC(20,2) )
	--Начисленно и удержано с начала года до тек. месяца
	INSERT INTO #T1
	SELECT 
		SJC.LINK_EMPL, SJC.TYP_OPER, SJC.WAY_CALC, 
		LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN SJC.LINK_VKR ELSE 0 END), 
		LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN SJC.LINK_EKR ELSE 0 END), 
		ISNULL(SUM(SUMMA), 0.00)
	FROM 
		#SJC SJC INNER JOIN #varKSEMPLS E ON SJC.LINK_EMPL = E.LINK_EMPL
	WHERE 
			SJC.PERIOD_BEGIN >= @varKSSTART_YEAR 
		AND SJC.PERIOD_END <= @varKSDATE_01
		AND SJC.TYP_OPER IN (1,2)
	GROUP BY 
		SJC.LINK_EMPL, 
		(CASE WHEN @detailed_SFIN = 1 THEN SJC.LINK_VKR ELSE 0 END), 
		(CASE WHEN @detailed_EKR = 1 THEN SJC.LINK_EKR ELSE 0 END), 
		SJC.TYP_OPER, SJC.WAY_CALC
	HAVING 
		ISNULL(SUM(SUMMA), 0.00) <> 0	

	INSERT INTO #T1
	SELECT Link_Empl, TYP_OPER, 0, LINK_VKR, LINK_EKR, ISNULL(SUM(SUMMA), 0.00)
	FROM #T1 
	GROUP BY 
		Link_Empl, TYP_OPER, LINK_VKR, LINK_EKR
	HAVING 
		ISNULL(SUM(SUMMA), 0.00) <> 0	

	------------------------
	CREATE TABLE #T2( Link_Empl INT, TYP_OPER INT, WAY_CALC INT, LINK_VKR INT, LINK_EKR INT, summa NUMERIC(20,2) )
	--Начисленно и удержано с начала года по тек. месяц
	INSERT INTO #T2
	SELECT 
		SJC.LINK_EMPL, SJC.TYP_OPER, SJC.WAY_CALC, 
		LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN LINK_VKR ELSE 0 END), 
		LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN LINK_EKR ELSE 0 END), 
		ISNULL(SUM(SUMMA), 0.00)
	FROM 
		#SJC SJC INNER JOIN #varKSEMPLS E ON SJC.LINK_EMPL = E.LINK_EMPL
	WHERE 
			SJC.PERIOD_BEGIN >= @varKSSTART_YEAR
		AND SJC.PERIOD_END <= @varKSEND_DATE
		AND SJC.TYP_OPER IN (1,2)
	GROUP BY 
		SJC.LINK_EMPL, 
		(CASE WHEN @detailed_SFIN = 1 THEN LINK_VKR ELSE 0 END), 
		(CASE WHEN @detailed_EKR = 1 THEN LINK_EKR ELSE 0 END),		
		SJC.TYP_OPER, SJC.WAY_CALC
	HAVING 
		ISNULL(SUM(SUMMA), 0.00) <> 0		
	
	INSERT INTO #T2
	SELECT Link_Empl, TYP_OPER, 0, LINK_VKR, LINK_EKR, ISNULL(SUM(SUMMA), 0.00)
	FROM #T2 
	GROUP BY 
		Link_Empl, TYP_OPER, LINK_VKR, LINK_EKR
	HAVING 
		ISNULL(SUM(SUMMA), 0.00) <> 0	

	------------------------
	CREATE TABLE #T3( Link_Empl INT, TYP_OPER INT, WAY_CALC INT, LINK_VKR INT, LINK_EKR INT, summa NUMERIC(20,2) )
	----Все операции тек месяца
	INSERT INTO #T3 
	SELECT 
		SJC.LINK_EMPL, SJC.TYP_OPER, SJC.WAY_CALC, 
		LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN LINK_VKR ELSE 0 END), 
		LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN LINK_EKR ELSE 0 END), 	
		ISNULL(SUM(SUMMA), 0.00)
	FROM 
		#SJC SJC INNER JOIN #varKSEMPLS E ON SJC.LINK_EMPL = E.LINK_EMPL
	WHERE 
			SJC.PERIOD_BEGIN >= @varKSstart_date 
		AND SJC.PERIOD_END <= @varKSEND_DATE
	GROUP BY 
		SJC.LINK_EMPL, 
		(CASE WHEN @detailed_SFIN = 1 THEN LINK_VKR ELSE 0 END), 
		(CASE WHEN @detailed_EKR = 1 THEN LINK_EKR ELSE 0 END),
		SJC.TYP_OPER, SJC.WAY_CALC
	
	INSERT INTO #T3
	SELECT Link_Empl, TYP_OPER, 0, LINK_VKR, LINK_EKR, ISNULL(SUM(SUMMA), 0.00)
	FROM #T3 
	GROUP BY 
		Link_Empl, TYP_OPER, LINK_VKR, LINK_EKR
	HAVING 
		ISNULL(SUM(SUMMA), 0.00) <> 0	

	------------------------ Информация об остатках ----------------------------------
	CREATE TABLE #SAL_REMAIN (LINK_EMPL INT, LINK_VKR INT, LINK_EKR INT, SUMMA NUMERIC(18,2), NDFL NUMERIC(18,2) )

	INSERT INTO #SAL_REMAIN (LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA, NDFL)
	SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUM(SUMMA), SUM(NDFL)
	FROM
	( 
		SELECT 
			SR.LINK_EMPL, 
			LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN SR.LINK_VKR ELSE 0 END), 
			LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN SR.LINK_EKR ELSE 0 END),		
			SUMMA = SR.SUMMA, 
			NDFL = SR.NDFL
		FROM 
			dbo.SAL_REMAIN SR INNER JOIN #varKSEMPLS E ON SR.LINK_EMPL = E.LINK_EMPL
		WHERE 
			YEAR_SAL = @varKSnYear 
			AND (@varKSVKR_ID IS NULL OR LINK_VKR IN (SELECT LINK FROM dbo.BufferGetTableByID(@varKSVKR_ID) ))
			AND ( LEN(@varKScVal3) = 0 OR SR.LINK_EKR IN (SELECT LINK FROM #otbor_ekr))
		
		--Выплаты за прошлый год на погашение остатка прошлого года
		UNION ALL
		SELECT 
			SJC.LINK_EMPL, 
			LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN LINK_VKR ELSE 0 END), 
			LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN LINK_EKR ELSE 0 END), 	
			-SUMMA,
			NDFL = 0
		FROM 
			#SJC SJC INNER JOIN #varKSEMPLS E ON SJC.LINK_EMPL = E.LINK_EMPL
		WHERE
			@AS_SALARY = 1
			AND 
			YEAR(SJC.PERIOD_BEGIN) = YEAR(@DATE_BEG_PREV_YEAR)
	) T	
	GROUP BY 
		LINK_EMPL, LINK_VKR, LINK_EKR
	HAVING
		SUM(SUMMA) <> 0 OR SUM(NDFL) <> 0	


	-----------------------
	DECLARE @varKSCNT_N INT, @varKSCNT_U INT, @varKSCNT_O INT
	
	--
	CREATE TABLE #TMP_N (LINK_DEP1 INT, LINK_EMPL1 INT, NN VARCHAR(15), SN NUMERIC(15,2), LINK_VKR_N INT, LINK_EKR_N INT, way_calc tinyint, p tinyint )
	
	INSERT INTO #TMP_N 
	SELECT 
		SJC.LINK_DEP, SJC.LINK_EMPL, left(SJC.SNAME,15), SUMMA, 
		LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN SJC.LINK_VKR ELSE 0 END), 
		LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN SJC.LINK_EKR ELSE 0 END), 
		SJC.way_calc, 0
	FROM 
		#SJC SJC INNER JOIN #varKSEMPLS E ON SJC.LINK_EMPL = E.LINK_EMPL
	WHERE 
			SJC.TYP_OPER = 1 
		AND SJC.PERIOD_BEGIN >= @varKSstart_date AND SJC.PERIOD_END <= @varKSEND_DATE
		AND @nCheck1 = 1
				
	--UNION ALL
	/*Для вывода дней больничных в своде по организациям ЦБ*/
	--SELECT 
	--	SJC.LINK_DEP, SJC.LINK_EMPL, SJC.SNAME, [DAYS], 
	--	LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN SJC.LINK_VKR ELSE 0 END), 
	--	LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN SJC.LINK_EKR ELSE 0 END), 
	--	SJC.way_calc, 1
	--FROM 
	--	#SJC SJC INNER JOIN #varKSEMPLS E ON SJC.LINK_EMPL = E.LINK_EMPL
	--WHERE 
	--		SJC.TYP_OPER = 1 and SJC.way_calc in (13,20)
	--	AND PERIOD_BEGIN >= @varKSstart_date AND PERIOD_END <= @varKSEND_DATE
	--	AND @nCheck1 = 1		

	SET @varKSCNT_N = (SELECT COUNT(DISTINCT NN) FROM #TMP_N )

	------
	--UPDATE #TMP_N
	--SET  
	--	NN = rtrim(ltrim(NN))
	--	+ (CASE WHEN p=1 THEN ' Дни' ELSE '' END)
	--WHERE 
	--	LINK_EKR_N is not null and way_calc in (13,20) AND @ALL_DEP = 1
	------

	CREATE TABLE #TMP_U (LINK_DEP2 INT, LINK_EMPL2 INT, NU VARCHAR(100), SU NUMERIC(15,2), LINK_VKR_U INT, LINK_EKR_U INT)
	INSERT INTO #TMP_U
	SELECT 
		SJC.LINK_DEP, SJC.LINK_EMPL, left(SJC.[NAME],100), SJC.SUMMA,
		LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN SJC.LINK_VKR ELSE 0 END), 
		LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN SJC.LINK_EKR ELSE 0 END)		
	FROM 
		#SJC SJC INNER JOIN #varKSEMPLS E ON SJC.LINK_EMPL = E.LINK_EMPL
	WHERE 
			TYP_OPER = 2
		AND PERIOD_BEGIN >= @varKSstart_date AND PERIOD_END <= @varKSEND_DATE
		AND @nCheck2 = 1
		AND SJC.SUMMA <> 0
	
	SET @varKSCNT_U = (SELECT COUNT(DISTINCT NU) FROM #TMP_U )
	------
	
	CREATE TABLE #TMP_O (LINK_DEP3 INT, LINK_EMPL3 INT, NNO VARCHAR(15), SO NUMERIC(15,2), LINK_VKR_O INT, LINK_EKR_O INT)
	INSERT INTO #TMP_O 
	SELECT 
		SJC.LINK_DEP, SJC.LINK_EMPL, left(SJC.[SNAME],15), SJC.SUMMA,
		LINK_VKR = (CASE WHEN @detailed_SFIN = 1 THEN SJC.LINK_VKR ELSE 0 END), 
		LINK_EKR = (CASE WHEN @detailed_EKR = 1 THEN SJC.LINK_EKR ELSE 0 END)
	FROM 
		#SJC SJC INNER JOIN #varKSEMPLS E ON SJC.LINK_EMPL = E.LINK_EMPL
	WHERE 
			TYP_OPER = 3
		AND PERIOD_BEGIN >= @varKSstart_date AND PERIOD_END <= @varKSEND_DATE
		AND @nCheck3 = 1
		AND SJC.SUMMA <> 0		

	SET @varKSCNT_O = (SELECT COUNT(DISTINCT NNO) FROM #TMP_O )

	INSERT INTO #varKSEMPLS2
	SELECT DISTINCT LINK_EMPL, LINK_VKR, LINK_EKR FROM #T1 WHERE WAY_CALC = 0 AND LINK_EMPL IS NOT NULL AND SUMMA <> 0 
	UNION
	SELECT DISTINCT LINK_EMPL, LINK_VKR, LINK_EKR FROM #T2 WHERE WAY_CALC = 0 AND LINK_EMPL IS NOT NULL AND SUMMA <> 0
	UNION
	SELECT DISTINCT LINK_EMPL, LINK_VKR, LINK_EKR FROM #SAL_REMAIN WHERE (SUMMA <> 0 OR NDFL <> 0)
	UNION
	SELECT DISTINCT LINK_EMPL1, LINK_VKR_N, LINK_EKR_N FROM #TMP_N WHERE SN <> 0
	UNION
	SELECT DISTINCT LINK_EMPL2, LINK_VKR_U, LINK_EKR_U FROM #TMP_U WHERE SU <> 0
	UNION
	SELECT DISTINCT LINK_EMPL3, LINK_VKR_O, LINK_EKR_O FROM #TMP_O WHERE SO <> 0

	--
	CREATE INDEX #varKSEMPLS2_INDEX1 ON #varKSEMPLS2 (LINK_EMPL, LINK_VKR, LINK_EKR)	

	------------------------------------------------------------------------------
	CREATE TABLE #REST_B1(
		LINK_EMPL INT, LINK_VKR INT, LINK_EKR INT,
		BEG_PAY NUMERIC(20,2), BEG_TAX NUMERIC(20,2), 
		BEG_R NUMERIC(20,2), BEG_NDFL NUMERIC(20),
		END_PAY NUMERIC(20,2), END_TAX NUMERIC(20,2),	
		CURR_PAY NUMERIC(20,2), CURR_TAX NUMERIC(20,2),	
		[CURR_DED] NUMERIC(20,2)
	)

	INSERT INTO #REST_B1
	SELECT 
		DF.LINK_EMPL, DF.LINK_VKR, DF.LINK_EKR,
		 
		[BEG_PAY] = ISNULL(T11.SUMMA, 0.00), --Начисленно до тек. месяца
		[BEG_TAX] = ISNULL(T12.SUMMA, 0.00), --Удержано до тек. месяца

		[BEG_R] = ISNULL(DSR.SUMMA, 0.00), --Остаток на нач. года начисления
		[BEG_NDFL] = ISNULL(DSR.NDFL, 0.00), --Переплата на нач. года удержания

		[END_PAY] = ISNULL(T21.SUMMA, 0.00), --Нач. с нач. года по тек месяц
		[END_TAX] = ISNULL(T22.SUMMA, 0.00), --Удерж. с нач. года по тек месяц
		
		[CURR_PAY] = ISNULL(T31.SUMMA, 0.00), --Начисленно в тек месяце
		[CURR_TAX] = ISNULL(T32.SUMMA, 0.00),  --Удержано в тек месяце
		[CURR_DED] = ISNULL(T33.SUMMA, 0.00) --Отч. в тек месяце

	FROM 
		#varKSEMPLS2 DF
		LEFT JOIN (SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA) FROM #T1 WHERE TYP_OPER = 1 AND WAY_CALC = 0 GROUP BY LINK_EMPL, LINK_VKR, LINK_EKR) T11 ON DF.LINK_EMPL = T11.LINK_EMPL AND DF.LINK_VKR = T11.LINK_VKR AND DF.LINK_EKR = T11.LINK_EKR
		LEFT JOIN (SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA) FROM #T1 WHERE TYP_OPER = 2 AND WAY_CALC = 0 GROUP BY LINK_EMPL, LINK_VKR, LINK_EKR) T12 ON DF.LINK_EMPL = T12.LINK_EMPL AND DF.LINK_VKR = T12.LINK_VKR AND DF.LINK_EKR = T12.LINK_EKR

		LEFT JOIN (SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA), NDFL = SUM(NDFL) FROM #SAL_REMAIN GROUP BY LINK_EMPL, LINK_VKR, LINK_EKR) DSR ON DF.LINK_EMPL = DSR.LINK_EMPL AND DF.LINK_VKR = DSR.LINK_VKR AND DF.LINK_EKR = DSR.LINK_EKR

		LEFT JOIN (SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA) FROM #T2 WHERE TYP_OPER = 1 AND WAY_CALC = 0 GROUP BY LINK_EMPL, LINK_VKR, LINK_EKR) T21 ON DF.LINK_EMPL = T21.LINK_EMPL AND DF.LINK_VKR = T21.LINK_VKR AND DF.LINK_EKR = T21.LINK_EKR
		LEFT JOIN (SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA) FROM #T2 WHERE TYP_OPER = 2 AND WAY_CALC = 0 GROUP BY LINK_EMPL, LINK_VKR, LINK_EKR) T22 ON DF.LINK_EMPL = T22.LINK_EMPL AND DF.LINK_VKR = T22.LINK_VKR AND DF.LINK_EKR = T22.LINK_EKR

		LEFT JOIN (SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA) FROM #T3 WHERE TYP_OPER = 1 AND WAY_CALC = 0 GROUP BY LINK_EMPL, LINK_VKR, LINK_EKR) T31 ON DF.LINK_EMPL = T31.LINK_EMPL AND DF.LINK_VKR = T31.LINK_VKR AND DF.LINK_EKR = T31.LINK_EKR
		LEFT JOIN (SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA) FROM #T3 WHERE TYP_OPER = 2 AND WAY_CALC = 0 GROUP BY LINK_EMPL, LINK_VKR, LINK_EKR) T32 ON DF.LINK_EMPL = T32.LINK_EMPL AND DF.LINK_VKR = T32.LINK_VKR AND DF.LINK_EKR = T32.LINK_EKR
		LEFT JOIN (SELECT LINK_EMPL, LINK_VKR, LINK_EKR, SUMMA = SUM(SUMMA) FROM #T3 WHERE TYP_OPER = 3 AND WAY_CALC = 0 GROUP BY LINK_EMPL, LINK_VKR, LINK_EKR) T33 ON DF.LINK_EMPL = T33.LINK_EMPL AND DF.LINK_VKR = T33.LINK_VKR AND DF.LINK_EKR = T33.LINK_EKR

	CREATE TABLE #REST_B(
		LINK_EMPL INT, LINK_VKR INT, LINK_EKR INT, 
		REST_BEG NUMERIC(20,2), 
		REST_D NUMERIC(20,2),
		CURR_PAY NUMERIC(20,2), CURR_TAX NUMERIC(20,2),	
		[CURR_DED] NUMERIC(20,2)
	)
	
	INSERT INTO #REST_B
	SELECT 
		LINK_EMPL, LINK_VKR, LINK_EKR, 
		BEG_PAY - BEG_TAX + BEG_R AS REST_BEG, --сальдо на начало мес
		END_PAY - END_TAX + BEG_R AS REST_D, --сальдо на конец мес
		CURR_PAY, 
		CURR_TAX,
		CURR_DED
	FROM 
		#REST_B1
	WHERE 
		(BEG_PAY - BEG_TAX + BEG_R) <> 0
		OR (END_PAY - END_TAX + BEG_R) <> 0
		OR CURR_PAY <> 0
		OR CURR_TAX <> 0
		OR CURR_DED <> 0


	INSERT INTO #varKSEMPLS1
	SELECT DISTINCT LINK_EMPL, LINK_VKR, LINK_EKR FROM #REST_B
	UNION
	SELECT DISTINCT LINK_EMPL1, LINK_VKR_N, LINK_EKR_N FROM #TMP_N WHERE SN <> 0
	UNION
	SELECT DISTINCT LINK_EMPL2, LINK_VKR_U, LINK_EKR_U FROM #TMP_U WHERE SU <> 0
	UNION
	SELECT DISTINCT LINK_EMPL3, LINK_VKR_O, LINK_EKR_O FROM #TMP_O WHERE SO <> 0

	--
	CREATE CLUSTERED INDEX #varKSEMPLS1_INDEX1 ON #varKSEMPLS1 (LINK_EMPL, LINK_VKR, LINK_EKR)	


	CREATE TABLE #RES0
	(
		LINK_DEP INT,
		LINK_EMPL INT,
		LINK_VKR INT,
		LINK_EKR INT, 
		SVD_TN VARCHAR(15), 
		SVD_FIO VARCHAR(254),
		SVD_PODR VARCHAR(254),
		SUBDIV_CODE VARCHAR(10),
		S_SN NUMERIC(20,2), S_SU NUMERIC(20,2), S_SO NUMERIC(20,2),
		SVD_Saldo NUMERIC(20,2), REST_END NUMERIC(20,2),
		POST_CODE VARCHAR(10),
		POST_NAME VARCHAR(254)
	)
	INSERT INTO #RES0
	SELECT 
		EP.DEP_LINK,
		[LINK_EMPL] = EP.LINK,
		E.LINK_VKR, 
		E.LINK_EKR,
		[TN] 		= EP.TAB,
		[FIO] 		= dbo.ku_GetPersFio(EP.PERS_LINK),
		[SUBDIV] 	= EP.SUBDIV_NAME,
		[SUBDIV_CODE] = EP.SUBDIV_CODE,
		[CURR_PAY] = ISNULL(RB.CURR_PAY, 0.00),
		[CURR_TAX] = ISNULL(RB.CURR_TAX, 0.00),
		[S_SO] = ISNULL(RB.CURR_DED, 0.00),
		[SVD_Saldo] = ISNULL(RB.REST_BEG, 0.00),
		[REST_END] = ISNULL(RB.REST_D, 0.00),
		POST_CODE, POST_NAME 
	FROM 
		DBO.KU_EMPL_PLACING EP 
		INNER JOIN #varKSEMPLS1 E ON EP.LINK = E.LINK_EMPL
		LEFT OUTER JOIN #REST_B RB ON EP.LINK = RB.LINK_EMPL AND RB.LINK_VKR = E.LINK_VKR AND RB.LINK_EKR = E.LINK_EKR
	WHERE
		((EP.DEP_LINK = @DEP_LINK AND @ALL_DEP = 0) OR @ALL_DEP = 1)
	
	DECLARE 
		@varKSTABLE_PAY VARCHAR(120), @varKSTABLE_TAX VARCHAR(120), @varKSTABLE_DED VARCHAR(120), 
		@varKSTABLE_OUT VARCHAR(120), @varKSTABLE_OUT2 VARCHAR(120)
	EXEC X_GET_TABLE_NAME @varKSTABLE_PAY OUTPUT
	SELECT @varKSTABLE_TAX = @varKSTABLE_PAY + '_1', @varKSTABLE_OUT = @varKSTABLE_PAY + '_2', 
		@varKSTABLE_OUT2 = @varKSTABLE_PAY + '_3',
		@varKSTABLE_DED = @varKSTABLE_PAY + '_4'

	IF @ALL_DEP = 0 BEGIN
		EXEC M_CROSS_TABLE
			'LINK_EMPL1, LINK_VKR_N, LINK_EKR_N',
			'NN', 'VARCHAR(15)',
			'SN', 'NUMERIC(15,2)', 'SUM(SN) AS SN',
			'#TMP_N', @varKSTABLE_PAY

		EXEC M_CROSS_TABLE
			'LINK_EMPL2, LINK_VKR_U, LINK_EKR_U',
			'NU', 'VARCHAR(100)',
			'SU', 'NUMERIC(15,2)', 'SUM(SU) AS SU',
			'#TMP_U', @varKSTABLE_TAX
	
		EXEC M_CROSS_TABLE
			'LINK_EMPL3, LINK_VKR_O, LINK_EKR_O',
			'NNO', 'VARCHAR(15)',
			'SO', 'NUMERIC(15,2)', 'SUM(SO) AS SO',
			'#TMP_O', @varKSTABLE_DED
		
		EXEC ( '
		SELECT  T1.*, ISNULL(F.CODE,''Все'') AS SFIN_CODE, ISNULL(G.CODE,''Все'') AS EKR_CODE, T2.*, T3.*, T4.* INTO ' + @varKSTABLE_OUT2 + ' 
		FROM 
			#RES0 T1
			LEFT JOIN DBO.SAL_SFIN F ON F.LINK = T1.LINK_VKR
			LEFT JOIN DBO.KOSGU G ON G.LINK = T1.LINK_EKR
			LEFT OUTER JOIN ' + @varKSTABLE_PAY + ' T2 ON T1.LINK_EMPL = T2.LINK_EMPL1 AND T1.LINK_VKR = T2.LINK_VKR_N AND T1.LINK_EKR = T2.LINK_EKR_N
			LEFT OUTER JOIN ' + @varKSTABLE_TAX + ' T3 ON T1.LINK_EMPL = T3.LINK_EMPL2 AND T1.LINK_VKR = T3.LINK_VKR_U AND T1.LINK_EKR = T3.LINK_EKR_U
			LEFT OUTER JOIN ' + @varKSTABLE_DED + ' T4 ON T1.LINK_EMPL = T4.LINK_EMPL3 AND T1.LINK_VKR = T4.LINK_VKR_O AND T1.LINK_EKR = T4.LINK_EKR_O
		')
		
	END
	ELSE BEGIN

		EXEC M_CROSS_TABLE
			'LINK_DEP1, LINK_VKR_N, LINK_EKR_N',
			'NN', 'VARCHAR(15)',
			'SN', 'NUMERIC(15,2)', 'SUM(SN) AS SN',
			'#TMP_N', @varKSTABLE_PAY

		EXEC M_CROSS_TABLE
			'LINK_DEP2, LINK_VKR_U, LINK_EKR_U',
			'NU', 'VARCHAR(100)',
			'SU', 'NUMERIC(15,2)', 'SUM(SU) AS SU',
			'#TMP_U', @varKSTABLE_TAX
	
		EXEC M_CROSS_TABLE
			'LINK_DEP3, LINK_VKR_O, LINK_EKR_O',
			'NNO', 'VARCHAR(15)',
			'SO', 'NUMERIC(15,2)', 'SUM(SO) AS SO',
			'#TMP_O', @varKSTABLE_DED

		EXEC ( '
		SELECT  T1.*,  ISNULL(F.CODE,''Все'') AS SFIN_CODE, ISNULL(G.CODE,''Все'') AS EKR_CODE, T2.*, T3.*, T4.* INTO ' + @varKSTABLE_OUT2 + ' 
		FROM 
			(Select LINK_DEP, LINK_VKR, LINK_EKR, S_SN= SUM(S_SN), S_SU= SUM(S_SU), S_SO= SUM(S_SO), SVD_Saldo= SUM(SVD_Saldo), REST_END= SUM(REST_END) FROM #RES0 GROUP BY LINK_DEP, LINK_VKR, LINK_EKR) T1 
		LEFT JOIN DBO.SAL_SFIN F ON F.LINK = T1.LINK_VKR
		LEFT JOIN DBO.KOSGU G ON G.LINK = T1.LINK_EKR			
		LEFT OUTER JOIN ' + @varKSTABLE_PAY + ' T2 ON T1.LINK_DEP = T2.LINK_DEP1 AND T1.LINK_VKR = T2.LINK_VKR_N AND T1.LINK_EKR = T2.LINK_EKR_N
		LEFT OUTER JOIN ' + @varKSTABLE_TAX + ' T3 ON T1.LINK_DEP = T3.LINK_DEP2 AND T1.LINK_VKR = T3.LINK_VKR_U AND T1.LINK_EKR = T3.LINK_EKR_U
		LEFT OUTER JOIN ' + @varKSTABLE_DED + ' T4 ON T1.LINK_DEP = T4.LINK_DEP3 AND T1.LINK_VKR = T4.LINK_VKR_O AND T1.LINK_EKR = T4.LINK_EKR_O
		')

	END

	DECLARE @varKSSQL_STR VARCHAR(4000), @varKSFIELD_NAME VARCHAR(100), @varKSI int
	SET @varKSI=1
	WHILE @varKSI<=@varKSCNT_N BEGIN
		SET @varKSFIELD_NAME= 'NN_' + RTRIM(LTRIM(STR(@varKSI))) 
		SET @varKSSQL_STR = ' UPDATE ' + @varKSTABLE_OUT2 
			+ '  SET ' + @varKSFIELD_NAME + ' = (SELECT TOP 1 ' + @varKSFIELD_NAME 
			+ ' FROM ' + @varKSTABLE_PAY 
			+ ' WHERE ' + @varKSFIELD_NAME+ '  IS NOT NULL ) ' 
		EXEC (@varKSSQL_STR)
		SET @varKSFIELD_NAME= 'SN_' + RTRIM(LTRIM(STR(@varKSI))) 
		SET @varKSSQL_STR = ' UPDATE  ' + @varKSTABLE_OUT2 
			+ '  SET ' + @varKSFIELD_NAME + ' = 0
			     WHERE ' + @varKSFIELD_NAME+ '  IS NULL ' 
		EXEC (@varKSSQL_STR)
		SET @varKSI=@varKSI+1
	END
	IF @varKSCNT_N=0 BEGIN
		EXEC (' ALTER TABLE ' + @varKSTABLE_OUT2 + ' ADD NN_0 VARCHAR(15), SN_0 NUMERIC(15,2) ')
	END
		

	SET @varKSI=1
	WHILE @varKSI<=@varKSCNT_U BEGIN
		SET @varKSFIELD_NAME= 'NU_' + RTRIM(LTRIM(STR(@varKSI))) 
		SET @varKSSQL_STR= ' UPDATE ' + @varKSTABLE_OUT2 
			+ '  SET ' + @varKSFIELD_NAME + ' = (SELECT TOP 1 ' + @varKSFIELD_NAME 
			+ ' FROM ' + @varKSTABLE_TAX 
			+ ' WHERE ' + @varKSFIELD_NAME+ '  IS NOT NULL ) ' 
		EXEC (@varKSSQL_STR)
		SET @varKSFIELD_NAME= 'SU_' + RTRIM(LTRIM(STR(@varKSI))) 
		SET @varKSSQL_STR = ' UPDATE  ' + @varKSTABLE_OUT2 
			+ '  SET ' + @varKSFIELD_NAME + ' = 0
			     WHERE ' + @varKSFIELD_NAME+ '  IS NULL ' 
		EXEC (@varKSSQL_STR)
		SET @varKSI=@varKSI+1
	END
	IF @varKSCNT_U=0 BEGIN
		EXEC (' ALTER TABLE ' + @varKSTABLE_OUT2 + ' ADD NU_0 VARCHAR(100), SU_0 NUMERIC(15,2) ')
	END

	SET @varKSI=1
	WHILE @varKSI<=@varKSCNT_O BEGIN
		SET @varKSFIELD_NAME= 'NNO_' + RTRIM(LTRIM(STR(@varKSI))) 
		SET @varKSSQL_STR= ' UPDATE ' + @varKSTABLE_OUT2 
			+ '  SET ' + @varKSFIELD_NAME + ' = (SELECT TOP 1 ' + @varKSFIELD_NAME 
			+ ' FROM ' + @varKSTABLE_DED 
			+ ' WHERE ' + @varKSFIELD_NAME+ '  IS NOT NULL ) ' 
		EXEC (@varKSSQL_STR)
		SET @varKSFIELD_NAME= 'SO_' + RTRIM(LTRIM(STR(@varKSI))) 
		SET @varKSSQL_STR = ' UPDATE  ' + @varKSTABLE_OUT2 
			+ '  SET ' + @varKSFIELD_NAME + ' = 0
			     WHERE ' + @varKSFIELD_NAME+ '  IS NULL ' 
		EXEC (@varKSSQL_STR)
		SET @varKSI=@varKSI+1
	END
	IF @varKSCNT_O=0 BEGIN
		EXEC (' ALTER TABLE ' + @varKSTABLE_OUT2 + ' ADD NNO_1 VARCHAR(15) DEFAULT '''', SO_1 NUMERIC(15, 2) DEFAULT 0')
	END

	DECLARE @SCRIPT varchar(1000)

	IF @ALL_DEP = 0 begin

		set @SCRIPT = 'SELECT * FROM ' + @varKSTABLE_OUT2 + ' 
		ORDER BY ' + 
			LTRIM(RTRIM(CASE @Sort1 
				WHEN 1 THEN 'SUBDIV_CODE'
				WHEN 2 THEN 'SVD_PODR'
				WHEN 3 THEN 'SVD_TN' 
				WHEN 4 THEN 'SVD_FIO'
				ELSE ''
			END)) + 

			LTRIM(RTRIM(CASE @Sort2 
				WHEN 2 THEN (CASE WHEN @Sort1 <> 3 THEN ',SVD_TN' ELSE '' END)
				WHEN 3 THEN (CASE WHEN @Sort1 <> 4 THEN ',SVD_FIO' ELSE '' END)
				ELSE ''
			END))
			
			+ ',SFIN_CODE, EKR_CODE'

		EXEC (@SCRIPT)
	end
	ELSE
		EXEC (
		' SELECT DISTINCT R.*, DEP_NAME= D.[NAME], GRP_NAME = COALESCE(GRP.GRP_NAME,''Без группы'')  FROM ' + @varKSTABLE_OUT2+' R '
		+ ' INNER JOIN DEPARTMENTS D on R.LINK_DEP = D.LINK
		LEFT JOIN (select GRP_NAME= G.[NAME], D_LINK= REF.DEP_LINK
			from DEPARTMENT_GROUPS G inner join DEPARTMENT_GROUPS_REF REF on G.LINK = REF.GROUP_LINK
			where G.LINK = (SELECT MAX(REF1.GROUP_LINK) from DEPARTMENT_GROUPS_REF REF1 where REF1.DEP_LINK = REF.DEP_LINK)) GRP on D.LINK = GRP.D_LINK'
		+ ' order by COALESCE(GRP.GRP_NAME,''Без группы''), D.[NAME],SFIN_CODE, EKR_CODE'
		)

	EXEC (' DROP TABLE ' + @varKSTABLE_PAY)
	EXEC (' DROP TABLE ' + @varKSTABLE_TAX)
	EXEC (' DROP TABLE ' + @varKSTABLE_OUT2)
	EXEC BufferClear
END





GO


GRANT EXECUTE ON dbo.[SD_REP_SVOD1] TO PUBLIC

GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[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 @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)	

	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
		ISNULL(DATE2,@DATE) >= @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


--ВЕРНУТЬ ПРЕЖНИЙ ПЕРИОД РЕДАКТИРОВАНИЯ
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
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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

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

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

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



-- Таблица 2 (FROM)
SELECT BUDG_LEVEL  = case D.BUH_TYPE WHEN 1 then cast(replace(B.CODE_EL,'0','') as char(1)) else '6' end,
		KOD_UBP 	= case cast(replace(B.CODE_EL,'0','') as char(1)) when 1 then D.CODE_UBP else BUDG end,
		NAME_UBP	= D.FULL_NAME
from dbo.DEPARTMENTS D
left join dbo.KL_ADMIN_BS V WITH (NOLOCK) on V.LINK = D.VED_LINK
left join dbo.KL_BUDG_TYPE B WITH (NOLOCK) on V.Link_Budg = B.LINK
where D.LINK = @iDepLink


-- Таблица 3 (TO)
SELECT 	KOD_TOFK  = TOFK.CODE,
		NAME_TOFK = TOFK.FULL_NAME
from dbo.DEPARTMENTS D
inner join dbo.TREASURY TOFK on D.TOFK_LINK = TOFK.LINK
where D.LINK = @iDepLink



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

	SELECT  LINK 		 = RN.LINK,
			LINK_UP		 = RN.LINK,
			GUID_FK		 = '',
			DATE_RN		 = RN.[DATE],
			NOM_RN		 = RN.NUMBER,
			LS_PAY		 = RN.ACC_CODE,
			VID_OPER     = cast(RN.VID as char(1)),
			KOD_UBP		 = case @cCodeOpt when 1 then RN.DEP_UBP else '' end,
			NAME_UBP 	 = RN.DEP_FNAME, 
			INN_UBP		 = RN.DEP_INN,
			KPP			 = RN.DEP_KPP,
			KOD_TOFK	 = RN.TOFK_CODE,
			NAME_TOFK	 = RN.TOFK_NAME,
			CARD_NUM	 = RN.CARD_CODE, 
			DOL_RUK		 = case @iPostRuk when 1 then B.POST_NAME else '' end,
			NAME_RUK	 = B.SHORT_NAME,
			DOL_BUH		 = case @iPostGl when 1 then GB.POST_NAME else '' end,
			NAME_BUH 	 = GB.SHORT_NAME,
			DATE_POD	 = RN.DATE_PROV,
			SUMMA_ITOG	 = RN.SUMMA,
			SUMMA_R2	 = (SELECT SUM(SUMMA) from dbo.BB_DET_RETURN_table_view ZT where ZT.LINK_UP = RN.LINK)

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

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

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









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[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))

INSERT INTO 
	#SDOC_VEDOM_TABLE1 (LINK_UP, LINK_EMPL, ORDERS, DISBURS)
SELECT 
	LINK_UP, LINK_EMPL, ORDERS = MAX(ORDERS), DISBURS = SUM(DISBURS)
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

--Для каждой ведомости определяются КБК и корреспондирующие счета
--Но только если указан конкретный источник и ЭКР в ведомости
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), 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), 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)
	)

	DECLARE 
		@ORGNAME VARCHAR(254), @DEP_LINK INT, @ORGFULLNAME VARCHAR(2000),
		@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),
			@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)
	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),
		@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)),
		@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)

--Выводить вместо подписи лицевой счёт
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, 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, 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
)
	

	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(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),
		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)),
		LEFT(ISNULL(P.DOC_NUM, ''),20),
		LEFT(@ORGNAME,254), @ORGFULLNAME,
		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
	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.[XD_OSNOV_SEARCH]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[XD_OSNOV_SEARCH]

GO

CREATE PROCEDURE dbo.XD_OSNOV_SEARCH
	@intOsnovVid int,
	@strDocObjCode varchar(30),
	@strNum	varchar(25),
	@numSumm numeric(18,2),
	@strSummVid varchar(18),
	@strComment varchar(254),
	@datDate1 datetime,
	@datDate2 datetime,
	@iDepLink int = 0,
	@strWhere	VARCHAR (254) = ''
AS
/* Определить тип документа */
DECLARE @intOsnovVidType int,
		@strObjectCode varchar(30),
		@strOsnovVidName varchar(150),
		@intObjectLink int,
		@strParentObjLink int,
		@strEXEC	VARCHAR (8000)

IF OBJECT_ID ('TEMPDB..#DOC_OSNOV') IS NOT NULL
	EXEC ('DROP TABLE #DOC_OSNOV')

CREATE TABLE #DOC_OSNOV
		(
		LINK INT,
		NUMBER VARCHAR (30), 
		DAT VARCHAR (10),
		COMMENTS VARCHAR (254),
		SUMMA VARCHAR(18),
		VID_NAME VARCHAR (254),
		[TYPE]	INT,
		TP INT,
		[OBJECT] VARCHAR (30)
		) 

IF @strNum IS NULL
	SET @strNum = ''

SET @strNum = REPLACE(REPLACE(@strNum,'?','_'),'*','%')


IF @strComment IS NULL
	SET @strComment = ''

SET @strComment = REPLACE(REPLACE(@strComment,'?','_'),'*','%')

if @iDepLink = 0
	select @iDepLink = isnull(dbo.BK_GetDepZB(), dbo.GetOwnDepLink())

IF @intOsnovVid > 0 
BEGIN
	SELECT @intOsnovVidType = TYPE,@strObjectCode = OBJECT,@strOsnovVidName = NAME FROM BD_OSNOV_VID WHERE LINK = @intOsnovVid
	SELECT @intObjectLink = LINK FROM S_OBJECTS WHERE CODE = @strObjectCode
	
	INSERT INTO #DOC_OSNOV
	SELECT
		G.LINK,
		G.NUMBER,
		convert(char(10), G.DATE,104) as DAT,
		CONVERT(VARCHAR(254),
		ISNULL(G.COMMENT,'')) AS COMMENTS,
		CONVERT(VARCHAR(18), ISNULL(G.SUMMA,0.0)) AS SUMMA,
		@strOsnovVidName AS VID_NAME,
		@intOsnovVid AS TYPE,
		@intOsnovVidType AS TP,
		@strObjectCode AS OBJECT
	FROM dbo.G_PROV G
	WHERE @intOsnovVidType = 1
		AND G.DEP = @iDepLink 
		AND G.OBJECT = @intObjectLink AND G.[DATE] BETWEEN @datDate1 AND @datDate2
		AND (@strNum = '' OR G.NUMBER LIKE @strNum) 		
		AND (@strComment = '' OR G.COMMENT LIKE @strComment)
 		AND (@strSummVid = '' OR (@strSummVid = 'равно' AND G.SUMMA = @numSumm)
							   OR (@strSummVid = 'меньше или равно' AND G.SUMMA <= @numSumm)
							   OR (@strSummVid = 'меньше' AND G.SUMMA < @numSumm)
							   OR (@strSummVid = 'больше или равно' AND G.SUMMA >= @numSumm)
 							   OR (@strSummVid = 'больше' AND G.SUMMA > @numSumm))
	
	UNION ALL

	SELECT
		S.LINK,
		S.NUMBER,
		convert(char(10),S.DATE,104) as DAT,
		CONVERT(VARCHAR(254), ISNULL(S.COMMENTARY,'')) AS COMMENTS,
		'' AS SUMMA,
		@strOsnovVidName AS VID_NAME,
		@intOsnovVid AS TYPE,
		@intOsnovVidType AS TP,
		@strObjectCode AS OBJECT		
	FROM dbo.SDOC S
	WHERE @intOsnovVidType = 2
		AND S.OBJECT = @intObjectLink AND S.[DATE] BETWEEN @datDate1 AND @datDate2
		AND S.LINK_DEP = @iDepLink
		AND (@strNum = '' OR S.NUMBER LIKE @strNum) 		
		AND (@strComment = '' OR S.COMMENTARY LIKE @strComment)
	
	UNION ALL
	
	SELECT
		O.LINK,
		O.NUMBER,
		convert(char(10),
		O.DATE,104) as DAT,
		CONVERT(VARCHAR(254), ISNULL(O.COMMENT,'')) AS COMMENTS,
	   '' AS SUMMA,
	   @strOsnovVidName AS VID_NAME,
	   @intOsnovVid AS TYPE,
	   @intOsnovVidType AS TP,
	   @strObjectCode AS OBJECT		
	FROM dbo.OSNOV_OTHER O
	WHERE @intOsnovVidType = 3
		AND O.TYPE_LINK = @intOsnovVid AND O.[DATE] BETWEEN @datDate1 AND @datDate2
		AND O.DEP = @iDepLink
		AND (@strNum = '' OR O.NUMBER LIKE @strNum) 		
		AND (@strComment = '' OR O.COMMENT LIKE @strComment)
END
ELSE
BEGIN
	IF EXISTS(SELECT * FROM S_OBJECTS WHERE CODE = @strDocObjCode)
		BEGIN	
			SELECT @strParentObjLink = LINK FROM S_OBJECTS WHERE CODE = @strDocObjCode	

			INSERT INTO #DOC_OSNOV
			SELECT G.LINK,cast(G.NUMBER as varchar(25)) as NUMBER,convert(char(10),G.DATE,104) as DAT, CONVERT(VARCHAR(254),ISNULL(G.COMMENT,'')) AS COMMENTS,
				   CONVERT(VARCHAR(18),ISNULL(G.SUMMA,0.0)) AS SUMMA, (SELECT LTRIM(RTRIM(NAME)) FROM S_OBJECTS WHERE LINK = G.OBJECT) AS VID_NAME,	
				   (SELECT LINK FROM dbo.OSNOV_VID WHERE OBJECT = (SELECT CODE FROM S_OBJECTS WHERE LINK = G.OBJECT)) AS TYPE, 1 AS TP,
					 (SELECT CODE FROM S_OBJECTS WHERE LINK = G.OBJECT) AS OBJECT		
			FROM G_PROV G WHERE G.OBJECT IN (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE IN 
			(SELECT OBJECT FROM dbo.OSNOV_VID WHERE LINK IN (SELECT LINK_OTHER FROM DOC_NASTR_T3 WHERE LINK_UP = @strParentObjLink)))
			 	AND G.[DATE] BETWEEN @datDate1 AND @datDate2
				AND G.DEP = @iDepLink
				AND (@strNum = '' OR G.NUMBER LIKE @strNum) 		
				AND (@strComment = '' OR G.COMMENT LIKE @strComment)

			UNION

			SELECT S.LINK,cast(S.NUMBER as varchar(25)) as NUMBER,convert(char(10),S.DATE,104) as DAT, CONVERT(VARCHAR(254),ISNULL(S.COMMENTARY,'')) AS COMMENTS,
				   '' AS SUMMA,(SELECT LTRIM(RTRIM(NAME)) FROM S_OBJECTS WHERE LINK = S.OBJECT) AS VID_NAME,
					   (SELECT LINK FROM dbo.OSNOV_VID WHERE OBJECT = (SELECT CODE FROM S_OBJECTS WHERE LINK = S.OBJECT)) AS TYPE, 2 AS TP,
					  (SELECT CODE FROM S_OBJECTS WHERE LINK = S.OBJECT) AS OBJECT		
				FROM SDOC S WHERE S.OBJECT IN (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE IN 
				(SELECT OBJECT FROM dbo.OSNOV_VID WHERE LINK IN (SELECT LINK_OTHER FROM DOC_NASTR_T3 WHERE LINK_UP = @strParentObjLink)))
				AND S.[DATE] BETWEEN @datDate1 AND @datDate2
				AND S.LINK_DEP = @iDepLink
				AND (@strNum = '' OR S.NUMBER LIKE @strNum) 		
				AND (@strComment = '' OR S.COMMENTARY LIKE @strComment)

			UNION

			SELECT O.LINK,cast(O.NUMBER as varchar(25)) as NUMBER,convert(char(10),O.DATE,104) as DAT, CONVERT(VARCHAR(254),ISNULL(O.COMMENT,'')) AS COMMENTS,
				   '' AS SUMMA,(SELECT NAME FROM dbo.OSNOV_VID WHERE LINK = O.TYPE_LINK) AS VID_NAME,O.TYPE_LINK AS TYPE,3 AS TP, 
					(SELECT OBJECT FROM dbo.OSNOV_VID WHERE LINK =O.TYPE_LINK) AS OBJECT
			FROM dbo.OSNOV_OTHER O WHERE O.TYPE_LINK IN (SELECT LINK_OTHER FROM DOC_NASTR_T3 WHERE LINK_UP = @strParentObjLink) AND O.[DATE] BETWEEN @datDate1 AND @datDate2
				AND O.DEP = @iDepLink
				AND (@strNum = '' OR O.NUMBER LIKE @strNum) 		
				AND (@strComment = '' OR O.COMMENT LIKE @strComment)

		END
	ELSE
		BEGIN
			INSERT INTO #DOC_OSNOV
			SELECT G.LINK,G.NUMBER,convert(char(10),G.DATE,104) as DAT, CONVERT(VARCHAR(254),ISNULL(G.COMMENT,'')) AS COMMENTS,
			   CONVERT(VARCHAR(18),ISNULL(G.SUMMA,0.0)) AS SUMMA,(SELECT LTRIM(RTRIM(NAME)) FROM S_OBJECTS WHERE LINK = G.OBJECT) AS VID_NAME,
			   (SELECT LINK FROM dbo.OSNOV_VID WHERE OBJECT = (SELECT CODE FROM S_OBJECTS WHERE LINK = G.OBJECT)) AS TYPE, 1 AS TP,
			   (SELECT CODE FROM S_OBJECTS WHERE LINK = G.OBJECT) AS OBJECT		
			FROM dbo.G_PROV G WHERE G.[DATE] BETWEEN @datDate1 AND @datDate2
			AND G.OBJECT NOT IN (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'SHABLON_DOCUMENTS_PROV')
			AND G.DEP = @iDepLink
			AND (@strNum = '' OR G.NUMBER LIKE @strNum) 		
			AND (@strComment = '' OR G.COMMENT LIKE @strComment)
	 		AND (@strSummVid = '' OR (@strSummVid = 'равно' AND G.SUMMA = @numSumm)
								   OR (@strSummVid = 'меньше или равно' AND G.SUMMA <= @numSumm)
								   OR (@strSummVid = 'меньше' AND G.SUMMA < @numSumm)
								   OR (@strSummVid = 'больше или равно' AND G.SUMMA >= @numSumm)
	 							   OR (@strSummVid = 'больше' AND G.SUMMA > @numSumm))
		END
		
	END	

	SET @strEXEC = 'SELECT A1.* FROM #DOC_OSNOV A1'

	IF ISNULL (@strWhere, '') <> ''
		SET @strEXEC = @strEXEC + ' WHERE ' + LTRIM (@strWhere)

	EXEC (@strEXEC)

	DROP TABLE #DOC_OSNOV	

GO

GRANT EXECUTE ON dbo.[XD_OSNOV_SEARCH] 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 
	@varKSnLink 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 @varKSnLink IS NOT NULL AND NOT EXISTS (SELECT * FROM @SPISOK_VEDOM WHERE LINK = @varKSnLink)
	INSERT INTO @SPISOK_VEDOM (LINK) VALUES (@varKSnLink)

IF @BUFFER_ID IS NOT NULL
	SET @varKSnLink = NULL
IF COALESCE((SELECT COUNT(*) FROM @SPISOK_VEDOM),0) =1
	SET @varKSnLink = (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))

INSERT INTO 
	#DOCUMENTS_DED_PR_TABLE_DGH1 (LINK, PERS_LINK, FIO, ORDERS, DISBURS)
SELECT 
	D.LINK, D.PERS_LINK, FIO,  ORDERS = MAX(d.ORDERS), DISBURS = SUM(d.DISBURS)
FROM 
	dbo.DOCUMENTS_DED_PR_TABLE_DGH D
WHERE 
	(D.LINK = @varKSnLink AND @varKSnLink IS NOT NULL
	OR
	D.LINK IN (SELECT LINK FROM @SPISOK_VEDOM))
GROUP BY 
	LINK, PERS_LINK, FIO

--	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	@varKSres 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), 
		 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 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)
)	

	DECLARE 
		@varKSORGNAME VARCHAR(254), @varKSDEP_LINK INT, @ORGFULLNAME VARCHAR(2000),
		@varKSDOC_DATE DATETIME, @varKSDOC_DATE1 varchar(10), @varKSDOC_NUM VARCHAR(60), 
		@varKSKASSIR VARCHAR(254), @varKSKASS_POST VARCHAR(254),
		@varKSDIV_NAME VARCHAR(254), @varKSDIV_CODE VARCHAR(10),
		@varKSTI_NAME VARCHAR(254), @varKSTI_CODE VARCHAR(10),
		@varKSVR_NAME VARCHAR(254), @varKSVR_CODE VARCHAR(10),
		@varKSNAME_PAY VARCHAR(254), @varKSCODE_PAY VARCHAR(10), @varKSNAME_PAYR VARCHAR(254),
		@varKSDATE_BEGIN DATETIME, @varKSDATE_END DATETIME,
		@varKSMonth VARCHAR(20), @varKSYear VARCHAR(4),
		@varKSDEP_ACCT VARCHAR(30),
		@varKSCARD_LINK int,
		@DEP_INN VARCHAR(12), @DEP_KPP VARCHAR(9), @DEP_OKPO VARCHAR(20), @DEP_OGRN VARCHAR(13)
				

	SELECT top 1
			@varKSORGNAME 	= DEP.NAME , 
			@ORGFULLNAME  = LEFT(DEP.[FULL_NAME],2000),
			@varKSDEP_LINK 	= DEP.LINK,
			@DEP_INN = INN, @DEP_KPP = KPP, @DEP_OKPO = OKPO, @DEP_OGRN = OGRN
	FROM DICTIONARY_DEPARTMENT DEP, USER_DEP UI WHERE DEP.LINK = UI.DEP_LINK

	SELECT top 1
		@varKSDOC_DATE = [DATE], @varKSDOC_DATE1 = convert(varchar(10), [DATE], 103), @varKSDOC_NUM = NUMBER,
		@varKSKASSIR = ISNULL(NAME_EMPL, 0),
		@varKSKASS_POST = (SELECT POST_NAME FROM dbo.KU_EMPL_PLACING EP WHERE EP.LINK = ISNULL(D.REF_EMPL, 0) ),
		@varKSDIV_NAME = ISNULL(NAME_FKR_D, ''), @varKSDIV_CODE = ISNULL(CODE_FKR_D, ''),
		@varKSTI_NAME = ISNULL(NAME_FKR_T, ''), @varKSTI_CODE = ISNULL(CODE_FKR_T, ''),
		@varKSVR_NAME = ISNULL(NAME_FKR_E, ''), @varKSVR_CODE = ISNULL(CODE_FKR_E, ''),
		@varKSNAME_PAY = ISNULL(NAME_PAY, ''), @varKSCODE_PAY = ISNULL(CODE_PAY, ''),  
		@varKSNAME_PAYR = ISNULL(NAME_PAYROLL, ''),
		@varKSDATE_BEGIN = dbo.ConvertDMY2Date(1, month_base, year_base),
		@varKSYear = YEAR_BASE,
		@varKSMonth = (SELECT m.mon FROM MONTHS M WHERE M.NUM = D.month_base),
		@varKSCARD_LINK = CARD_LINK
 	FROM DOCUMENTS_DED_PR_DGH D LEFT OUTER JOIN BI_DICTION_VKR F ON D.LINK_VKR = F.LINK_KBK
	WHERE 
		@varKSnLink IS NOT NULL AND D.LINK = @varKSnLink
		OR
		D.LINK = (SELECT TOP 1 LINK FROM DBO.BUFFER WHERE ID = @BUFFER_ID)

	SELECT 	@varKSDATE_END = dbo.DateEndOfMonth(@varKSDATE_BEGIN)

	SELECT PERS_LINK, LINK_DOC, LINK_EKR, SUM(SUMMA) AS SUMM
	INTO #SUM_EKR
 	FROM DBO.CALCULATE_JURNAL
	WHERE LINK_DOC = @varKSnLink
	GROUP BY PERS_LINK, LINK_DOC, LINK_EKR 

	INSERT INTO @varKSres
	(
		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, BANK_LINK, BANK_NAME, BIK, DEP_ACCT,
		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
	)
	SELECT 
		@varKSnLink, 
		@varKSDOC_DATE, @varKSDOC_DATE1, @varKSDOC_NUM, 
		@varKSKASSIR, @varKSKASS_POST,
		@varKSDIV_NAME, @varKSDIV_CODE,
		@varKSTI_NAME, @varKSTI_CODE,
		@varKSVR_NAME, @varKSVR_CODE,
		@varKSNAME_PAYR,
		@varKSNAME_PAY, @varKSCODE_PAY,
		@varKSDATE_BEGIN, @varKSDATE_END, 
		@varKSMonth, @varKSYear,
		D.PERS_LINK, 
        '',
		dbo.ku_GetPersFIO(D.PERS_LINK),
		P.FM, P.IM, P.OT,
		D.FIO,
		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 = @varKSDEP_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),
		'Внештатный сотрудник',
		ISNULL(P.DOC_NUM, ''),
		@varKSORGNAME, @ORGFULLNAME,
		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 
    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 = @varKSCARD_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 = @varKSnLink AND @varKSnLink 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 @varKSres 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 @varKSres SET SUM_ALL = (SELECT SUM(SUMMA) FROM @varKSres)
	UPDATE @varKSres SET COUNT_OP = (SELECT COUNT(*)  FROM @varKSres)

	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 
		@varKSres 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 @varKSres
	GROUP BY NDOG_SB, NOSB, NFSB
	ORDER BY 1, 2, 3
	
	SELECT @varKSORGNAME 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_1NDFL2009]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SD_REP_1NDFL2009]

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

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

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

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

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

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

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

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

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

---

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

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


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


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


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

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

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

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

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

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



		SET @I=@I+1
	END		

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

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

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

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


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

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

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

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

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


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

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

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

	DELETE FROM  #MONTHES2
	DELETE FROM  #MONTHES


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

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

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




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

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

		SET @varKSI = @varKSI + 1
	END

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

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

	SET @I=1

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

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


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

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

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

	EXEC (@SQLS1) 	

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

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

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

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

		DELETE FROM  #MONTHES2
		DELETE FROM  #MONTHES

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

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

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

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

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


	END

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

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



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

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

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

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

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

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


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



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


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

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


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

	EXEC dbo.BufferClear

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


GO


GRANT EXECUTE ON dbo.[SD_REP_1NDFL2009] TO PUBLIC

GO



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

GO

CREATE PROCEDURE [dbo].VX_UPGRADE_CLEAR
AS

--
--Удалить все временные таблицы
DECLARE @Cur1 CURSOR, @TAB_NAME VARCHAR(254), @SQL VARCHAR(1000)

SET @Cur1 = CURSOR FORWARD_ONLY

FOR SELECT NAME FROM SYSOBJECTS WHERE XTYPE = 'U' AND name LIKE '%[_]U'

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

		SET @SQL = 'DROP TABLE ' + @TAB_NAME
		EXECUTE(@SQL)

	END

	FETCH NEXT FROM @Cur1 INTO @TAB_NAME
END

CLOSE @Cur1
DEALLOCATE @Cur1

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

if exists (select * from dbo.sysobjects where id = object_id(N'[object_values]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('object_values')

if exists (select * from dbo.sysobjects where id = object_id(N'[object_var_values]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('object_var_values')

if exists (select * from dbo.sysobjects where id = object_id(N'[object_property]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('object_property')

if exists (select * from dbo.sysobjects where id = object_id(N'[s_navigator]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('s_navigator')

if exists (select * from dbo.sysobjects where id = object_id(N'[object_var]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('object_var')

if exists (select * from dbo.sysobjects where id = object_id(N'[s_property]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('s_property')

if exists (select * from dbo.sysobjects where id = object_id(N'[s_permissions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('s_permissions')

if exists (select * from dbo.sysobjects where id = object_id(N'[s_dbobjects]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('s_dbobjects')

if exists (select * from dbo.sysobjects where id = object_id(N'[s_tables]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('s_tables')

if exists (select * from dbo.sysobjects where id = object_id(N'[s_release]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('s_release')

if exists (select * from dbo.sysobjects where id = object_id(N'[s_objects]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DBCC DBREINDEX ('s_objects')


----Удалить все временные талицы, заканчивающиеся на _U
--DECLARE @TABLE_NAME VARCHAR(256), @SQL_SCRIPT VARCHAR(4000)
--WHILE EXISTS (SELECT NAME FROM SYS.TABLES WHERE RIGHT(NAME,2) = '[_]U')
--BEGIN

--	SELECT @TABLE_NAME = NAME FROM SYS.TABLES WHERE RIGHT(NAME,2) = '[_]U'

--	SET @SQL_SCRIPT = '
--	IF exists(select * from sysobjects where id = object_id(''[dbo].[' + @TABLE_NAME + ']'') and OBJECTPROPERTY(id, N''IsUserTable'') = 1)
--		drop table [dbo].[' + @TABLE_NAME + ']'

--	PRINT @SQL_SCRIPT
--	EXEC (@SQL_SCRIPT)

--	SET @TABLE_NAME = LEFT(@TABLE_NAME,LEN(@TABLE_NAME)-2)

--	SET @SQL_SCRIPT = '
--	if exists (select * from dbo.sysobjects where id = object_id(N'''+@TABLE_NAME+''') and OBJECTPROPERTY(id, N''IsUserTable'') = 1)
--		DBCC DBREINDEX (''' + @TABLE_NAME + ''')'
		
--	PRINT @SQL_SCRIPT
--	EXEC (@SQL_SCRIPT)
--END


GO


GRANT EXECUTE ON dbo.[VX_UPGRADE_CLEAR] TO PUBLIC

GO

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

GO
CREATE    PROCEDURE dbo.SD_REP_1NDFL
	@varKScYear VARCHAR(4),
	@varKSnLinkEmpl INT = NULL,
	@varKSnLinkPers INT = NULL
AS BEGIN
	DECLARE @varKSnYear INT
	SET @varKSnYear = CAST(@varKScYear AS INT)
	--DECLARE @varKSnLinkPers int
	
		
	IF @varKSnLinkPers IS NULL
		SET @varKSnLinkPers = (SELECT TOP 1 PERS_LINK FROM dbo.EMPL WHERE LINK = @varKSnLinkEmpl)

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output

	SELECT 
		ISNULL((SELECT TOP 1 DD3.CODE FROM dbo.DEPARTMENTS DD3 WHERE DD3.LINK = DD.IMNS_LINK), '') AS NALOG,
		ISNULL(INN, '') AS INN,
		ISNULL(KPP, '') AS KPP,
		ISNULL(OKATO, '') AS OKATO,
		ISNULL(OKTMO, '')AS OKTMO,
		ISNULL(FULL_NAME, '') AS FULL_NAME
	INTO #DEP
	FROM dbo.DEPARTMENTS DD
	WHERE DD.link = @DEP_LINK

	DECLARE @Today INT
	SET  @Today = (CASE WHEN (Select TOP 1 YEAR(WORKDATE) from USER_INFO WHERE DEP_LINK = @DEP_LINK) = @varKSnYear 
			THEN (Select TOP 1 Month(WORKDATE) from USER_INFO WHERE DEP_LINK = @DEP_LINK) 
			ELSE 12 END)

	CREATE TABLE #RES0 (
		LINK_FACE INT,
		INNFIZ VARCHAR(20),
		NUMB_SERT VARCHAR(20),
		STATUS VARCHAR(1),
		FM VARCHAR(254),
		IM VARCHAR(254),
		OT VARCHAR(254),
		KDVD VARCHAR(4),
		SERNOM VARCHAR(254), 
		BIRTH DATETIME,
		GRAZD VARCHAR(3),
		KSTR VARCHAR(3),
		LINK_ADR INT,
		IND_ADR VARCHAR(10),
		REGION VARCHAR(4),
		RAION VARCHAR(254),
		GOROD VARCHAR(254),
		NASEL VARCHAR(254),
		STREET VARCHAR(254),
		HOUSE VARCHAR(20),
		KORP VARCHAR(10),
		FLAT VARCHAR(10),
		HAS_VICHET TINYINT,
		HAS300 TINYINT,
		HAS600 TINYINT,
		HAS400 TINYINT,
		HAS500 TINYINT,
		HAS3000 TINYINT,
		CHILDREN INT,
		DOLG_NP NUMERIC(20,2),
		DOLG_NA NUMERIC(20,2),
		OLD13 NUMERIC(20,2),
		DATE_BEG DATETIME,
		SNN NUMERIC(8,0), SNU NUMERIC(8,0),
		DOLG_NPEND NUMERIC(8,0), DOLG_NAEND NUMERIC(8,0) 
	)

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

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

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


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

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

	Declare @SJC table (LINK_FACE int,PERS_LINK int, link_empl int, link_pays int, link_vkr int, link_ekr int, typ_per tinyint, typ_oper tinyint, summa numeric(18,2), period_begin datetime, date1 datetime, link_dep int, CODE_INC varchar(5))

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

			)
		AND JC.LINK_DEP = @DEP_LINK 

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

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

	---
	CREATE TABLE #MONTHES (MONTH INT, SUMMA NUMERIC(18,2), CODE_DED VARCHAR(10) )
	DECLARE @varKSI INT
	SET @varKSI = 1
	WHILE @varKSI < 13 BEGIN
		INSERT INTO #MONTHES
		SELECT @varKSI, V.SUMMA, DTD.SNAME
		FROM 
			dbo.NDFL_PHYS_PERS_DED_VAL(@varKSnLinkPers, @varKSI, @varKSnYear) V
			INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION DTD ON DTD.LINK = V.REF_PAY

		SET @varKSI = @varKSI + 1
	END

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

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

	DELETE FROM  #MONTHES2
	DELETE FROM  #MONTHES


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

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

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




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

		SET @varKSI = 1
		WHILE @varKSI < 13 BEGIN
			INSERT INTO #MONTHES
			SELECT @varKSI, V.SUMMA, DTD.SNAME
				FROM 
				dbo.ndfl_ded_month_all_table_MONTH(@varKSnLinkPers, @varKSI, @varKSnYear) V,
				DICTIONARY_TYP_DEDUCTION DTD
			WHERE DTD.LINK = V.LINK_DED
		SET @varKSI = @varKSI + 1
	END

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

	UPDATE #RES0 SET HAS_VICHET = CASE WHEN HAS300 + HAS600 + HAS400 + HAS500 + HAS3000 > 0 THEN 1 ELSE 2 END

	IF (SELECT top 1 HAS300 + HAS600 + HAS400 + HAS500 + HAS3000 FROM #RES0) <> 5 BEGIN
		INSERT INTO #MONTHES2
		SELECT V.CODE, 
			0, 0, 0, 0, 0, 0, 
			0, 0, 0, 0, 0, 0
		FROM (	      SELECT '101' AS CODE 
			UNION SELECT '102' AS CODE 
			UNION SELECT '103' AS CODE 
			UNION SELECT '104' AS CODE 
			UNION SELECT '105' AS CODE) V
		WHERE V.CODE NOT IN (SELECT CODE_DED FROM #MONTHES2)
	END


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

		DELETE FROM  #MONTHES2
		DELETE FROM  #MONTHES

		INSERT INTO #MONTHES2
		SELECT 
			'', 
			SUM(SM01), SUM(SM02), SUM(SM03), SUM(SM04), SUM(SM05), SUM(SM06), 
			SUM(SM07), SUM(SM08), SUM(SM09), SUM(SM10), SUM(SM11), SUM(SM12)
		FROM #PAYS0 WHERE MODE = 5

		INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12,SM13)
		SELECT 6, '',
			SM01,
			CASE WHEN @Today >= 2 THEN SM01 + SM02 ELSE 0 END,
			CASE WHEN @Today >= 3 THEN SM01 + SM02 + SM03 ELSE 0 END,
			CASE WHEN @Today >= 4 THEN SM01 + SM02 + SM03 + SM04 ELSE 0 END,
			CASE WHEN @Today >= 5 THEN SM01 + SM02 + SM03 + SM04 + SM05 ELSE 0 END,
			CASE WHEN @Today >= 6 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 ELSE 0 END,
			CASE WHEN @Today >= 7 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 ELSE 0 END,
			CASE WHEN @Today >= 8 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 ELSE 0 END,
			CASE WHEN @Today >= 9 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 ELSE 0 END,
			CASE WHEN @Today >= 10 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 + SM10 ELSE 0 END,
			CASE WHEN @Today >= 11 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 + SM10 + SM11 ELSE 0 END,
			CASE WHEN @Today >= 12 THEN SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 + SM10 + SM11 + SM12 ELSE 0 END,
			SM01 + SM02 + SM03 + SM04 + SM05 + SM06 + SM07 + SM08 + SM09 + SM10 + SM11 + SM12
		FROM #MONTHES2
		DELETE FROM  #MONTHES2
	END
	ELSE BEGIN
		INSERT INTO #PAYS0 (MODE,CODE,SM01,SM02,SM03,SM04,SM05,SM06,SM07,SM08,SM09,SM10,SM11,SM12)
		SELECT 5, V.CODE, 
			0, 0, 0, 0, 0, 0, 
			0, 0, 0, 0, 0, 0
		FROM (SELECT '101' AS CODE UNION SELECT '102' AS CODE UNION SELECT '103' AS CODE UNION SELECT '104' AS CODE UNION SELECT '105' AS CODE) V
		UNION
		SELECT 6, '', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

		UPDATE #RES0 SET HAS_VICHET = 0, HAS300 = 0, HAS600 = 0, HAS400 = 0, HAS500 = 0, HAS3000 = 0
	END


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

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



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




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

	INSERT INTO #MONTHES2 (CODE_DED) VALUES ('')

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

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

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

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


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



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


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

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


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

	EXEC dbo.BufferClear

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


GO


GRANT EXECUTE ON dbo.[SD_REP_1NDFL] TO PUBLIC

GO



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

GO
---- exec [dbo].SA_RSV1_EXPORT_0700_2013 142

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

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

SET NOCOUNT  ON

--Строка заголовка
CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))

INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

declare @NAME_PROG varchar(254), @VERS_PROG VARCHAR(254), @WORK_END varchar(1)
Select @NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
	@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
from dbo.DICTIONARY_TASK where CODE = 'SALARY'
--------------------------------------------
-- Проставлять ОКАТО или ОКТМО по настройке
DECLARE @OKATO_OR_OKTMO int
SET @OKATO_OR_OKTMO = dbo.SA_GET_OPTION_BY_CODE('NASTR_USE_OKATO_OKTMO') 
	
	
	
	
DECLARE @LINK_DEP INT, @YEAR INT, @Version TINYINT, @Period_Number TINYINT, @LINK_FORM INT, @Begin_Date DATETIME, @End_Date DATETIME, @modify_date DATETIME
SELECT 
	@LINK_DEP = LINK_ORGANIZATION, 
	@YEAR = YEAR(Begin_Date),
	@Version = [Version],
	@Period_Number = Period_Number,
	@LINK_FORM = LINK_FORM,
	@Begin_Date = dbo.DateBeginOfYear(Begin_Date),
	@End_Date = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,Period_Number*3,YEAR(Begin_Date))),
	@modify_date = modify_date
FROM dbo.REPORT_SAVED_FORMS WHERE LINK_SAVED_FORM = @link

SELECT top 1
	DD1.OKPO AS OKPO1, 
	RIGHT(REPLICATE('0',12) + LTRIM(RTRIM(DD1.INN)), 12) AS INN1, 
	DD1.KPP AS KPP1, 
	FULL_NAME = UPPER(DD1.FULL_NAME),
	UPPER(DD1.NAME) AS ORGNAME,
	DD2.NALOG AS IMNS_SONO, DD2.NAME AS IMNS_NAME, 
	DD2.NALOG AS SONO, 
	RIGHT(REPLICATE('0',15) + LTRIM(RTRIM(DD1.OGRN)), 15) AS OGRN1,
	LTRIM(RTRIM(dbo.GetAddressBykladr(DD1.REF_LINK_A))) 
		+ CASE WHEN ISNULL(DD1.HOUSE, '') = '' THEN '' ELSE  ' ' + LTRIM(RTRIM(DD1.HOUSE)) END
		+ CASE WHEN ISNULL(DD1.FLAT, '') = '' THEN '' ELSE ' - ' + LTRIM(RTRIM(DD1.FLAT)) END
	AS ADDR_STR,
	CAST(NULL AS DATETIME) AS DATE_END,
	UPPER(RTRIM(CHIEF.FM) + ' ' + LEFT(CHIEF.IM, 1) + '. ' + LEFT(CHIEF.OT,1) + '.') AS CHIEF_FIO,
	RTRIM(CHIEF.PHONE) AS CH_PHONE,
	UPPER(RTRIM(GLBUH.FM) + ' ' + LEFT(GLBUH.IM, 1) + '. ' + LEFT(GLBUH.OT,1) + '.') AS GLBUH_FIO,
	RTRIM(GLBUH.PHONE) AS GL_PHONE,
	OGRN = RIGHT(REPLICATE('0',15) + LTRIM(RTRIM(DD1.OGRN)), 15),
	DD1.OKATO,
	DD1.OKTMO,
	OKVED = (CASE WHEN LEN(ltrim(rtrim(DD1.OKVED)))<8 AND RIGHT(DD1.OKVED,1) = '.' THEN STUFF(DD1.OKVED,LEN(ltrim(rtrim(DD1.OKVED))),1,'') ELSE DD1.OKVED end)  ,
 	DD1.OKPO,
	DD1.FSS_REG_NUM, --Регистрационный номер (код) страхователя ТФОМС
	DD1.FSS_KOD_P, --Код подчиненности - код, состоящий из пяти цифр, указывающий на территориальный орган Фонда, в котором страхователь зарегистрирован в текущий момент;	
	DD1.FSS_KOD_DOP, --Дополнительный код предусмотрен для обособленных подразделений организаций
	DD1.OKOPF, --- код Общероссийского классификатора организационно-правовых форм;
	DD1.OKFS, --- код Общероссийского классификатора форм собственности;
	DD1.PFNUMBER,
	DA.PINDEX, REGION = UPPER(DA.REGION), DA.REGCODE, RAION = UPPER(DA.RAION), GOROD = UPPER(DA.GOROD), 
	NASEL = UPPER(DA.NASEL), STREET = UPPER(DA.STREET), DA.HOUSE, DA.KORP, DA.FLAT,
	TFOMS_RNUM = DD1.TFOMS_REG_NUM,
	TFOMS_KT = DD1.TFOMS_KT,
	TFOMS_KTI = '03',
	WORK_END = '1'
INTO #DEP_DATA	
FROM DICTIONARY_DEPARTMENT DD1 
	LEFT OUTER JOIN DICTIONARY_DEPARTMENT DD2 ON DD1.IMNS_LINK = DD2.LINK
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Руководитель') chief on chief.link_dep = dd1.link
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Главный бухгалтер') GLBUH ON GLBUH.link_dep = dd1.link
	LEFT JOIN DBO.DEP_ADRESS(@LINK_DEP) DA ON 1=1
WHERE DD1.LINK = @LINK_DEP

DECLARE @Cur0 CURSOR, @CurD0 CURSOR, @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,@CurI CURSOR, @CurI1 CURSOR

DECLARE @lcFNAME varchar(254)
SELECT @lcFNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),@YEAR) + '-ORG-' + RTRIM(LTRIM(COALESCE(PFNUMBER,''))) + '-DCK-00001-DPT-000000-DCK-00000.XML' FROM #DEP_DATA

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
  SELECT @lcFNAME, 'OEM' --Имя файла
  UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="Windows-1251" ?>'
  UNION ALL SELECT @lcFNAME, SPACE(0) + '<ФайлПФР>'
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<ИмяФайла>' + RTRIM(LTRIM(@lcFNAME)) + '</ИмяФайла>'
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<ЗаголовокФайла>'
	  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ВерсияФормата>07.00</ВерсияФормата>'
	  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ТипФайла>ВНЕШНИЙ</ТипФайла>'
	  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ПрограммаПодготовкиДанных>'
	    UNION ALL SELECT @lcFNAME, SPACE(3) + '<НазваниеПрограммы>' + @NAME_PROG + '</НазваниеПрограммы>'
	    UNION ALL SELECT @lcFNAME, SPACE(3) + '<Версия>' + @VERS_PROG + '</Версия>'
	  UNION ALL SELECT @lcFNAME, SPACE(2) + '</ПрограммаПодготовкиДанных>'
	  UNION ALL SELECT @lcFNAME, SPACE(2) + '<ИсточникДанных>СТРАХОВАТЕЛЬ</ИсточникДанных> '
	UNION ALL SELECT @lcFNAME, SPACE(1) + '</ЗаголовокФайла>'
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<ПачкаВходящихДокументов Окружение="Единичный запрос">'
	  UNION ALL SELECT @lcFNAME, SPACE(2) + '<РАСЧЕТ_ПО_СТРАХОВЫМ_ВЗНОСАМ_НА_ОПС_И_ОМС_ПЛАТЕЛЬЩИКАМИ_СВ_ПРОИЗВОДЯЩИМИ_ВЫПЛАТЫ_ФЛ_НАЧИНАЯ_С_2013_ГОДА>'
	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<НомерВпачке>1</НомерВпачке>'
	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<РегистрационныйНомерПФР>' + LTRIM(RTRIM(ISNULL(PFNUMBER,''))) + '</РегистрационныйНомерПФР>'  + CHAR(10) +
								  SPACE(3) + '<НомерКорректировки>' + CASE @Version WHEN 0 THEN '000' ELSE (REPLICATE('0',2) + ltrim(rtrim(CONVERT(varchar(3),@Version)))) END + '</НомерКорректировки>'  + CHAR(10) +
								  SPACE(3) + '<КодОтчетногоПериода>' + CASE @Period_Number WHEN 1 THEN '03' WHEN 2 THEN '06' WHEN 3 THEN '09' ELSE '12' END +'</КодОтчетногоПериода>' + CHAR(10) +
								  SPACE(3) + '<КалендарныйГод>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),@YEAR),''))) + '</КалендарныйГод> ' + CHAR(10) +
							      CASE WHEN LTRIM(RTRIM(ISNULL(@WORK_END,''))) = 'Л' THEN
										SPACE(3) + '<ПрекращениеДеятельности>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(1),WORK_END),''))) + '</ПрекращениеДеятельности> ' + CHAR(10)
								  ELSE '' END
	   FROM #DEP_DATA						   

	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<НаименованиеОрганизации>' + LTRIM(RTRIM(ISNULL(FULL_NAME,''))) + '</НаименованиеОрганизации>' FROM #DEP_DATA
	   --UNION ALL SELECT @lcFNAME, SPACE(3) + '<РегистрационныйНомерТФОМС>' + LTRIM(RTRIM(ISNULL(TFOMS_RNUM,''))) + '</РегистрационныйНомерТФОМС>' FROM #DEP_DATA
	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<ИНН>' + LTRIM(RTRIM(ISNULL(INN1,''))) + '</ИНН>' FROM #DEP_DATA
	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<КПП>' + LTRIM(RTRIM(ISNULL(KPP1,''))) + '</КПП>' FROM #DEP_DATA
	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<ОГРН>' + LTRIM(RTRIM(ISNULL(OGRN1,''))) + '</ОГРН>' FROM #DEP_DATA 
	   UNION ALL SELECT @lcFNAME, SPACE(3) + case when @OKATO_OR_OKTMO = 1 
											 then ('<КодПоОКАТО>' + REPLACE(LTRIM(RTRIM(ISNULL(OKATO,''))),SPACE(1),'') + '</КодПоОКАТО>'  )
											 ELSE ('<КодПоОКТМО>' + REPLACE(LTRIM(RTRIM(ISNULL(OKTMO,''))),SPACE(1),'') + '</КодПоОКТМО>'  )  END 
											 FROM #DEP_DATA
	   											
	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКВЭД>' + LTRIM(RTRIM(ISNULL(OKVED,''))) + '</КодПоОКВЭД>' FROM #DEP_DATA 
	   --UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКПО>' + LTRIM(RTRIM(ISNULL(OKPO,''))) + '</КодПоОКПО>' FROM #DEP_DATA 
	   --UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКОПФ>' + LTRIM(RTRIM(ISNULL(OKOPF,''))) + '</КодПоОКОПФ>' FROM #DEP_DATA 
	   --UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКФС>' + LTRIM(RTRIM(ISNULL(OKFS,''))) + '</КодПоОКФС>' FROM #DEP_DATA 
	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<Телефон>' + LTRIM(RTRIM(ISNULL(GL_PHONE,''))) + '</Телефон>' FROM #DEP_DATA 

	   UNION ALL SELECT @lcFNAME, SPACE(3) + '<АдресРегистрации>'
		   UNION ALL SELECT @lcFNAME, SPACE(4) + '<ТипАдреса>РОССИЙСКИЙ</ТипАдреса>' 
		   UNION ALL SELECT @lcFNAME, SPACE(4) + '<Индекс>'+ LTRIM(RTRIM(ISNULL(PINDEX,''))) + '</Индекс>' FROM #DEP_DATA   
		   UNION ALL SELECT @lcFNAME, SPACE(4) + '<РоссийскийАдрес>' + CHAR(10) +

											CASE WHEN LTRIM(RTRIM(ISNULL(REGION,''))) <> '' THEN
											 SPACE(5) + '<Регион>' + CHAR(10) + 
												SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(REGION,len(REGION)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(REGION),1,' '))) ) )) + '</ГеографическоеНазвание>' + CHAR(10) + 
												SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(REGION),1,' ')) )) + '</Сокращение>' + CHAR(10) +
											SPACE(5) + '</Регион>' + CHAR(10) 
											ELSE '' END +
											
											CASE WHEN LTRIM(RTRIM(ISNULL(RAION,''))) <> '' THEN
											 SPACE(5) + '<Район>' + CHAR(10) + 
												SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(RAION,len(RAION)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(RAION),1,' '))) ) )) + '</ГеографическоеНазвание>' + CHAR(10) + 
												SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(RAION),1,' ')) )) + '</Сокращение>' + CHAR(10) +
											SPACE(5) + '</Район>' + CHAR(10) 
											ELSE '' END +

											CASE WHEN LTRIM(RTRIM(ISNULL(GOROD,''))) <> '' THEN
											 SPACE(5) + '<Город>' + CHAR(10) + 
												SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(GOROD,len(GOROD)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(GOROD),1,' '))) ) )) + '</ГеографическоеНазвание>' + CHAR(10) + 
												SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(GOROD),1,' ')) )) + '</Сокращение>' + CHAR(10) +
											SPACE(5) + '</Город>' + CHAR(10) 
											ELSE '' END +

											CASE WHEN LTRIM(RTRIM(ISNULL(NASEL,''))) <> '' THEN
											 SPACE(5) + '<НаселенныйПункт>' + CHAR(10) + 
												SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(NASEL,len(NASEL)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(NASEL),1,' '))) ) )) + '</ГеографическоеНазвание>' + CHAR(10) + 
												SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(NASEL),1,' ')) )) + '</Сокращение>' + CHAR(10) +
											SPACE(5) + '</НаселенныйПункт>' + CHAR(10) 
											ELSE '' END +	

											CASE WHEN LTRIM(RTRIM(ISNULL(STREET,''))) <> '' THEN
											SPACE(5) + '<Улица>' + CHAR(10)
												+ SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(STREET,len(STREET)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(STREET),1,' '))) ) ))+'</ГеографическоеНазвание>' + CHAR(10) 
												+ SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(STREET),1,' ')) ))+'</Сокращение>' + CHAR(10) 
												+ SPACE(5) + '</Улица>' + CHAR(10)
											ELSE '' END	+			

											CASE WHEN LTRIM(RTRIM(ISNULL(HOUSE,''))) <> '' THEN
											 SPACE(5) + '<Дом>' + CHAR(10) + 
												SPACE(6) + '<Сокращение>ДОМ</Сокращение>' + CHAR(10) +
												SPACE(6) + '<Номер>'+ UPPER(LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),HOUSE),'')))) + '</Номер>' + CHAR(10) + 
											SPACE(5) + '</Дом>' + CHAR(10) 
											ELSE '' END +												

											CASE WHEN LTRIM(RTRIM(ISNULL(KORP,''))) <> '' THEN
											 SPACE(5) + '<Корпус>' + CHAR(10) + 
												SPACE(6) + '<Сокращение>КОРП.</Сокращение>' + CHAR(10) +
												SPACE(6) + '<Номер>'+ UPPER(LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),KORP),'')))) + '</Номер>' + CHAR(10) + 
											SPACE(5) + '</Корпус>' + CHAR(10) 
											ELSE '' END +																

											CASE WHEN LTRIM(RTRIM(ISNULL(FLAT,''))) <> '' THEN
											 SPACE(5) + '<Квартира>' + CHAR(10) + 
												SPACE(6) + '<Сокращение>КВ.</Сокращение>' + CHAR(10) +
												SPACE(6) + '<Номер>'+ UPPER(LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),FLAT),'')))) + '</Номер>' + CHAR(10) + 
											SPACE(5) + '</Квартира>' + CHAR(10) 
											ELSE '' END +				
											
									SPACE(4) + '</РоссийскийАдрес>' + CHAR(10) +
								SPACE(3) + '</АдресРегистрации>'
			FROM #DEP_DATA    

------ стр.1_2
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
select @lcFNAME, 
		CASE WHEN T.COL = 3 THEN
			SPACE(3) + '<КоличествоЗЛ>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ>'
		ELSE
			SPACE(3) + '<СреднесписочнаяЧисленность>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СреднесписочнаяЧисленность>'		
		END	
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 1, 1, DEFAULT) T WHERE T.COL IN (3,4) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)	
		  --SELECT @lcFNAME, SPACE(3) + '<КодУстановленногоТарифа>' + LTRIM(RTRIM(ISNULL(TFOMS_KT,''))) + '</КодУстановленногоТарифа>' FROM #DEP_DATA
/*UNION ALL*/ SELECT @lcFNAME, SPACE(3) + '<КоличествоСтраниц>6</КоличествоСтраниц>'
UNION ALL SELECT @lcFNAME, SPACE(3) + '<КоличествоЛистовПриложения>0</КоличествоЛистовПриложения>'

----- стр.2
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<Раздел1РасчетПоНачисленнымУплаченным>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ОстатокЗадолженностиНаНачалоРасчетногоПериода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, 1, 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) + '<НачисленоСначалаРасчетногоПериода2013>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME,
	CASE T.COL 
	WHEN 3 THEN 
		 CASE T.ROW WHEN 2 THEN SPACE(5) + '<ВсегоСначалаРасчетногоПериода2013>' WHEN 6 THEN SPACE(5) + '<ПоследниеТриМесяцаИтого2013>' ELSE  SPACE(5) + '<ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 2))) + 'с2013>' 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) + '<ОПСстраховаяЧастьПоДопТар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(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) + '</ВсегоСначалаРасчетногоПериода2013>' WHEN 6 THEN SPACE(5) + '</ПоследниеТриМесяцаИтого2013>' ELSE  SPACE(5) + '</ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 2))) + 'с2013>' END	
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 0, DEFAULT) T WHERE ROW IN (2,3,4,5,6) AND T.COL IN (3,4,5,6,7)  ORDER BY T.ROW, 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) + '<ДоначисленоСначалаРасчетногоПериода2013>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, CASE T.COL 
	WHEN 3 THEN SPACE(5) + '<ВсегоСначалаРасчетногоПериода2013>' + 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) + '<ОПСстраховаяЧастьПоДопТар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(6) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'	+ CHAR(10) +
				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) ORDER BY T.COL

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, CASE T.COL 
	WHEN 3 THEN	SPACE(5) + '<СсуммПревышающихПредельнуюВеличинуБазы>' + 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) + '<ОПСстраховаяЧастьПоДопТар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(6) + '<СтраховыеВзносыОМС>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СтраховыеВзносыОМС>'	 + CHAR(10) +
				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,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) + '<ВсегоКуплате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(5) + '<ОПСстраховаяЧастьПоДопТар1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧастьПоДопТар1>'		
	WHEN 6 THEN	SPACE(5) + '<ОПСстраховаяЧастьПоДопТар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, 10, 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) + '<УплаченоСначалаРасчетногоПериода2013>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME,
	CASE T.COL 
	WHEN 3 THEN 
		 CASE T.ROW WHEN 11 THEN SPACE(5) + '<ВсегоСначалаРасчетногоПериода2013>' WHEN 15 THEN SPACE(5) + '<ПоследниеТриМесяцаИтого2013>' ELSE  SPACE(5) + '<ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 11))) + 'с2013>' 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) + '<ОПСстраховаяЧастьПоДопТар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(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) + '</ВсегоСначалаРасчетногоПериода2013>' WHEN 15 THEN SPACE(5) + '</ПоследниеТриМесяцаИтого2013>' ELSE  SPACE(5) + '</ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 11))) + 'с2013>' 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)  ORDER BY T.ROW, 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) + '<ВтомЧислеЗаПредыдущиеРасчетныеПериоды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) + '<ОстатокЗадолженностиНаКонецРасчетногоПериода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(5) + '<ОПСстраховаяЧастьПоДопТар1>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</ОПСстраховаяЧастьПоДопТар1>'		
	WHEN 6 THEN	SPACE(5) + '<ОПСстраховаяЧастьПоДопТар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, 17, 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(3) + '</Раздел1РасчетПоНачисленнымУплаченным>'	


-----Разделы 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_2R (NUM TINYINT, TAB_NUM TINYINT, RAZDEL_NAME VARCHAR(254))
INSERT INTO #STR_2_2R 
		SELECT 1,4,'НаОбязательноеПенсионноеСтрахование'
UNION	SELECT 2,4,'НаОбязательноеМедицинскоеСтрахование'

--UNION	SELECT 2,4,'НачисленоСтраховыхВзносовВпользуРаботниковИнвалидов'
--UNION	SELECT 3,4,'РасчетПоВыплатамРаботникамЕНВД' WHERE @YEAR <= 2010
--UNION	SELECT 4,4,'НачисленоСтраховыхВзносовВпользуРаботниковЕНВД' WHERE @YEAR <= 2010

CREATE TABLE #STR_2_2B (NUM TINYINT, RAZDEL_NUM TINYINT, BLOK_NAME VARCHAR(254))
INSERT INTO #STR_2_2B 
		SELECT 1,1,'ВыплатыИвознаграждения_1966старше'
UNION	SELECT 2,1,'ВыплатыИвознаграждения_1967моложе'
UNION	SELECT 3,1,'ВыплатыИвознаграждения_ВременноИГ'
UNION	SELECT 4,1,'НеПодлежащиеОбложению_1966старше'
UNION	SELECT 5,1,'НеПодлежащиеОбложению_1967моложе'
UNION	SELECT 6,1,'НеПодлежащиеОбложению_ВременноИГ'
UNION	SELECT 7,1,'СуммаРасходовПринимаемыхКвычету_1966старше'
UNION	SELECT 8,1,'СуммаРасходовПринимаемыхКвычету_1967моложе'
UNION	SELECT 9,1,'СуммаРасходовПринимаемыхКвычету_ВременноИГ'
UNION	SELECT 11,1,'ПревышающиеПредельнуюВеличинуБазы_1966старше'
UNION	SELECT 12,1,'ПревышающиеПредельнуюВеличинуБазы_1967моложе'
UNION	SELECT 13,1,'ПревышающиеПредельнуюВеличинуБазы_ВременноИГ'
--UNION	SELECT 14,1,'БазаДляНачисленияСтраховыхВзносовНаОПС_1966старше'
--UNION	SELECT 15,1,'БазаДляНачисленияСтраховыхВзносовНаОПС_1967моложе'
UNION	SELECT 14,1,'БазаДляНачисленияСтраховыхВзносовНаОПСстраховая'
UNION	SELECT 15,1,'БазаДляНачисленияСтраховыхВзносовНаОПСнакопительная'
UNION	SELECT 16,1,'НачисленоНаОПСстраховая'
UNION	SELECT 17,1,'НачисленоНаОПСнакопительная'
UNION	SELECT 18,1,'НачисленоНаОПСсСуммПревышающих'
UNION	SELECT 19,1,'КоличествоФЛпоТарифу'
--UNION	SELECT 19,1,'КоличествоФЛпоКоторымБазаПревысилаПредел'
--UNION	SELECT 20,2,'СуммаВыплатИвознаграждений'
--UNION	SELECT 21,2,'НеПодлежащиеОбложению'
--UNION	SELECT 22,2,'СуммаРасходовПринимаемыхКвычету'
--UNION	SELECT 23,2,'ПревышающиеПредельнуюВеличинуБазы'
--UNION	SELECT 24,2,'БазаДляНачисленияСтраховыхВзносовНаОМС'
--UNION	SELECT 25,2,'НачисленоНаОМС'
UNION	SELECT 20,1,'КоличествоФЛпоКоторымБазаПревысилаПредел'
UNION	SELECT 22,2,'СуммаВыплатИвознаграждений'
UNION	SELECT 23,2,'НеПодлежащиеОбложению'
UNION	SELECT 24,2,'СуммаРасходовПринимаемыхКвычету'
UNION	SELECT 25,2,'ПревышающиеПредельнуюВеличинуБазы'
UNION	SELECT 26,2,'БазаДляНачисленияСтраховыхВзносовНаОМС'
UNION	SELECT 27,2,'НачисленоНаОМС'
--- ДОП ТАРИФЫ
CREATE TABLE #TABLES1 (NUM TINYINT, TAB_NAME VARCHAR(254))
INSERT INTO #TABLES1 
		SELECT 5,'Раздел2_2_РасчетСВпоДопТарифуЧ_1'
  union SELECT 6,'Раздел2_3_РасчетСВпоДопТарифуЧ_2'

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,5,'КоличествоФЛПоКоторымСВначисленыПоДопТарифу'
UNION	SELECT 7,6,'СуммаВыплатИвознаграждений'
UNION	SELECT 8,6,'НеПодлежащиеОбложению'
UNION	SELECT 9,6,'СуммаРасходовПринимаемыхКвычету'
UNION	SELECT 10,6,'БазаДляНачисленияСтраховыхВзносовПоДопТарифу'
UNION	SELECT 11,6,'НачисленоПоДопТарифу'
UNION	SELECT 12,6,'КоличествоФЛПоКоторымСВначисленыПоДопТарифу'

--select @TAB_NAME= TAB_NAME from  #TABLES order by NUM

--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_2R 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_2B 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 = 19 or  @num = 20
								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_2R 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_2B WHERE RAZDEL_NUM = @RAZDEL_NUM OR RAZDEL_NUM = @RAZDEL_NUM order by NUM
							OPEN @CurI1
							FETCH NEXT FROM @CurI1 INTO @NUM, @BLOK_NAME
							WHILE (@@fetch_status <> -1)
							BEGIN
								IF (@@fetch_status <> -2)
								BEGIN
									if @num = 19 or  @num = 20
									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_2R WHERE TAB_NUM = @TAB_NUM order by NUM
				--OPEN @Cur
				--FETCH NEXT FROM @Cur INTO @RAZDEL_NUM, @RAZDEL_NAME
				--WHILE (@@fetch_status <> -1)
				--BEGIN
				--	IF (@@fetch_status <> -2)
				--	BEGIN		

				--		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @RAZDEL_NAME + '>'
						
						SET @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 = 6 or  @num = 12
								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

		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_2---
		IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (1306, 7, DEFAULT, DEFAULT) WHERE SUMMA <> 0) > 0
		BEGIN
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_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, 7, 1, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ЧисленностьЧленовОрганизации>'

				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ЧисленностьИнвалидов>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
						 SPACE(6) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
					WHEN 4 THEN SPACE(6) + '<КоличествоЗЛ_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_1месяц>'
					WHEN 5 THEN SPACE(6) + '<КоличествоЗЛ_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_2месяц>'		
					WHEN 6 THEN SPACE(6) + '<КоличествоЗЛ_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_3месяц>'
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 2, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ЧисленностьИнвалидов>'
			
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<УдельныйВесЧисленности>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
						 SPACE(6) + '<УдельныйВес_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_Всего>'
					WHEN 4 THEN SPACE(6) + '<УдельныйВес_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_1месяц>'
					WHEN 5 THEN SPACE(6) + '<УдельныйВес_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_2месяц>'		
					WHEN 6 THEN SPACE(6) + '<УдельныйВес_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_3месяц>'
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 3, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</УдельныйВесЧисленности>'			
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_2_ДляОбщественныхОрганизацийИнвалидов>'
	END	--IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (1306, 6, 3, DEFAULT) WHERE SUMMA <> 0) > 0	

---Раздел3_3
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (1306, 8, DEFAULT, DEFAULT) WHERE SUMMA <> 0) > 0
	BEGIN

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_3_ДляОрганизацийУставныйКапиталСостоитИзВкладовОбщОргИнвалидов>'
					
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СреднесписочнаяЧисленность>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
							SPACE(6) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
				WHEN 4 THEN SPACE(6) + '<КоличествоЗЛ_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_1месяц>'
				WHEN 5 THEN SPACE(6) + '<КоличествоЗЛ_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_2месяц>'		
				WHEN 6 THEN SPACE(6) + '<КоличествоЗЛ_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_3месяц>'
				END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 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, 8, 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, 8, 3, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</УдельныйВесЧисленности>'
					
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ФондОплатыТруда>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
							SPACE(6) + '<РасчетСумм>' + CHAR(10) +
								SPACE(7) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
					WHEN 4 THEN SPACE(7) + '<СуммаПоследние1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние1месяц>'
					WHEN 5 THEN SPACE(7) + '<СуммаПоследние2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние2месяц>'		
					WHEN 6 THEN SPACE(7) + '<СуммаПоследние3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние3месяц>'
				END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 4, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</РасчетСумм>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ФондОплатыТруда>'		
		
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ЗарплатаИнвалидов>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
		  					SPACE(6) + '<РасчетСумм>' + CHAR(10) +
								SPACE(7) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
					WHEN 4 THEN SPACE(7) + '<СуммаПоследние1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние1месяц>'
					WHEN 5 THEN SPACE(7) + '<СуммаПоследние2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние2месяц>'		
					WHEN 6 THEN SPACE(7) + '<СуммаПоследние3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаПоследние3месяц>'
				END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 5, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</РасчетСумм>'			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ЗарплатаИнвалидов>'		
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<УдельныйВесЗарплатыИнвалидов>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
							 SPACE(6) + '<УдельныйВес_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_Всего>'
				WHEN 4 THEN SPACE(6) + '<УдельныйВес_1месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_1месяц>'
				WHEN 5 THEN SPACE(6) + '<УдельныйВес_2месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_2месяц>'		
				WHEN 6 THEN SPACE(6) + '<УдельныйВес_3месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</УдельныйВес_3месяц>'
				END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 6, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</УдельныйВесЗарплатыИнвалидов>'
						
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_3_ДляОрганизацийУставныйКапиталСостоитИзВкладовОбщОргИнвалидов>'
	END --IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (1306, 7, 3, DEFAULT) WHERE SUMMA <> 0) > 0
END --	IF (SELECT COUNT(*) FROM #INVALID) > 0 -- инвалиды
--Раздел3_4


	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 9, DEFAULT, DEFAULT) WHERE COL = 3 AND SUMMA <> 0) > 0 -- информ. технол.
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_4_ДляОрганизацийИТ>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, SPACE(5) + 
				'<СуммаДоходовПоНКвсего>' + CHAR(10) + 
					SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' + CHAR(10) + 
					SPACE(6) + '<СуммаДоходаПоПредшествующему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>' + CHAR(10) +
					SPACE(6) + '<СуммаДоходаПоТекущему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>' + CHAR(10)
				+ SPACE(5) +'</СуммаДоходовПоНКвсего>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 3) T ORDER BY T.COL

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, SPACE(5) + 
				'<СуммаДоходовИТизНих>' + CHAR(10) + 
					SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' + CHAR(10) + 
					SPACE(6) + '<СуммаДоходаПоПредшествующему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>' + CHAR(10) +
					SPACE(6) + '<СуммаДоходаПоТекущему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>' + CHAR(10) 
				+ SPACE(5) +'</СуммаДоходовИТизНих>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 2, 3) T ORDER BY T.COL

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, SPACE(5) + 
				'<ДоляДоходовИТ>' + CHAR(10) + 
					SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' + CHAR(10) + 
					SPACE(6) + '<ДоляДоходаПоПредшествующему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</ДоляДоходаПоПредшествующему>' + CHAR(10) + 
					SPACE(6) + '<ДоляДоходаПоТекущему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,5),T.SUMMA)),''))) + '</ДоляДоходаПоТекущему>' + CHAR(10)
				+ SPACE(5) +'</ДоляДоходовИТ>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 3, 3) T ORDER BY T.COL

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, SPACE(5) + 
				'<ЧисленностьРаботниковИТ>' + CHAR(10) + 
					SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' + CHAR(10) + 
					SPACE(6) + '<КоличествоЗЛпоПредшествующему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛпоПредшествующему>' + CHAR(10) +
					SPACE(6) + '<КоличествоЗЛпоТекущему>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛпоТекущему>' + CHAR(10)
				+ SPACE(5) +'</ЧисленностьРаботниковИТ>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 4, 3) T ORDER BY T.COL

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СведенияОвыпискеИзРеестраИТорганизаций>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, CASE T.COL 
				WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
				WHEN 4 THEN SPACE(6) + '<ДатаЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,'\  \.\  \.\    '))) + '</ДатаЗаписиВреестре>'
				WHEN 5 THEN SPACE(6) + '<НомерЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</НомерЗаписиВреестре>'		
				END						
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 5, DEFAULT) T WHERE T.COL IN (3,4,5) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СведенияОвыпискеИзРеестраИТорганизаций>'
		
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_4_ДляОрганизацийИТ>'
	END	--(SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 7, D
----Раздел3_5	
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 10, DEFAULT, DEFAULT) WHERE COL = 4 AND SUMMA <> 0) > 0 -- информ. технол.
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_5_ДляОрганизацийСМИ>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СведенияПоВидуДеятельности>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
					SELECT @lcFNAME, CASE T.COL 
					WHEN 1 THEN SPACE(6) + '<НомерПП>' + LTRIM(RTRIM(T.ROW)) + '</НомерПП>'
					WHEN 2 THEN SPACE(6) + '<НаименованиеВидаЭД>' + LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</НаименованиеВидаЭД>'
							 + SPACE(6) + '<КодПоОКВЭД>' + LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</КодПоОКВЭД>'
					WHEN 4 THEN SPACE(6) + '<ДоходыПоВидуЭД>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</ДоходыПоВидуЭД>'
					WHEN 5 THEN	SPACE(6) + '<ДоляДохода>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</ДоляДохода>'		
					END
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 20, DEFAULT, DEFAULT) T where T.ROW IN (1,2,3,4,5,6,7,8,9,10) and T.COL IN (1,2,4,5) ORDER BY T.ROW, t.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СведенияПоВидуДеятельности>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ИтогоПоВсемВидамДеятельности>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) +'</ИтогоПоВсемВидамДеятельности>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 11, 6) T ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СведенияИзРеестраСМИ>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
					WHEN 5 THEN SPACE(6) + '<ДатаЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,'\  \.\  \.\    '))) + '</ДатаЗаписиВреестре>'
					WHEN 6 THEN SPACE(6) + '<НомерЗаписиВреестре>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</НомерЗаписиВреестре>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 12, DEFAULT) T WHERE T.COL IN (3,6,7) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СведенияИзРеестраСМИ>'
		
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_5_ДляОрганизацийСМИ>'
	END
----Раздел3_6	
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 11, DEFAULT, DEFAULT) WHERE COL = 3 AND SUMMA <> 0) > 0 -- информ. технол.
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_6_ДляОрганизацийПрименяющихУСН>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, SPACE(5) + 
				'<СуммаДоходаПоСтатье346_15НКвсего>' + CHAR(10) + 
					SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ROW_CODE)) + '</КодСтроки>' + CHAR(10) + 
					SPACE(6) + '<СуммаДохода>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДохода>' + CHAR(10) +
				+ SPACE(5) +'</СуммаДоходаПоСтатье346_15НКвсего>'
			FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 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, 11, 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, 11, 3, 3) T ORDER BY T.COL

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_6_ДляОрганизацийПрименяющихУСН>'
	END
----Раздел3_7	
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 12, DEFAULT, DEFAULT) WHERE COL in (3,4) AND SUMMA <> 0) > 0 -- информ. технол.
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_7_ДляНекоммерческихОрганизацийПрименяющихУСН>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовВсего>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>'
					WHEN 6 THEN SPACE(6) + '<СуммаДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, DEFAULT) T WHERE T.COL IN (3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СуммаДоходовВсего>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовВвидеЦелевыхПоступлений>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>'
					WHEN 6 THEN SPACE(6) + '<СуммаДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, DEFAULT) T WHERE T.COL IN (3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СуммаДоходовВвидеЦелевыхПоступлений>'
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовВвидеГрантов>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>'
					WHEN 6 THEN SPACE(6) + '<СуммаДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 3, DEFAULT) T WHERE T.COL IN (3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СуммаДоходовВвидеГрантов>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовОтОсуществленияОпределенныхВЭД>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(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, 4, DEFAULT) T WHERE T.COL IN (3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СуммаДоходовОтОсуществленияОпределенныхВЭД>'
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ДоляДоходов>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>'
					WHEN 6 THEN SPACE(6) + '<СуммаДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, DEFAULT) T WHERE T.COL IN (3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ДоляДоходов>'
	

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_7_ДляНекоммерческихОрганизацийПрименяющихУСН>'
	END
--- Раздел3_8
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 13, DEFAULT, DEFAULT) WHERE COL in (3,4) AND SUMMA <> 0) > 0 -- информ. технол.
	BEGIN
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел3_8_ДляОрганизацийОказывающихИнжиниринговыеУслуги>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовПоНКвсего>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>'
					WHEN 6 THEN SPACE(6) + '<СуммаДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, DEFAULT) T WHERE T.COL IN (3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СуммаДоходовПоНКвсего>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СуммаДоходовОтИнжинирингаИзНих>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
					WHEN 5 THEN SPACE(6) + '<СуммаДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоПредшествующему>'
					WHEN 6 THEN SPACE(6) + '<СуммаДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СуммаДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 2, DEFAULT) T WHERE T.COL IN (3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СуммаДоходовОтИнжинирингаИзНих>'
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ДоляДоходовИнжиниринг>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
					WHEN 5 THEN SPACE(6) + '<ДоляДоходаПоПредшествующему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</ДоляДоходаПоПредшествующему>'
					WHEN 6 THEN SPACE(6) + '<ДоляДоходаПоТекущему>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</ДоляДоходаПоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 3, DEFAULT) T WHERE T.COL IN (3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ДоляДоходовИнжиниринг>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СредняяЧисленностьРаботниковИнжиниринг>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
					WHEN 5 THEN SPACE(6) + '<КоличествоЗЛпоПредшествующему>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</КоличествоЗЛпоПредшествующему>'
					WHEN 6 THEN SPACE(6) + '<КоличествоЗЛпоТекущему>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</КоличествоЗЛпоТекущему>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 5, DEFAULT) T WHERE T.COL IN (3,4) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СредняяЧисленностьРаботниковИнжиниринг>'
			
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<СведенияОполученииЗаключенияПоТВОЭЗ>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME, CASE T.COL 
					WHEN 3 THEN SPACE(6) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>'
					WHEN 5 THEN SPACE(6) + '<ДатаПолученияПоложЗаключения>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</ДатаПолученияПоложЗаключения>'
					WHEN 6 THEN SPACE(6) + '<НомерЗаключения>'+ LTRIM(RTRIM(ISNULL(T.STR_VAL,''))) + '</НомерЗаключения>'		
					END						
				FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 6, DEFAULT) T WHERE T.COL IN (5,6) ORDER BY T.COL
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</СведенияОполученииЗаключенияПоТВОЭЗ>'
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел3_8_ДляОрганизацийОказывающихИнжиниринговыеУслуги>'

	END
	
	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '</Раздел3РасчетНаПравоПримененияПониженногоТарифа>'

END --IF (SELECT COUNT(*) FROM #INVALID) > 0 OR -- информ. технол.

---РАЗДЕЛ_4  Стр.12
CREATE TABLE #DONACHISL (
	LINK INT,OSN int, YEAR_D VARCHAR(4), MON int, 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_MED_STR NUMERIC(18,2))

CREATE TABLE #TAB13 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
INSERT INTO #TAB13 (ROW_CODE, COL, SUMMA, STR_VAL)
SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

INSERT INTO #DONACHISL (OSN, YEAR_D, MON, SUM_STR, SUM_STR_LIM, SUM_NAK ,SUM_STR_D1 , SUM_STR_D2, SUM_MED_STR)
SELECT DISTINCT 
	OSN = (SELECT TOP 1 SUMMA FROM #TAB13 T WHERE T.COL = 2 AND T.ROW_CODE = T13.ROW_CODE),
	YEAR_D = (SELECT TOP 1 STR_VAL FROM #TAB13 T WHERE T.COL = 3 AND T.ROW_CODE = T13.ROW_CODE),
	MON = (SELECT TOP 1 SUMMA FROM #TAB13 T WHERE T.COL = 4 AND T.ROW_CODE = T13.ROW_CODE),
	SUM_STR = (SELECT TOP 1 SUMMA FROM #TAB13 T WHERE T.COL = 5 AND T.ROW_CODE = T13.ROW_CODE),
	SUM_STR_LIM = (SELECT TOP 1 SUMMA FROM #TAB13 T WHERE T.COL = 6 AND T.ROW_CODE = T13.ROW_CODE),
	SUM_NAK = (SELECT TOP 1 SUMMA FROM #TAB13 T WHERE T.COL = 7 AND T.ROW_CODE = T13.ROW_CODE),
	SUM_STR_D1 = (SELECT TOP 1 SUMMA FROM #TAB13 T WHERE T.COL = 8 AND T.ROW_CODE = T13.ROW_CODE),
	SUM_STR_D2 = (SELECT TOP 1 SUMMA FROM #TAB13 T WHERE T.COL = 9 AND T.ROW_CODE = T13.ROW_CODE),
	SUM_MED_STR = (SELECT TOP 1 SUMMA FROM #TAB13 T WHERE T.COL = 10 AND T.ROW_CODE = T13.ROW_CODE)
FROM
	#TAB13 T13

DROP TABLE #TAB13

--Проставить номера попорядку
DECLARE @NEXT_NUM1 INT
SET @NEXT_NUM1 = 0
UPDATE #DONACHISL SET @NEXT_NUM1 = @NEXT_NUM1 + 1, LINK = @NEXT_NUM1

--IF (SELECT COUNT(*) FROM #DONACHISL) > 0 -- инвалиды
--	OR (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 13, DEFAULT, DEFAULT) WHERE COL = 4 AND SUMMA <> 0) > 0 -- информ. технол.
--BEGIN

	IF (SELECT COUNT(*) FROM #DONACHISL) > 0 -- инвалиды
	BEGIN
	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<Раздел4СуммыДоначисленныхСтраховыхВзносов>'

		UNION ALL SELECT @lcFNAME, 
			SPACE(3) + '<СуммаДоначисленныхВзносовЗаПериод>'  + CHAR(10) +
				SPACE(4) + '<НомерПП>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(LINK,0)))) + '</НомерПП>' + CHAR(10) +			
				SPACE(4) + '<ОснованиеДляДоначисленияСВ>' + LTRIM(RTRIM(CONVERT(VARCHAR(1),ISNULL(OSN,0)))) + '</ОснованиеДляДоначисленияСВ>' + CHAR(10) +	
				SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(YEAR_D,''))) + '</Год>' + CHAR(10) + 		
				SPACE(4) + '<Месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(2),ISNULL(MON,0)))) + '</Месяц>' + CHAR(10) + 	
				SPACE(4) +  '<СуммаДоначисленныхСтраховыхВзносов>' + CHAR(10) +
					SPACE(5) + '<ОПСстраховаяЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR,0)))) + '</ОПСстраховаяЧасть>' + CHAR(10) + 										
					SPACE(5) + '<ОПСстраховаяЧастьСвышеПределаБазы>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_LIM,0)))) + '</ОПСстраховаяЧастьСвышеПределаБазы>' + CHAR(10) + 										
					SPACE(5) + '<ОПСнакопительнаяЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_NAK,0)))) + '</ОПСнакопительнаяЧасть>' + CHAR(10) +
					SPACE(5) + '<ОПСстраховаяЧастьПоДопТар1>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_D1,0)))) + '</ОПСстраховаяЧастьПоДопТар1>' + CHAR(10) +
					SPACE(5) + '<ОПСстраховаяЧастьПоДопТар2>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_D2,0)))) + '</ОПСстраховаяЧастьПоДопТар2>' + CHAR(10) +
					SPACE(5) + '<СтраховыеВзносыОМС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_MED_STR,0)))) + '</СтраховыеВзносыОМС>' + CHAR(10) +	
				SPACE(4) + '</СуммаДоначисленныхСтраховыхВзносов>'  + CHAR(10) +
			SPACE(3) + '</СуммаДоначисленныхВзносовЗаПериод>'
		FROM #DONACHISL				


		UNION ALL SELECT @lcFNAME, 
			SPACE(3) + '<ИтогоДоначислено>' + CHAR(10) +
					SPACE(4) + '<ОПСстраховаяЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR,0))))) + '</ОПСстраховаяЧасть>' + CHAR(10) +			
					SPACE(4) + '<ОПСстраховаяЧастьСвышеПределаБазы>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_LIM,0))))) + '</ОПСстраховаяЧастьСвышеПределаБазы>' + CHAR(10) + 										
					SPACE(4) + '<ОПСнакопительнаяЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_NAK,0))))) + '</ОПСнакопительнаяЧасть>' + CHAR(10) +
					SPACE(4) + '<ОПСстраховаяЧастьПоДопТар1>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_D1,0))))) + '</ОПСстраховаяЧастьПоДопТар1>' + CHAR(10) +
					SPACE(4) + '<ОПСстраховаяЧастьПоДопТар2>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_D2,0))))) + '</ОПСстраховаяЧастьПоДопТар2>' + CHAR(10) +
					SPACE(4) + '<СтраховыеВзносыОМС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_MED_STR,0))))) + '</СтраховыеВзносыОМС>' + CHAR(10) +
			SPACE(3) + '</ИтогоДоначислено>' 
		FROM #DONACHISL	

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '</Раздел4СуммыДоначисленныхСтраховыхВзносов>'	
	END

--end



---РАЗДЕЛ_5  Стр.13_1
CREATE TABLE #STUD (
	LINK INT, FIO VARCHAR(254), FIO2 VARCHAR(254), NUM_SPR1 VARCHAR(30), DATE_SPR1 VARCHAR(10),NUM_SPR2 VARCHAR(30), DATE_SPR2 VARCHAR(10), 
	SM_ALL 	NUMERIC(18,2), SM1 NUMERIC(18,2), SM2 NUMERIC(18,2), SM3 NUMERIC(18,2) )

CREATE TABLE #TAB14 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
INSERT INTO #TAB14 (ROW_CODE, COL, SUMMA, STR_VAL)
SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 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 #TAB14 T WHERE T.COL = 2 AND T.ROW_CODE = T14.ROW_CODE),
	NUM_SPR1 = (SELECT TOP 1 LEFT(LTRIM(RTRIM(dbo.SA_GET_WORD_NUM(STR_VAL,1,' '))),30) FROM #TAB14 T WHERE T.COL = 3 AND T.ROW_CODE = T14.ROW_CODE),
	DATE_SPR1 = (SELECT TOP 1 LEFT(LTRIM(RTRIM(dbo.SA_GET_WORD_NUM(STR_VAL,2,' '))),10) FROM #TAB14 T WHERE T.COL = 3 AND T.ROW_CODE = T14.ROW_CODE),
	NUM_SPR2 = (SELECT TOP 1 LEFT(LTRIM(RTRIM(dbo.SA_GET_WORD_NUM(STR_VAL,1,' '))),30) FROM #TAB14 T WHERE T.COL = 4 AND T.ROW_CODE = T14.ROW_CODE),
	DATE_SPR2 = (SELECT TOP 1 LEFT(LTRIM(RTRIM(dbo.SA_GET_WORD_NUM(STR_VAL,2,' '))),10) FROM #TAB14 T WHERE T.COL = 4 AND T.ROW_CODE = T14.ROW_CODE),
	SM_ALL = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 5 AND T.ROW_CODE = T14.ROW_CODE),
	SM1 = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 6 AND T.ROW_CODE = T14.ROW_CODE),
	SM2 = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 7 AND T.ROW_CODE = T14.ROW_CODE),
	SM3 = (SELECT TOP 1 SUMMA FROM #TAB14 T WHERE T.COL = 8 AND T.ROW_CODE = T14.ROW_CODE)
FROM
	#TAB14 T14

DROP TABLE #TAB14

--Проставить номера попорядку
DECLARE @NEXT_NUM2 INT
SET @NEXT_NUM2 = 0
UPDATE #STUD SET @NEXT_NUM2 = @NEXT_NUM2 + 1, LINK = @NEXT_NUM2

--количество обучающихся
DECLARE @COUNT_STUD INT
set @COUNT_STUD  =  (select count(*) from #STUD ) 


--IF (SELECT COUNT(*) FROM #STUD) > 0 -- студенты
--	OR (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 14, DEFAULT, DEFAULT) WHERE COL = 5 AND SUMMA <> 0) > 0 -- оплата студентам
--BEGIN

IF (SELECT COUNT(*) FROM #STUD) > 0 -- студенты
BEGIN
	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<Раздел5СведенияОВыплатахВпользуОбучающихся>'
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<КоличествоОбучающихся>' + LTRIM(RTRIM(CONVERT(VARCHAR(5),ISNULL(@COUNT_STUD,0)))) + '</КоличествоОбучающихся>' 			
		UNION ALL SELECT @lcFNAME, 
			SPACE(4) + '<СведенияОбОбучающемся>' + CHAR(10) +		
				SPACE(5) + '<НомерПП>' + LTRIM(RTRIM(CONVERT(VARCHAR(5),ISNULL(link,0)))) + '</НомерПП>' + CHAR(10) + 		
				SPACE(5) + '<ФИО>'  + CHAR(10) + 
					SPACE(6) + '<Фамилия>' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,1,','),'')))) + '</Фамилия>' + CHAR(10) + 		
					SPACE(6) + '<Имя>' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,2,','),'')))) + '</Имя>' + CHAR(10) + 		
					SPACE(6) + '<Отчество>' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,3,','),'')))) + '</Отчество>' + CHAR(10) + 										
				SPACE(5) + '</ФИО>'  + CHAR(10) + 
				SPACE(5) + '<НомерСправкиОчленствеВстудОтряде>' + LTRIM(RTRIM(ISNULL(NUM_SPR1,''))) + '</НомерСправкиОчленствеВстудОтряде>' + CHAR(10) + 										
				SPACE(5) + '<ДатаВыдачиСправкиОчленствеВстудОтряде>' + LTRIM(RTRIM(ISNULL(DATE_SPR1,''))) + '</ДатаВыдачиСправкиОчленствеВстудОтряде>' + CHAR(10) + 	
				SPACE(5) + '<НомерСправкиОбОчномОбучении>' + LTRIM(RTRIM(ISNULL(NUM_SPR2,''))) + '</НомерСправкиОбОчномОбучении>' + CHAR(10) + 										
				SPACE(5) + '<ДатаВыдачиСправкиОбОчномОбучении>' + LTRIM(RTRIM(ISNULL(DATE_SPR2,''))) + '</ДатаВыдачиСправкиОбОчномОбучении>' + CHAR(10) + 										
				SPACE(5) + '<СуммыВыплатИвознаграждений>'  + CHAR(10) + 
					SPACE(6) + '<СуммаВсегоСначалаРасчетногоПериода>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM_ALL,0)))) + '</СуммаВсегоСначалаРасчетногоПериода>' + CHAR(10) +
					SPACE(6) + '<СуммаПоследние1месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM1,0)))) + '</СуммаПоследние1месяц>' + CHAR(10) +	
					SPACE(6) + '<СуммаПоследние2месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM2,0)))) + '</СуммаПоследние2месяц>' + CHAR(10) +	
					SPACE(6) + '<СуммаПоследние3месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM3,0)))) + '</СуммаПоследние3месяц>' + CHAR(10) +	
				SPACE(5) + '</СуммыВыплатИвознаграждений>'  + CHAR(10) + 
			SPACE(4) + '</СведенияОбОбучающемся>'
		FROM #STUD				


		UNION ALL SELECT @lcFNAME, 
			SPACE(4) + '<ИтогоВыплат>' + CHAR(10) +
					SPACE(5) + '<СуммаВсегоСначалаРасчетногоПериода>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SM_ALL,0))))) + '</СуммаВсегоСначалаРасчетногоПериода>' + CHAR(10) +			
					SPACE(5) + '<СуммаПоследние1месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SM1,0))))) + '</СуммаПоследние1месяц>' + CHAR(10) +
					SPACE(5) + '<СуммаПоследние2месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SM2,0))))) + '</СуммаПоследние2месяц>' + CHAR(10) +
					SPACE(5) + '<СуммаПоследние3месяц>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SM3,0))))) + '</СуммаПоследние3месяц>' + CHAR(10) +
			SPACE(4) + '</ИтогоВыплат>' 
		FROM #STUD	

	if (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 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СведенияОВыплатахВпользуОбучающихся>'	
END

--end

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) 
SELECT @lcFNAME, 
	SPACE(3) + '<ЛицоПодтверждающееСведения>1</ЛицоПодтверждающееСведения>' + CHAR(10) +
	SPACE(3) + '<ФИОлицаПодтверждающегоСведения>' + CHAR(10) +
		SPACE(4) + '<Фамилия>' + UPPER(LTRIM(RTRIM(ISNULL(O.FM,'')))) + '</Фамилия>'  + CHAR(10) +
		SPACE(4) + '<Имя>' + UPPER(LTRIM(RTRIM(ISNULL(O.IM,'')))) + '</Имя>'  + CHAR(10) +
		SPACE(4) + '<Отчество>' + UPPER(LTRIM(RTRIM(ISNULL(O.OT,'')))) + '</Отчество>' + CHAR(10) +
	SPACE(3) + '</ФИОлицаПодтверждающегоСведения>' + CHAR(10) +
	SPACE(3) + '<НаименованиеОрганизацииПредставителя>' + UPPER(LTRIM(RTRIM(ISNULL(d.FULL_NAME,'')))) + '</НаименованиеОрганизацииПредставителя>' + CHAR(10) +
	SPACE(3) + '<ДокументПодтверждающийПолномочияПредставителя>' + CHAR(10) +
		SPACE(4) + '<НаименованиеУдостоверяющего>' + UPPER(LTRIM(RTRIM(ISNULL(F.NAME,'')))) + '</НаименованиеУдостоверяющего>'  + CHAR(10) +
		SPACE(4) + '<СерияРимскиеЦифры>' + case when f.code='21' then substring(p.doc_num,1,2) else ' ' end + '</СерияРимскиеЦифры>'  + CHAR(10) +
		SPACE(4) + '<СерияРусскиеБуквы>' + case when f.code='21' then substring(p.doc_num,4,2) else ' ' end + '</СерияРусскиеБуквы>' + CHAR(10) +
		SPACE(4) + '<НомерУдостоверяющего>' + case when f.code='21' then substring(p.doc_num,7,7) else ' ' end + '</НомерУдостоверяющего>'  + CHAR(10) +
		SPACE(4) + '<ДатаВыдачи>' + LTRIM(RTRIM(ISNULL(convert(varchar(10),p.doc_date,104),''))) + '</ДатаВыдачи>' + CHAR(10) +
		SPACE(4) + '<КемВыдан>' + UPPER(LTRIM(RTRIM(ISNULL(p.DOC_WHOM,'')))) + '</КемВыдан>' + CHAR(10) +
	SPACE(3) + '</ДокументПодтверждающийПолномочияПредставителя>' 
FROM dbo.GetOtvFaceData(@LINK_DEP, 'Руководитель') O
inner join EMPL e on e.link = o.link_empl
inner join PERSON p on p.link = e.pers_link
inner join FACE_DOCUMENT f on f.link = p.doc_link
inner join DICTIONARY_DEPARTMENT d on d.link = @LINK_DEP


INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) 
SELECT @lcFNAME, SPACE(3) + '<ДатаЗаполнения>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),@modify_date,104),''))) + '</ДатаЗаполнения>'

--Заверешение
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(2) + '</РАСЧЕТ_ПО_СТРАХОВЫМ_ВЗНОСАМ_НА_ОПС_И_ОМС_ПЛАТЕЛЬЩИКАМИ_СВ_ПРОИЗВОДЯЩИМИ_ВЫПЛАТЫ_ФЛ_НАЧИНАЯ_С_2013_ГОДА>'
	UNION ALL SELECT @lcFNAME, SPACE(1) + '</ПачкаВходящихДокументов>'
  UNION ALL SELECT @lcFNAME, SPACE(0) + '</ФайлПФР>'	

SET NOCOUNT OFF

select * from #OUTPUT order by [ID]











GO


GRANT EXECUTE ON dbo.[SA_RSV1_EXPORT_0700_2013] TO PUBLIC

GO




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

GO
CREATE PROCEDURE dbo.BK_UPDATE_OUT_TABLE_OSNOV
	@intLINK_UP		int,
	@intOBJECT		int,
	@intDICTION		int
AS
BEGIN
	DECLARE
		@intERROR	int,
		@intRowCount	int,
		@inttrancount	int

	SET @inttrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON

	IF @intDICTION IS NULL 
		DELETE FROM dbo.OUT_TABLE_OSNOV WHERE LINK_UP = @intLINK_UP AND OBJECT = @intOBJECT
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN 7
		END
	ELSE
	BEGIN
		SELECT @intDICTION = (Select LINK FROM dbo.OSNOV WITH (ROWLOCK) WHERE LINK = @intDICTION)

		SELECT
			@intERROR = @@ERROR,
			@intRowCount = @@ROWCOUNT
			
		IF @intERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN 7
		END

		IF @intRowCount = 0
		BEGIN
			ROLLBACK TRAN
			RETURN 3
		END

		UPDATE dbo.OUT_TABLE_OSNOV
		SET OSNOV = @intDICTION
		WHERE LINK_UP = @intLINK_UP
			AND [OBJECT] = @intOBJECT
			
		SELECT
			@intERROR = @@ERROR,
			@intRowCount = @@ROWCOUNT
			
		IF @intERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN 7
		END

		IF @intRowCount = 0
		BEGIN
			INSERT INTO OUT_TABLE_OSNOV (LINK_UP, [OBJECT], OSNOV)
			VALUES (@intLINK_UP, @intOBJECT, @intDICTION)
			IF @@ERROR <> 0
			BEGIN
				ROLLBACK TRAN
				RETURN 7
			END
		END
	END
	
	IF @@TRANCOUNT > @inttrancount
		COMMIT TRAN

	RETURN 0
END

GO

GRANT EXECUTE ON dbo.[BK_UPDATE_OUT_TABLE_OSNOV] 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_BB_REESTR_DEN_SR]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[X_SAVE_BB_REESTR_DEN_SR]
GO





CREATE     
PROCEDURE dbo.X_SAVE_BB_REESTR_DEN_SR
	@iLINK		int	OUTPUT,
	@cNUMBER		char(25) = null,
	@dDATE		datetime = null,
	@nSumma		numeric(19,2) = 0,
	@cComment		varchar(254) = null,
	@iDEP_LINK       INT = null,
	@iACC_LINK       INT = null,
	@iBACC_LINK       INT = null,
	@iCARD_LINK       INT = null,
	@iOSNOV_LINK       INT = null
	

AS
SET LOCK_TIMEOUT 30000
SET IMPLICIT_TRANSACTIONS ON
DECLARE @iERROR	tinyint,
		@cVALUE	varchar(7000),
		@cEventText	varchar(254),
		@itrancount	int,
		@iLinkObj	int,
		@iParam	int

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

	SELECT @iLinkObj = LINK FROM S_OBJECTS WHERE CODE = 'BB_REESTR_DEN_SR'

	EXECUTE @iERROR = dbo.X_UPDATE_G_PROV @iLINK OUTPUT, @cNUMBER, @dDATE, @iLinkObj, NULL, @nSumma, @cComment,0,@iDEP_LINK,@iACC_LINK

	SELECT @iParam = LINK FROM S_OBJECTS WHERE CODE = 'BB_REESTR_DEN_SR_CARD_LINK'
	--карта
	EXECUTE @iERROR = dbo.BK_UPDATE_G_PROV_CARD @iLINK, @iParam, @iCARD_LINK
	IF @iERROR <> 0
		RETURN @iERROR

	SELECT @iParam = LINK FROM S_OBJECTS WHERE CODE = 'BB_REESTR_DEN_SR_BACC_LINK'
	--Получатель
	EXECUTE @iERROR = dbo.X_UPDATE_G_PROV_DEP_ACCT @iLINK, @iParam, @iBACC_LINK
	IF @iERROR <> 0
		RETURN @iERROR

	SELECT @iParam = LINK FROM S_OBJECTS WHERE CODE = 'BB_REESTR_DEN_SR_OSNOV_LINK'
	--карта
	EXECUTE @iERROR = dbo.X_UPDATE_G_PROV_OSNOV @iLINK, @iParam, @iOSNOV_LINK
	IF @iERROR <> 0
		RETURN @iERROR

	
		--Событие системного журнала
	SET @cEventText = 'Заявка на получение денежных средств, перечисляемых на карту' + ' №' + RTRIM(@cNUMBER) + ' от ' + convert(varchar, @dDATE, 104)
	EXECUTE WF_GENERATEEVENT 'Сохранение документа', @cEventText, @iLinkObj, 'G_PROV', @iLINK

IF @@TRANCOUNT > @iTrancount
	COMMIT TRAN
RETURN 0





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE PROCEDURE dbo.BB_ZKR_CREATE_RESTR_DEN_SR
	@iLinkZKR	INT,
	@iLinkReestr INT output
AS


declare	@iObjCode 	VARCHAR(100),
		@cNumber	VARCHAR(25),
		@dDate		DATETIME,
		@nSum		NUMERIC(28,2),
		@iDep	INT,
		@iAcc	INT,
		@iBACC	INT,
		@iOsnov int,
		
		@iKBK 	INT,
		@iEKR 	INT,
		@iTabLink int,
		@iOrders int,
		
		@iRet int
		
		

select	@iDep = DEP,
		@iAcc = ACC,
		@dDate = [DATE],
		@nSum = SUMMA
from dbo.G_PROV
where LINK = @iLinkZKR

select	@iBACC = D_Acc
from dbo.FINANSE_PAYS
where LINK = @iLinkZKR
	
SELECT @iObjCode = CODE -- Линк и Код объекта для нового документа
FROM dbo.S_OBJECTS
WHERE CODE = 'BB_REESTR_DEN_SR'


EXEC X_DOCUMENT_GET_NEXT_NUMBER @iObjCode, @cNumber OUTPUT, @iDep   -- Номер нового документа 
-- Находим лик на договор в Основаниях, если нет то добавляем
EXEC dbo.BB_OSNOV_DOC @iOsnov OUTPUT, @iLinkZKR, 'BB_ZAYAVKA_KR'

-- Заводим новый документ
EXECUTE @iRet = dbo.X_SAVE_BB_REESTR_DEN_SR	@iLinkReestr OUTPUT, @cNumber, @dDate, @nSum, 'Документ сформирован на основе заявки на кассовый расход', @iDep, @iAcc, @iBACC, NULL, @iOsnov  
	IF @iRet <> 0
	BEGIN
		ROLLBACK
		RETURN @iRet	
	END

-- Курсор с сумами и линками документов
DECLARE SUM_DOC_CUR CURSOR LOCAL STATIC READ_ONLY FOR
SELECT  LINK_KBK, LINK_SGU, SUMMA
FROM dbo.ZAYAVKA_KR_TABLE
where LINK_UP = @iLinkZKR 

OPEN SUM_DOC_CUR
FETCH NEXT FROM SUM_DOC_CUR INTO @iKBK, @iEKR, @nSum
set @iOrders = 1
WHILE @@FETCH_STATUS = 0
BEGIN
	EXECUTE @iRet = dbo.X_SAVE_BB_REESTR_DEN_SR_TABLE @iTabLink, @iLinkReestr, @iOrders, null, @iEKR, @iKBK, @nSum
		IF @iRet <> 0
	BEGIN
		ROLLBACK
		RETURN @iRet	
	END
	FETCH NEXT FROM SUM_DOC_CUR INTO @iKBK, @iEKR, @nSum
	set @iOrders = @iOrders + 1
END
CLOSE SUM_DOC_CUR
DEALLOCATE SUM_DOC_CUR	




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on dbo.BB_ZKR_CREATE_RESTR_DEN_SR to public
GO

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

GO
--- Выгрузка ОС ---
CREATE PROCEDURE dbo.BK_EXPORT_INV1
	(
	@dDATE1		DATETIME,
	@cMAX_COST	VARCHAR (100),
	@iMODE		TINYINT	= 0
	)
AS
BEGIN
	DECLARE 
		@F_NAME	VARCHAR (100),
		@nMAX_COST	NUMERIC (20),
		@DATE_END	DATETIME,
		@FILE_NAME	VARCHAR (10)

	-- Данные Учреждения
	IF OBJECT_ID('tempdb..#DEPARTMENTS') IS NOT NULL 
		DROP TABLE #DEPARTMENTS

	CREATE TABLE #DEPARTMENTS(
		LINK INT
		,KPP	VARCHAR(9)
		,INN	VARCHAR(13)
		,NAME	VARCHAR(254)
		,[TYPE] VARCHAR(60)
		)

	INSERT INTO #DEPARTMENTS  
		(
		LINK
		,KPP
		,INN
		,NAME
		,[TYPE]
		)
	SELECT 
		LINK	= D.LINK
		,KPP	= D.KPP
		,INN	= D.INN
		,NAME	= D.NAME
		,[TYPE]	= DBT.BT_NAME1
	FROM dbo.DEPARTMENTS D
	INNER JOIN dbo.DICTIONARY_BUH_TYPE DBT ON (DBT.BUH_TYPE = D.BUH_TYPE)
	WHERE d.LINK = ISNULL (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())

	IF dbo.CheckIsNumeric (ISNULL (@cMAX_COST, '')) = 1
		SET @nMAX_COST = CONVERT (NUMERIC (20), @cMAX_COST) * 1000
	ELSE
		SET @nMAX_COST = 300000

	-- Остатки
	IF OBJECT_ID('tempdb..#REST') IS NOT NULL 
		DROP TABLE #REST
		
	CREATE TABLE #REST
		(
		ID			INT IDENTITY
		,[DATE]		DATETIME
		,DEP_LINK	INT
		,INV		INT
		,QTY		NUMERIC(28,2)
		,BALANS		NUMERIC(28,2)
		,AMORT		NUMERIC(28,2)
		,LAST_SUM	NUMERIC(28,2),
		COST		NUMERIC(28,2)
		)

	INSERT INTO #REST
		(
		[DATE]		
		,DEP_LINK		
		,INV		
		,QTY		
		,BALANS		
		,AMORT		
		,LAST_SUM,
		COST
		)
	SELECT
		@dDATE1,
		R1.DEP_LINK,
		R1.INV,
		SUM (R1.QTY),
		SUM (R1.BALANS),
		SUM (R1.AMORT),
		SUM (R1.LAST_SUM),
		CASE
			WHEN SUM (R1.QTY) = 0 THEN SUM (R1.BALANS)
			ELSE SUM (R1.BALANS) / SUM (R1.QTY)
		END
	FROM dbo.BK_GetTableRestINV
		(@dDATE1,
		DEFAULT,
		DEFAULT) R1
	INNER JOIN #DEPARTMENTS D ON (D.LINK = R1.DEP_LINK)
	GROUP BY
		R1.DEP_LINK,
		R1.INV
	HAVING
		SUM (R1.QTY) <> 0
		OR SUM (R1.BALANS) <> 0
	SET @DATE_END = DATEADD (DAY, -1, @dDATE1)

	EXEC dbo.GetRandStr
		5,
		@FILE_NAME OUTPUT
		
	SET @FILE_NAME = 'INV' + LTRIM (@FILE_NAME)
	
	SELECT
		F_NAME = CONVERT (VARCHAR (8), @FILE_NAME),
		OUT_TEXT = 'DBF',
		TYP = CASE
					WHEN LEFT (SA1.cANALIT, 1) = '2' THEN 2
					ELSE 1
				END,
		NAME = CONVERT (VARCHAR (250), INV.NAME),
		MARKA = CONVERT (VARCHAR (250), ISNULL (AS1.PASSPORT, '')),
		INOD = CONVERT (VARCHAR (14), INV.CODE),
		DAT_EKS = ISNULL (CONVERT (VARCHAR (100), AS1.DATE_PROD, 104), ''),
		COST2 = CONVERT (NUMERIC (15,2), R1.BALANS),
		COST = CONVERT (NUMERIC (15,2), R1.LAST_SUM), 
		DATE_BUH = O1.DATE_OPER
	FROM #REST R1
	INNER JOIN dbo.INVENTORY INV ON (INV.LINK = R1.INV)
	INNER JOIN dbo.NOMENCLATURE NOM ON (NOM.LINK = INV.NOMENCLATURE)
	INNER JOIN dbo.GROUP_INV GR1 ON (GR1.LINK = NOM.GROUP_INV)
	LEFT JOIN dbo.S_ACCOUNTS SA1 ON (SA1.LINK = GR1.ACCOUNT
		AND SA1.ZABALANS = 0)
	LEFT JOIN dbo.ASSETS AS1 ON (AS1.LINK_UP = INV.LINK)
	LEFT JOIN dbo.BK_GetTableOperINV
		(DEFAULT,
		DEFAULT,
		@DATE_END,
		2,
		DEFAULT
		)	O1 ON (O1.INV = INV.LINK AND R1.DEP_LINK = O1.DEP_LINK)
	WHERE R1.COST < @nMAX_COST

	DROP TABLE #DEPARTMENTS
	DROP TABLE #REST

	RETURN 0
END

GO

GRANT EXECUTE ON dbo.[BK_EXPORT_INV1] 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(100),
					DATE_BEG datetime,
					DATE_END datetime,
					[PROC] numeric(7,3),
					[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 isnull(S.KT_AP1, S.DT_AP1), S.DATE_PROV, sum(S.SUMMA), 0, 0, 0
from dbo.AProvByBufferConditions(@dDateB, @dDateE, NULL, 'CREDIT_ACC_11',
			 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_11', 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,null,'SGU_K',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 @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

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
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
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] = 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] = 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
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
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] = 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] = 4
order by 1

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].[BB_EXPORT_SPR]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BB_EXPORT_SPR]
GO


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

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

AS 
declare @iSum int
set @iSum = 0
-- Таблица 1
-- Код справочника
select  LINK = 0,
	LINK_UP = 0,
	KOD_SPR = case @cObjCode when 'BI_DICTION_INCOME'  	then 'DICTIONARY_INCOME'
				 when 'BI_DICTION_EXP' 	   	then 'DICTIONARY_EXPEND'
				 when 'BI_DICTION_IVF'	   	then 'DICTIONARY_SOURCE'
				 when 'BI_DICTION_KBK2'		then 'DICTIONARY_KBK_INC'
				 when 'BI_DICTION_KBK1'   	then 'DICTIONARY_KBK_EXP'
				 when 'BI_DICTION_KBK4'   	then 'DICTIONARY_KBK_SOURCE'
				 when 'BD_DOP_CLASSIF' 	   	then 'DICTIONARY_ADD_BK'
				 when 'BI_DICTION_DIV' 	   	then 'DICTIONARY_DIVISION'
				 when 'DICTIONARY_TARGET_PROG' 	then 'DICTIONARY_PROGRAM'
				 when 'BI_DICTION_CSR' 	  	then 'DICTIONARY_TARGET_ITEM'
				 when 'DICTIONARY_ITEM'   	then 'DICTIONARY_ITEM'
				 when 'DICTIONARY_KOSGU'   	then 'DICTIONARY_ITEM'
				 when 'DICTIONARY_BANK'   	then 'DICTIONARY_BANK'
				 when 'DICTIONARY_DEPARTMENT'	then 'DICTIONARY_CORR'
				 when 'DICTIONARY_TREASURY'	then 'DICTIONARY_CORR'
				 when 'DICTIONARY_ACCOUNTS'	then 'DICTIONARY_ACCOUNT'
				 when 'DICTIONARY_K_ACCOUNTS'	then 'DICTIONARY_ACCOUNT'
				 when 'BB_DICTION_PROG'	then 'DICTIONARY_PROGRAM'
				 
		 end


-- Таблица 2
-- в зависимости от справочника
IF @cObjCode = 'BI_DICTION_INCOME'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME] = LNAME,
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = '',
		BUDGET = '',
		[ORDER] = '',
		PARENT = ''
	from dbo.KL_KD
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BI_DICTION_EXP'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME] = [LNAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = '',
		BUDGET = '',
		[ORDER] = '',
		PARENT = ''  
	from dbo.KL_EXPEND
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BI_DICTION_IVNESHF'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = '',
		BUDGET = '',
		[ORDER] = '',
		PARENT = ''  
	from dbo.BI_DICTION_IVNESHF
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BI_DICTION_IVF'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = '',
		BUDGET = '',
		[ORDER] = '',
		PARENT = ''  
	from dbo.BI_DICTION_IVF
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BB_DICTION_PROG'
begin
	select 	LINK,
			LINK_UP = LINK,
			CODE, 
			[SNAME] = cast([NAME] as varchar(45)),
			[NAME] = [LNAME],
			DATE_BEGIN = cast(null as datetime),  
			DATE_END = cast(null as datetime),
		[LEVEL] = '',
		BUDGET = '',
		[ORDER] = '',
		PARENT = '' 
	from dbo.KL_PROG
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end IF @cObjCode = 'BD_DOP_CLASSIF'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime) ,
		[LEVEL] = '',
		BUDGET = '',
		[ORDER] = '',
		PARENT = '' 
	from dbo.DOP_CLASSIF
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BI_DICTION_DIV'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME] = [LNAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = '',
		BUDGET = '',
		[ORDER] = '',
		PARENT = ''   
	from dbo.KL_DIVISION
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'DICTIONARY_TARGET_PROG'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = '',
		BUDGET = '',
		[ORDER] = '',
		PARENT = ''   
	from dbo.DICTIONARY_TARGET_PROG
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BI_DICTION_CSR'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME]  = cast([NAME] as varchar(512)),
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = '',
		BUDGET = '',
		[ORDER] = '',
		PARENT = '' 
	from dbo.BI_DICTION_CSR
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'DICTIONARY_ITEM' or @cObjCode = 'DICTIONARY_KOSGU'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = '',
		BUDGET = '',
		[ORDER] = '',
		PARENT = ''   
	from dbo.DICTIONARY_ITEM               
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 

IF left(@cObjCode,14) = 'BI_DICTION_KBK'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE = cast(replace(CODE,'.','') as varchar(20)), 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME] ,
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = '',
		BUDGET = '',
		[ORDER] = '',
		PARENT = ''  
	from dbo.KL_KBK               
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 

IF @cObjCode = 'DICTIONARY_BANK'
begin
	select 	LINK,
		LINK_UP = LINK,
		BIC = cast(replace(BIK,'.','') as varchar(20)), 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME] = FNAME,
		KS,
		CITY,
		STATE = 1  
	from dbo.DICTIONARY_BANK                
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by BIK
	set @iSum = @@rowcount 
end 

IF @cObjCode = 'DICTIONARY_DEPARTMENT'
begin
	select 	LINK,
		LINK_UP = LINK,
		INN     = cast(INN_LONG as char(12)),
		CODE_BP = cast(BUDG as char(5)),
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME]  = [FULL_NAME],
		CPPU	= KPP,	
		OKATO	= cast(replace(OKATO,' ','') as char(11)),
		ADRESS  = isnull(rtrim(cast(dbo.GetAddressByKladr(REF_LINK_A) + CASE when HOUSE is null or HOUSE = '' then '' else ' ,' + HOUSE end   as varchar(100))),'')
	from dbo.DICTIONARY_DEPARTMENT D                
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by INN
	set @iSum = @@rowcount 
end 

IF @cObjCode = 'DICTIONARY_TREASURY'
begin
	select 	LINK,
		LINK_UP = LINK,
		INN,
		CODE_BP = '',
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME]  = [FULL_NAME],
		CPPU	= KPP,	
		OKATO	= '',
		ADRESS  = isnull(rtrim(cast(dbo.GetAddressByKladr(REF_LINK_A) + CASE when HOUSE is null or HOUSE = '' then '' else ' ,' + HOUSE end   as varchar(100))),'')
	from dbo.DICTIONARY_TREASURY                
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by INN
	set @iSum = @@rowcount 
end 

IF @cObjCode = 'DICTIONARY_ACCOUNTS'
begin
	select 	DA.LINK,
		LINK_UP    = DA.LINK,
		CACCOUNT   = DA.CODE,
		ACC_TYPE   = '',
		ACC_VID    = '',
		STATE      = 1,
		CCORR      = D.INN_LONG,
		CORR_BP    = cast(D.BUDG as char(5)),
		CORR_SNAME = cast(D.[NAME] as varchar(20)),
		BANK_BIC   = isnull(B.BIK,''),
		BANK_KS	   = isnull(B.KS,''),	
		BANK_SNAME = isnull(cast(B.[NAME] as varchar(100)),''),
		TOP_ACC    = isnull(TA.CODE,'')
	from dbo.DEPARTMENT_ACCOUNTS DA
	inner join dbo.DICTIONARY_DEPARTMENT D on DA.LINK_UP = D.LINK and D.LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))               
	left join dbo.BANKS B on B.LINK = DA.BANK_LINK and DA.BANK_LINK is not null
	left join dbo.TREASURY_ACCOUNTS TA on DA.TA_LINK = TA.LINK  and DA.TA_LINK is not null
	order by DA.CODE
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'DICTIONARY_K_ACCOUNTS'
begin
	select 	TA.LINK,
		LINK_UP    = TA.LINK,
		CACCOUNT   = TA.CODE,
		ACC_TYPE   = '',
		ACC_VID    = '',
		STATE      = 1,
		CCORR      = T.INN,
		CORR_BP    = '',
		CORR_SNAME = cast(T.[NAME] as varchar(20)),
		BANK_BIC   = isnull(B.BIK,''),
		BANK_KS	   = isnull(B.KS,''),	
		BANK_SNAME = isnull(cast(B.[NAME] as varchar(100)),''),
		TOP_ACC    = ''
	from dbo.TREASURY_ACCOUNTS TA
	inner join dbo.TREASURY T on TA.LINK_UP = T.LINK and T.LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))               
	left join dbo.BANKS B on B.LINK = TA.BANK_LINK               
	order by TA.CODE
	set @iSum = @@rowcount 
end 


-- Таблица 3
-- Колличество записей
select  LINK = 0,
	LINK_UP = 0,
	[SUM] = @iSum



GO


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


END

GO

GRANT EXECUTE ON dbo.[BK_PRINTDOC_AVANSE_REP] TO PUBLIC

GO

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

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

GO

CREATE    PROCEDURE dbo.SA_N_VAC_FILL1 
(
 @LINK_DOC INT OUTPUT, --Ссылка на документ.	
 @OBJ_CODE VARCHAR(50), --Код объекта
 @SR_VID TINYINT = 1, -- Прочие расчеты по среднему 1 - Компенсация за отпуск, 2 - прочее
 @LINK_VAC INT, --Ссылка на приказ
 @SR_LINK_EMPL INT  = NULL, --Прочие расчеты по среднему  Ссылка на сотрудника
 @LINK_PAYS INT = NULL, --Ссылка на вид начисления
 @TYP_PERIOD TINYINT  = NULL, --Тип расчетного периода: 1- 3 месяца, 2 - 12 месяцев
 @VID_DAYS TINYINT  = NULL,-- Способ расчета 1 - в рабочих днях, 2 - в календарных днях
 @SR_DATE1 DATETIME  = NULL,--  для расчета прочих начислений по среднему Дата начала
 @SR_DATE2 DATETIME  = NULL,--  для расчета прочих начислений по среднему Дата окончания
 @SR_DATE DATETIME  = NULL,--  для расчета прочих начислений по среднему Дата начала расчетного периода
 @RECALC TINYINT = 0, -- 0 Полный расчет. расчет начинается с таблицы 3 
			-- 1 - не надо рассчитывать по видам начислений
			-- 2 - не надо рассчитывать по месяцам
			-- 3 - не надо рассчитывать средние суммы
 @OPER TINYINT = 0, -- 1 - сформировать операции
 @LINK_DEP INT = NULL
)
AS

SET NOCOUNT ON

-- Определение типа расчетного периода
SET @TYP_PERIOD = CASE WHEN COALESCE(@TYP_PERIOD,0) = 0 THEN
			CASE RTRIM(LTRIM(@OBJ_CODE))
				WHEN 'DOCUMENTS_ADD_FURLOUGH' THEN dbo.sa_get_option_by_code('FURLOUGH_OPT2')
				WHEN 'DOCUMENTS_CALC_TRAVEL' THEN dbo.sa_get_option_by_code('CALC_TRAVEL_OPT1')
				WHEN 'DOCUMENTS_CALC_AVG' THEN 1
				ELSE NULL
			END
		ELSE @TYP_PERIOD END
-- Определение способа расчета
SET @VID_DAYS = CASE WHEN COALESCE(@VID_DAYS,0) = 0 THEN
			CASE RTRIM(LTRIM(@OBJ_CODE))
				WHEN 'DOCUMENTS_ADD_FURLOUGH' THEN dbo.sa_get_option_by_code('FURLOUGH_OPT3')
				WHEN 'DOCUMENTS_CALC_TRAVEL' THEN dbo.sa_get_option_by_code('CALC_TRAVEL_OPT2')
				WHEN 'DOCUMENTS_CALC_AVG' THEN 2
				ELSE NULL
			END
		ELSE @VID_DAYS END
---инит
DECLARE 
 @LINK_EMPL INT, --Ссылка на сотрудника
 @DATE_BEGIN DATETIME, --Начало отпуска, командировки
 @DATE_BEGIN2 DATETIME, --Начало отпуска, командировки
 @DATE_END DATETIME, --Окончание отпуска, командировки
 @REF_TYP INT, --Ссылка на вид отпуска, командировки
 @order_link int, 
 @NEW_DATE_END DATETIME,
 @NEW_DATE_BEG DATETIME,
 @UCHET_PREM TINYINT,
 @comment varchar(100),
 @HOLIDAY TINYINT,
 @NO_RAION TINYINT

DECLARE @UNAME VARCHAR(30)
SET @UNAME = CASE WHEN DBO.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPT10') = 1 THEN COALESCE(dbo.AdminGetUserFIO(default),'') ELSE '' END
SET @UNAME = @UNAME + CASE WHEN LEN(@UNAME) > 0 THEN ':' ELSE '' END

IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_ADD_FURLOUGH'
BEGIN

	SELECT @LINK_EMPL = EMPL_LINK, @LINK_PAYS = COALESCE(@LINK_PAYS,LINK_PAYS), 
		@DATE_BEGIN = DATE_BEGIN,
		@SR_DATE = COALESCE(@SR_DATE, (select min(DATE_BEGIN) from dbo.ITEM_VACATION IV1 WHERE IV1.order_link = IV.order_link and IV1.EMPL_LINK = IV.EMPL_LINK)), 
		@DATE_END = DATE_END,
		@REF_TYP = IV.TYPE_LINK, @order_link = order_link,
		@comment = @UNAME + 'Начисл.отпускных:' + COALESCE(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM(VV.[NAME])),30) + ' №'+RTRIM(LTRIM([NUMBER])) + ' от ' + CONVERT(VARCHAR(10),[DATE],104),
		@HOLIDAY = VV.HOLIDAY, --С учетом праздничных
		@LINK_DEP = COALESCE(@LINK_DEP,O.DEP_LINK)
	FROM dbo.ORDERS O INNER JOIN dbo.ITEM_VACATION IV ON IV.ORDER_LINK = O.LINK
		INNER JOIN dbo.VACATION_VID VV ON IV.TYPE_LINK = VV.LINK WHERE IV.LINK = @LINK_VAC

	DECLARE	@DATE_BREAK DATETIME	-- дата отзыва из отпуска
	DECLARE	@DATE_BREAK_NEW_BEGIN DATETIME	-- дата отзыва из отпуска

	-- Уменьшение: об отзыве, о выходе из отпуска по уходу за ребенком
	IF EXISTS(SELECT * FROM ITEM_VACATION_BREAK IVB WHERE IVB.ACTIVE = 1 AND ISNULL(BREAK_WORK_DAYS,0) != 0 AND IVB.VAC_LINK = @LINK_VAC) BEGIN

		DECLARE @BREAK_WORK_DAYS INT	-- количество рабочих дней отзва
		DECLARE @LEN_KAL_DAYS INT	-- количество календарных дней продления
		DECLARE @EMPL_LINK INT		-- ссылка на сотрудника
		--
		SELECT	TOP 1
			@EMPL_LINK = EMPL_LINK,
			@DATE_BREAK = DATE_BREAK,
			@BREAK_WORK_DAYS = BREAK_WORK_DAYS,
			@LEN_KAL_DAYS = LEN_KAL_DAYS
		FROM	ITEM_VACATION_BREAK IVB
		WHERE	IVB.ACTIVE = 1
			AND ISNULL(BREAK_WORK_DAYS,0) != 0
			AND IVB.VAC_LINK = @LINK_VAC
		--
		SET ROWCOUNT @BREAK_WORK_DAYS
		SELECT	T.DATE
		INTO	#TEMP_TABLE
		FROM
		(
		SELECT	[DATE]  = dbo.ConvertDMY2Date(GD.DAY, MONTH(G.PERIOD), Year(G.PERIOD)),
			[HOURS] = MAX(HOURS)
		FROM	GRAPHICS G INNER JOIN dbo.GRAPHIC_DAYS GD ON GD.LINK_UP=G.LINK 
		WHERE	G.GRAPH_LINK = dbo.kd_GetEmplGr(@EMPL_LINK)
			AND dbo.ConvertDMY2Date(GD.DAY, MONTH(G.PERIOD), Year(G.PERIOD)) BETWEEN @DATE_BREAK AND @DATE_BREAK + @BREAK_WORK_DAYS + @LEN_KAL_DAYS
		GROUP	BY dbo.ConvertDMY2Date(GD.DAY, MONTH(G.PERIOD), Year(G.PERIOD))
		) T
		WHERE	T.HOURS > 0
			AND T.DATE >= @DATE_BREAK
		SET ROWCOUNT 0
		--
		SET @DATE_BREAK_NEW_BEGIN = (SELECT TOP 1 DATE + 1 FROM #TEMP_TABLE ORDER BY DATE DESC)
		SET @NEW_DATE_END = @DATE_END + @LEN_KAL_DAYS - 1 + 1  -- расчет окончания отпуска с учетом отзыва
	
		DROP TABLE #TEMP_TABLE
		SET @DATE_END = COALESCE(@NEW_DATE_END,@DATE_END)

	END 
	ELSE BEGIN
		SET @NEW_DATE_END = (SELECT MIN(ivb.DATE_BREAK - 1) FROM dbo.item_vacation iv inner join dbo.item_vacation_break ivb on ivb.vac_link = iv.link WHERE ivb.ACTIVE = 1 AND iv.LINK = @LINK_VAC)
		SET @DATE_END = (CASE WHEN COALESCE(@NEW_DATE_END,@DATE_END) <  @DATE_END THEN COALESCE(@NEW_DATE_END,@DATE_END) ELSE @DATE_END END)
	END
	-- Увеличение: о продлении по болезни
	SET @NEW_DATE_END = (SELECT MAX(ivb.NEW_DATE_END) FROM item_vacation iv inner join item_vacation_dis ivb on ivb.vac_link = iv.link WHERE  ivb.ACTIVE = 1 AND iv.LINK = @LINK_VAC)
	SET @DATE_END = (CASE WHEN COALESCE(@NEW_DATE_END,@DATE_END) >  @DATE_END THEN COALESCE(@NEW_DATE_END,@DATE_END) ELSE @DATE_END END)

END


IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_TRAVEL'
BEGIN
	SELECT @LINK_EMPL = EMPL_LINK, @LINK_PAYS = COALESCE(@LINK_PAYS,LINK_PAYS), 
		@SR_DATE = COALESCE(@SR_DATE, DATE_BEGIN), 
		@DATE_BEGIN = DATE_BEGIN, @DATE_END = DATE_END, 
		@REF_TYP = IT.TYPE_LINK,
		@comment = @UNAME + 'Начисл.командир.:' + COALESCE(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM(KV.[NAME])),30) + ' №'+RTRIM(LTRIM([NUMBER])) + ' от ' + CONVERT(VARCHAR(10),[DATE],104),
		@LINK_DEP = COALESCE(@LINK_DEP,O.DEP_LINK)
	FROM dbo.ORDERS O INNER JOIN dbo.item_travel IT ON IT.ORDER_LINK = O.LINK
		INNER JOIN dbo.KOMAND_VID KV ON IT.TYPE_LINK = KV.LINK WHERE IT.LINK = @LINK_VAC

	-- Увеличение: о продлении 
	SET @NEW_DATE_END = (SELECT MAX(ivb.NEW_DATE_END) FROM item_travel iv inner join item_travel_long ivb on ivb.TRAVEL_LINK = iv.link WHERE ivb.ACTIVE = 1 AND iv.LINK = @LINK_VAC)
	SET @DATE_END = (CASE WHEN COALESCE(@NEW_DATE_END,@DATE_END) >  @DATE_END THEN COALESCE(@NEW_DATE_END,@DATE_END) ELSE @DATE_END END)

END

DECLARE @PDAY NUMERIC(5,2)
SET @PDAY = 0

IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_AVG'
BEGIN

	SELECT @LINK_EMPL = EMPL_LINK, 
		@SR_DATE = COALESCE(@SR_DATE, DIS_DATE), 
		@DATE_BEGIN = DIS_DATE + 1, 
		@DATE_END = (DIS_DATE + 1) + CASE WHEN ISNULL(VAC_KOMPENS_DAY,0) > 0 THEN CONVERT(INT, VAC_KOMPENS_DAY) ELSE 0 END,
		@PDAY = CASE WHEN ISNULL(VAC_KOMPENS_DAY,0) > 0 THEN VAC_KOMPENS_DAY - CONVERT(INT, VAC_KOMPENS_DAY) ELSE 0 END,
		@REF_TYP = IT.REASON,
		@comment = @UNAME + 'Компенс.за неисп.отпуск:' + COALESCE(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM(KV.[NAME])),30) + ' №'+RTRIM(LTRIM([NUMBER])) + ' от ' + CONVERT(VARCHAR(10),[DATE],104),
		@LINK_DEP = COALESCE(@LINK_DEP,O.DEP_LINK), 
		@SR_DATE1 = DIS_DATE + 1, 
		@SR_DATE2 = DIS_DATE + CASE WHEN ISNULL(VAC_KOMPENS_DAY,0) > 0 THEN CONVERT(INT, VAC_KOMPENS_DAY) ELSE 0 END
	FROM dbo.ORDERS O INNER JOIN dbo.ITEM_DIS_FACE IT ON IT.ORDER_LINK = O.LINK
		INNER JOIN [dbo].[DICTION] KV ON IT.REASON = KV.LINK 
	WHERE IT.LINK = @LINK_VAC AND ISNULL(VAC_KOMPENS_DAY,0) > 0

	IF @LINK_EMPL IS NULL
		SELECT @LINK_EMPL = @SR_LINK_EMPL, @comment = @UNAME + 'Начисл.средн.:' + COALESCE(dbo.sd_GetEmplName(@LINK_EMPL),'') + ',' + LEFT(RTRIM(LTRIM(P.[NAME])),30)
		FROM dbo.PAYS P WHERE LINK = @LINK_PAYS

	SELECT @LINK_DEP = DEP_LINK FROM DBO.USER_DEP WHERE @LINK_DEP IS NULL
END

--- Учет премии в расчете
IF (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1)
	SET @UCHET_PREM = COALESCE(dbo.sa_get_option_by_code('FURLOUGH_OPT8'),1)
ELSE
	SET @UCHET_PREM = COALESCE(dbo.sa_get_option_by_code('CALC_TRAVEL_OPT5'),1)

---

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

SET @RP = (CASE @TYP_PERIOD WHEN 1 THEN 3 WHEN 2 THEN 12 ELSE 0 END)

SELECT TOP 1 
 @LINK_PERS = PERS_LINK,  @SystPay = SYST_PAY, @DEP_LINK = DEP_LINK, 
 @DATE_BEGIN_RP = dbo.kd_DateBeginWork(LINK,@DATE_BEGIN), 
 @DATE_END_RP = dbo.kd_DateEndWork(LINK,@DATE_BEGIN), 
 @MAX_DATE = '29990101',
 @NO_RAION = ISNULL(NO_RAION,0) 
FROM dbo.EMPL WHERE LINK = @LINK_EMPL

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



---Определение расчетного периода
IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_AVG'
	SELECT @DATE_BEGIN_RP = @SR_DATE, @DATE_END_RP = dbo.DateEndOfMonth(DATEADD(MONTH, @RP-1,@SR_DATE)), @DATE_BEGIN = @SR_DATE1, @DATE_END = @SR_DATE2, @LINK_EMPL = @SR_LINK_EMPL
ELSE
	SELECT 
	@DATE_BEGIN_RP = dbo.DateBeginOfMonth( CASE WHEN @DATE_BEGIN_RP > @SR_DATE THEN @DATE_BEGIN_RP ELSE @SR_DATE END),
	@DATE_END_RP = dbo.DateEndOfMonth( CASE WHEN COALESCE(@DATE_END_RP,@MAX_DATE) < dbo.DateEndOfMonth(DATEADD(MONTH, @RP-1,@SR_DATE)) THEN COALESCE(@DATE_END_RP,@MAX_DATE) ELSE dbo.DateEndOfMonth(DATEADD(MONTH, @RP-1,@SR_DATE)) END ),
	@SR_VID = 1

---
DECLARE @MINROT NUMERIC(18,2)
SET @MINROT = dbo.minrot2(@DATE_BEGIN) * @EmplNumStake

--- Если новый расчет, то получить линк документа
DECLARE @NUMBER VARCHAR(10), @DATE_DOC DATETIME
IF COALESCE(@LINK_DOC,0)  = 0
BEGIN
	exec dbo.SALARY_NEXT_NUM @NUMBER OUT, @OBJ_CODE
	SET @DATE_DOC = (Select top 1 WORKDATE from USER_DATES)
	exec dbo.SD_N_VACATION_SAVE @LINK_DOC OUT,@OBJ_CODE, @NUMBER, @DATE_DOC, @LINK_PAYS, @comment, 0, @LINK_EMPL, 0, 0, @TYP_PERIOD, 
			@DATE_BEGIN, @DATE_END, 0, @VID_DAYS, @LINK_VAC, 0, @SR_VID, @DATE_BEGIN_RP, @LINK_DEP
END
ELSE
	SET @DATE_DOC = (SELECT [DATE] FROM SDOC WHERE LINK = @LINK_DOC)

--
UPDATE dbo.SDOC_AVAC 
SET INSTR = 1
WHERE LINK_UP = @LINK_DOC


/***************************************************************************************/
--- вспомогательный период. Вычисление коэффициентов индексации зарплаты по время отпуска
DECLARE @INDEX TABLE ([DATE] DATETIME, [DATE2] DATETIME, SUMMA NUMERIC(18,2), INDEX_VAL NUMERIC(18,10))

/*Перечень сотрудников, которым НЕ нужно индексировать*/
DECLARE @NO_INDEX_EMPL table (link int)
INSERT INTO @NO_INDEX_EMPL (link)
SELECT LINK_EMPL FROM dbo.GROUPS_EMPL G inner join dbo.GROUPS_EMPL_REF E on E.LINK_GROUP = G.LINK
WHERE G.LINK = [dbo].[sa_get_option_by_code]('DICTIONARY_INDEX_OPT4')

--Способ индексации 
--Использовать коэффициент индексации из справочника,Рассчитывать коэффициент от оклада сотрудника,Рассчитывать коэффициент для каждого начисления
DECLARE @INDEX_OPT2 int 
SET @INDEX_OPT2 = [dbo].[sa_get_option_by_code]('DICTIONARY_INDEX_OPT2')

/*Перечень надбавок, которые НЕ нужно индексировать*/
DECLARE @NO_INDEX_PAY table (link int)
INSERT INTO @NO_INDEX_PAY (link)
SELECT P.link
FROM dbo.PAY_GROUPS G inner join PAYS_REF PR on PR.LINK_GROUPS = G.LINK
	inner join  dbo.PAYS P on P.LINK = PR.LINK_PAYS
WHERE G.LINK = [dbo].[sa_get_option_by_code]('DICTIONARY_INDEX_OPT3')

declare @pn2 table (link_pay int, period datetime, summa numeric(18,2))	

--на случай повышения после окончания расчётного периода и до наступления отпуска
INSERT INTO @INDEX ([DATE], [DATE2], SUMMA, INDEX_VAL)
VALUES (@DATE_END_RP,@DATE_BEGIN,0,1)

IF @INDEX_OPT2 >= 2 AND NOT EXISTS (SELECT * FROM @NO_INDEX_EMPL WHERE LINK = @LINK_EMPL)
BEGIN

	--на случай повышения ОКЛАДОВ во время отпуска
	INSERT INTO @INDEX
	SELECT DISTINCT      
		[DATE] = CASE WHEN @DATE_BEGIN >= DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END, 
		NULL,
		0,
		1
	FROM 
		DBO.DICTIONARY_PAYS_EMPL_FN(@DATE_END, @LINK_EMPL, 0, DEFAULT, @DEP_LINK, DEFAULT) S
	WHERE
		EXISTS (SELECT * FROM dbo.WAY_CALC WC WHERE WC.TYPE = 1 AND WC.CODE = S.WAY_CALC AND WC.OKLAD = 1)
		AND
		EXISTS (Select * FROM dbo.group_pays(@LINK_PAYS) T WHERE T.PAY_LINK = s.LINK_PAYS)
		AND
		NOT EXISTS (SELECT * FROM @NO_INDEX_PAY A WHERE A.LINK = s.LINK_PAYS)

	UPDATE A
	SET A.DATE2 = ISNULL((SELECT MIN(B.[DATE])-1 FROM @INDEX B WHERE B.[DATE] > A.[DATE]),@DATE_END)
	FROM @INDEX A
	
	DECLARE @Cur1 CURSOR, @Cur2 CURSOR, @NEXT_DATE DATETIME, @NEXT_DATE2 DATETIME, @INDEX_VAL NUMERIC(18,10)
	SET @Cur1 = CURSOR FORWARD_ONLY

	FOR SELECT [DATE] FROM @INDEX ORDER BY [DATE]

	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @NEXT_DATE
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			
			UPDATE @INDEX 
			SET SUMMA = (SELECT SUM(SUMMA) FROM dbo.SA_ALL_PAYS_ALL_DATE0(@LINK_EMPL, @NEXT_DATE, DEFAULT, @LINK_DEP) S 
							INNER JOIN dbo.PAYS P ON P.LINK = S.LINK_PAY
							INNER JOIN dbo.WAY_CALC W ON P.WAY_CALC = W.CODE 
							WHERE LINK_SOVM = 0 AND W.[TYPE] = 1 AND W.OKLAD = 1 )
			WHERE 
				[DATE] = @NEXT_DATE

			SET @INDEX_VAL = 1
		
			SET @Cur2 = CURSOR FORWARD_ONLY
			FOR SELECT [DATE] FROM @INDEX WHERE [DATE] <= @NEXT_DATE ORDER BY [DATE]
			OPEN @Cur2
			FETCH NEXT FROM @Cur2 INTO @NEXT_DATE2
			WHILE (@@fetch_status <> -1)
			BEGIN
				IF (@@fetch_status <> -2)
				BEGIN
					SET @INDEX_VAL = @INDEX_VAL 
					* (CASE WHEN (SELECT TOP 1 SUMMA FROM @INDEX WHERE [DATE] < @NEXT_DATE2 ORDER BY [DATE] DESC) <> 0
						THEN
							(SELECT SUMMA / (SELECT TOP 1 SUMMA FROM @INDEX WHERE [DATE] < @NEXT_DATE2 ORDER BY [DATE] DESC) FROM @INDEX WHERE [DATE] = @NEXT_DATE2)
						ELSE 1
						END)
				END
				FETCH NEXT FROM @Cur2 INTO @NEXT_DATE2
			END

			CLOSE @Cur2
			DEALLOCATE @Cur2				

			UPDATE @INDEX 
			SET INDEX_VAL = @INDEX_VAL
			WHERE [DATE] = @NEXT_DATE
		
		END

		FETCH NEXT FROM @Cur1 INTO @NEXT_DATE
	END

	CLOSE @Cur1
	DEALLOCATE @Cur1

	--убираются вспомогательный период
	DELETE FROM @INDEX WHERE DATE2 < @DATE_BEGIN

END --IF NOT EXISTS (SELECT * FROM @NO_INDEX_EMPL WHERE LINK = @LINK_EMPL

IF @INDEX_OPT2 = 1 AND NOT EXISTS (SELECT * FROM @NO_INDEX_EMPL WHERE LINK = @LINK_EMPL)
BEGIN

	INSERT INTO @INDEX ([DATE], [DATE2], SUMMA, INDEX_VAL)
	SELECT TOP 1 @DATE_END_RP+1, [DATE], 0, [KOEF] FROM dbo.DICTIONARY_INDEX WHERE [DATE] BETWEEN @DATE_END_RP+1 AND @DATE_BEGIN ORDER BY [DATE] DESC

	INSERT INTO @INDEX ([DATE], [DATE2], SUMMA, INDEX_VAL)
	SELECT TOP 1 [DATE], @DATE_END, 0, [KOEF] FROM dbo.DICTIONARY_INDEX WHERE [DATE] BETWEEN @DATE_BEGIN+1 AND @DATE_END ORDER BY [DATE] DESC	

	UPDATE A
	SET A.DATE2 = ISNULL((SELECT MIN(B.[DATE])-1 FROM @INDEX B WHERE B.[DATE] > A.[DATE]),@DATE_END)
	FROM @INDEX A	
	
END	
--SELECT @INDEX_OPT2, * FROM @INDEX

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

--
IF @RECALC = 0  --- Расчет сумм по видам начислений
BEGIN

	--- Промежуточная база расчета
	CREATE TABLE #BASE1 (
		PERIOD DATETIME,
		NADB NUMERIC(18,2),
		CODE_PAY VARCHAR(254),
		NAME_PAY VARCHAR(254), 
		WAY_CALC INT,
		LINK_PAY INT,
		SUMMA NUMERIC(18,2),
		SUM0 NUMERIC(18,2),
		KOEF  NUMERIC(18,4),
		CV	NUMERIC(18,2),
		LINK_VKR INT,
		DATE1 DATETIME,
		DATE2 DATETIME
	)


	DECLARE @DEFAULT_KBK INT
	SET @DEFAULT_KBK = (Select TOP 1 KBK.LINK_KBK FROM dbo.KU_EmplStafKBK(default) KBK WHERE KBK.LINK_EMPL = @LINK_EMPL)

	INSERT INTO #BASE1 (PERIOD, NADB, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, SUM0, KOEF, CV, LINK_VKR, DATE1, DATE2)
	exec dbo.SD_BASE_SUM_PAY_DIF_PERIODS @LINK_PAYS, @LINK_EMPL, @DATE_BEGIN_RP, @DATE_END_RP, @OBJ_CODE, @DATE_BEGIN, @DATE_END_RP

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

		SELECT TOP 1  @DATE_BEGIN_RP = dbo.kd_DateBeginWork(LINK,@DATE_BEGIN), @DATE_END_RP = dbo.kd_DateEndWork(LINK,@DATE_BEGIN)
		FROM dbo.EMPL WHERE LINK = @LINK_EMPL
		---	
		IF RTRIM(LTRIM(@OBJ_CODE)) = 'DOCUMENTS_CALC_AVG'
			SELECT @DATE_BEGIN_RP = DATEADD(MONTH,-@RP,@SR_DATE), @DATE_END_RP = dbo.DateEndOfMonth(DATEADD(MONTH, (@RP-1)+@RP,@SR_DATE))
		ELSE 
			SELECT @DATE_BEGIN_RP = dbo.DateBeginOfMonth( CASE WHEN @DATE_BEGIN_RP > DATEADD(MONTH, -(@RP+@RP),@DATE_BEGIN) THEN @DATE_BEGIN_RP ELSE DATEADD(MONTH, -@RP*2,@DATE_BEGIN) END),
			@DATE_END_RP = dbo.DateEndOfMonth( CASE WHEN COALESCE(@DATE_END_RP,@MAX_DATE) < DATEADD(MONTH, -((CASE WHEN @RP > 0 THEN 1 ELSE 0 END)+@RP),@DATE_BEGIN) THEN COALESCE(@DATE_END_RP,@MAX_DATE) ELSE DATEADD(MONTH, -((CASE WHEN @RP > 0 THEN 1 ELSE 0 END)+@RP),@DATE_BEGIN) END )

		IF COALESCE(@DATE_END_RP,@MAX_DATE) < @DATE_BEGIN_RP
			SET @DATE_END_RP = dbo.DateEndOfMonth(@DATE_BEGIN_RP)
		---
		INSERT INTO #BASE1 (PERIOD, NADB, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, SUM0, KOEF, CV, LINK_VKR, DATE1, DATE2)
		exec dbo.SD_BASE_SUM_PAY_DIF_PERIODS @LINK_PAYS, @LINK_EMPL, @DATE_BEGIN_RP, @DATE_END_RP, @OBJ_CODE, @DATE_BEGIN, @DATE_END_RP

		IF COALESCE((SELECT SUM(SUMMA) FROM #BASE1),0) = 0 BEGIN
			SET @DATE_BEGIN_RP = dbo.DateBeginOfMonth(@DATE_BEGIN)
			SET @DATE_END_RP = dbo.DateEndOfMonth(@DATE_BEGIN)
	
			INSERT INTO #BASE1 (PERIOD, NADB, CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, SUMMA, SUM0, KOEF, CV, LINK_VKR, DATE1, DATE2)
			SELECT @DATE_BEGIN, 0, P.CODE, P.NAME, P.WAY_CALC, S.LINK_PAY, S.SUMMA,S.SUMMA, 1, 0, S.LINK_KBK, @DATE_BEGIN_RP, dbo.DateEndOfMonth(@DATE_BEGIN) 
			FROM 
				dbo.SA_ALL_PAYS_ALL_DATE0(@LINK_EMPL, @DATE_BEGIN, DEFAULT, @LINK_DEP) S
				inner join dbo.pays P on s.link_pay = p.link
			WHERE s.link_pay IN (SELECT T.PAY_LINK FROM dbo.group_pays(@LINK_PAYS) T)
	
		END
		
	END

--индексируем на коэффициенты повышения после расчетного периода и до наступления отпуска

	DECLARE @INDEX2 NUMERIC(18,10)
	SET @INDEX2 = ISNULL((SELECT TOP 1 INDEX_VAL FROM @INDEX WHERE [DATE] <= @DATE_BEGIN ORDER BY [DATE] DESC),1)

	IF @INDEX2 > 1 BEGIN

		UPDATE B
		SET B.KOEF = B.KOEF * @INDEX2, B.SUMMA = B.SUMMA * @INDEX2
		FROM
			#BASE1 B
		WHERE
			B.PERIOD < @DATE_END_RP
			AND
			NOT EXISTS (SELECT * FROM @NO_INDEX_PAY N WHERE N.LINK = B.LINK_PAY)

		--убираются вспомогательный период
		UPDATE @INDEX SET INDEX_VAL = 1
		WHERE DATE <= @DATE_BEGIN
	
	END	--IF @INDEX2 > 1 BEGIN		

	---
	UPDATE #BASE1 SET LINK_VKR = @DEFAULT_KBK WHERE LINK_VKR IS NULL

	--- Определим, делать ли расчет в разрезе КБК
	DECLARE @KBK_OPT TINYINT
	IF (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1)
		SET @KBK_OPT = dbo.sa_get_option_by_code('FURLOUGH_OPT7')
	ELSE			
		SET @KBK_OPT = dbo.sa_get_option_by_code('CALC_TRAVEL_OPT4')

	DECLARE @isMATER tinyint
	SET @isMATER = dbo.sa_get_option_by_code('FURLOUGH_OPT12')

	IF @KBK_OPT <> 1
	BEGIN
		--- Заменить на общий коэф. индексации, если есть за один период несколько одинаковых начислений с разными источниками и разными коэффициентами индексации
		CREATE TABLE #GRP_KOEF (PERIOD DATETIME, LINK_PAY INT, GRP_KOEF NUMERIC(18,4))
		
		INSERT INTO #GRP_KOEF (PERIOD, LINK_PAY, GRP_KOEF)
		SELECT PERIOD, LINK_PAY, ROUND(SUM(SUMMA) / SUM(SUM0),4) FROM #BASE1 GROUP BY PERIOD, LINK_PAY HAVING(SUM(SUM0)) > 0
		
		UPDATE #BASE1
		SET KOEF = (SELECT TOP 1 GRP_KOEF FROM #GRP_KOEF G WHERE G.PERIOD = #BASE1.PERIOD AND G.LINK_PAY = #BASE1.LINK_PAY)
		WHERE EXISTS (SELECT * FROM #GRP_KOEF G WHERE G.PERIOD = #BASE1.PERIOD AND G.LINK_PAY = #BASE1.LINK_PAY)
		
		DROP TABLE #GRP_KOEF
	END	

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

	--Если у сотрудника указано "Не начислять районный", то рассчитываем без районного
	SET @FURLOUGH_OPT_REG_KOEF = 
			CASE RTRIM(LTRIM(@OBJ_CODE))
				WHEN 'DOCUMENTS_ADD_FURLOUGH' THEN (CASE WHEN @NO_RAION = 1 THEN 0 ELSE dbo.sa_get_option_by_code('FURLOUGH_OPT15') END)
				WHEN 'DOCUMENTS_CALC_TRAVEL' THEN (CASE WHEN @NO_RAION = 1 THEN 0 ELSE dbo.sa_get_option_by_code('CALC_TRAVEL_OPT7') END)
				WHEN 'DOCUMENTS_CALC_AVG' THEN (CASE WHEN @NO_RAION = 1 
													THEN 0 
													ELSE 
														CASE WHEN @SR_VID = 1 
															THEN dbo.sa_get_option_by_code('FURLOUGH_OPT15') 
															ELSE dbo.sa_get_option_by_code('CALC_TRAVEL_OPT7') 
														END	
												END)				
				ELSE 0
			END		

	SET @FURLOUGH_OPT_NORTH_KOEF =
			CASE RTRIM(LTRIM(@OBJ_CODE))
				WHEN 'DOCUMENTS_ADD_FURLOUGH' THEN dbo.sa_get_option_by_code('FURLOUGH_OPT16')
				WHEN 'DOCUMENTS_CALC_TRAVEL' THEN dbo.sa_get_option_by_code('CALC_TRAVEL_OPT8')
				WHEN 'DOCUMENTS_CALC_AVG' THEN 	CASE WHEN @SR_VID = 1 
													THEN dbo.sa_get_option_by_code('FURLOUGH_OPT16') 
													ELSE dbo.sa_get_option_by_code('CALC_TRAVEL_OPT8') 
												END	
				ELSE 0
			END		 

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

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

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

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

	---
	Select PERIOD = MIN(PERIOD), PERIOD1 = (YEAR(PERIOD) * 100 + MONTH(PERIOD)), CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, 
		SUMMA = SUM( CASE WHEN WAY_CALC in (6,7) AND (DATEDIFF(MONTH,DATE1, DATE2) + 1) <> 0 AND @UCHET_PREM = 1 THEN 
					CONVERT(NUMERIC(18,2), SUM0 * --В размере месячной части за каждый месяц расчетного периода (если она начислена за период > 1 месяц)
						(DATEDIFF(MONTH,CASE WHEN DATE1 <= @DATE_BEGIN_RP THEN @DATE_BEGIN_RP ELSE DATE1 END,
								CASE WHEN DATE2 >= @DATE_END_RP THEN @DATE_END_RP ELSE DATE2 END) + 1)
						/ (DATEDIFF(MONTH,DATE1, DATE2) + 1))
				ELSE
					CASE WHEN WAY_CALC = 12 
					THEN
						CONVERT(NUMERIC(18,2), SUM0 * 
							CASE @isMATER
								WHEN 1 THEN 1 --1) Полностью
								WHEN 2 THEN --2) В размере месячной части за каждый месяц расчетного периода (если она начислена за период > 1 месяц)
									CONVERT(NUMERIC(18,2), (DATEDIFF(MONTH,CASE WHEN DATE1 <= @DATE_BEGIN_RP THEN @DATE_BEGIN_RP ELSE DATE1 END, 
									CASE WHEN DATE2 >= @DATE_END_RP THEN @DATE_END_RP ELSE DATE2 END) + 1))
									/ (DATEDIFF(MONTH,DATE1, DATE2) + 1)
								WHEN 3 THEN 0 --3) Вообще не включать
							ELSE 1 END)
					ELSE SUM0 
					END
			END), 
		SUM0 = SUM(SUM0),	
		KOEF, 
		LINK_VKR = (CASE WHEN @KBK_OPT = 1 then LINK_VKR else @DEFAULT_KBK end), DATE1, DATE2 
	INTO #BASE
	from #BASE1 
	where (@isMATER = 3 and WAY_CALC <> 12 or @isMATER <> 3)
	group by (YEAR(PERIOD) * 100 + MONTH(PERIOD)), CODE_PAY, NAME_PAY, WAY_CALC, LINK_PAY, KOEF, (CASE WHEN @KBK_OPT = 1 then LINK_VKR else @DEFAULT_KBK end), DATE1, DATE2 

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

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

	DECLARE @PAYS_MONTS1 VARCHAR(100)
	SET @PAYS_MONTS1 = @PAYS_MONTS + '1'

	EXEC M_CROSS_TABLE
		'LINK_PAY, LINK_VKR',
		'PERIOD1', 'INT',
		'KOEF', 'NUMERIC(18,4)', 'MAX(KOEF) AS KOEF',
		'#BASE', @PAYS_MONTS1

	DELETE FROM dbo.SDOC_AVAC_TABLE3  WHERE LINK_UP = @LINK_DOC
	
	DECLARE @SCRIPT VARCHAR(8000)
	SET @SCRIPT = ' INSERT INTO dbo.SDOC_AVAC_TABLE3 (LINK_UP, ORDERS, LINK_PAY, LINK_KBK, SUMMA1, KOEF1, SUMMA2, KOEF2, SUMMA3, KOEF3, SUMMA4, KOEF4, SUMMA5, KOEF5, SUMMA6, KOEF6, 
				SUMMA7, KOEF7, SUMMA8, KOEF8,  SUMMA9, KOEF9, SUMMA10, KOEF10, SUMMA11, KOEF11,  SUMMA12, KOEF12)'  
			+ ' Select ' + CONVERT(VARCHAR(20),@LINK_DOC) + ', 0, P1.LINK_PAY, P1.LINK_VKR'  
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,0,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,0,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,0,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,0,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,0,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,0,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,1,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,1,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,1,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,1,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,1,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,1,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,2,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,2,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,2,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,2,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,2,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,2,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,3,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,3,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,3,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,3,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,3,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,3,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,4,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,4,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,4,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,4,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,4,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,4,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,5,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,5,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,5,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,5,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,5,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,5,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,6,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,6,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,6,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,6,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,6,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,6,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,7,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,7,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,7,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,7,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,7,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,7,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,8,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,8,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,8,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,8,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,8,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,8,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,9,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,9,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,9,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,9,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,9,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,9,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,10,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,10,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,10,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,10,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,10,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,10,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
			+ CASE WHEN EXISTS (SELECT * from #BASE WHERE YEAR(PERIOD) = YEAR(DATEADD(MONTH,11,@DATE_BEGIN_RP)) AND MONTH(PERIOD) = MONTH(DATEADD(MONTH,11,@DATE_BEGIN_RP)) )
			THEN ', COALESCE(SUMMA_'
				+ CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,11,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,11,@DATE_BEGIN_RP))) ) 
				+ ',0), COALESCE(KOEF_' + CONVERT(VARCHAR(10),(Select  COUNT(DISTINCT YEAR(PERIOD) * 100 + MONTH(PERIOD)) FROM #BASE WHERE YEAR(PERIOD) * 100 + MONTH(PERIOD) <= YEAR(DATEADD(MONTH,11,@DATE_BEGIN_RP)) *100 + MONTH(DATEADD(MONTH,11,@DATE_BEGIN_RP))) ) 
				+ ',0)' ELSE ',0,0' END
		+ ' from ' + @PAYS_MONTS + ' P1 LEFT JOIN ' + @PAYS_MONTS1 + ' P2 ON P1.LINK_PAY = P2.LINK_PAY AND P1.LINK_VKR = P2.LINK_VKR' 

	exec (@SCRIPT)

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


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

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

	INSERT INTO @WTIME (M,Y,DAYS,HOURS,DAYS_NORM,HOURS_NORM,KDAYS,KDAYS_N)
	---Данные по табелям 
	SELECT  M, Y,
		DAYS = COALESCE(CONVERT(NUMERIC(4,0), DBO.SA_GET_EMPL_WD (@LINK_EMPL, 0, DEFAULT, dbo.ConvertDMY2Date(1,M,Y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,M,Y)), @LINK_GRAPH, 0) ),0),
		HOURS = COALESCE(CONVERT(NUMERIC(10,2), DBO.SA_GET_EMPL_WH (@LINK_EMPL, 0, DEFAULT, dbo.ConvertDMY2Date(1,M,Y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,M,Y)), @LINK_GRAPH, 0) ),0),
		DAYS_NORM = ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(@LINK_EMPL,M,Y)),0),
		HOURS_NORM = ISNULL(CONVERT(NUMERIC(10,2),dbo.NORM_HOURS(@LINK_EMPL,M,Y)),0),
		0,0
	FROM dbo.months_ex(@DATE_BEGIN_RP, @DATE_END_RP) M
	WHERE NOT EXISTS (SELECT * FROM @WTIME W WHERE (W.Y = M.Y AND W.M = M.M) )

	---
	IF  @VID_DAYS <> 1 BEGIN-- В календарных днях
		UPDATE @WTIME
		SET KDAYS = ISNULL(CONVERT(NUMERIC(4,0),dbo.SA_CALENDAR_DAYS_FN(@LINK_EMPL,M,Y)),0),
			KDAYS_N = ISNULL(CONVERT(NUMERIC(4,0),DAY(dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1, M, Y)))),0)

	END

	Declare @KBK_DEF INT
	SET @KBK_DEF = (Select top 1 link_kbk from dbo.KU_EmplStafKBK(default) where link_empl = @LINK_EMPL)

	---
	DECLARE @TABLE2 TABLE (Y INT, M INT, LINK_KBK INT, SUMMA_ZP NUMERIC(18,2), SUMMA_PR NUMERIC(18,2), SUMMA_MAT NUMERIC(18,2), DAYS INT, HOURS NUMERIC(18,2), DAYS_NORM INT, HOURS_NORM NUMERIC(18,2), KDAYS INT, KDAYS_N INT)
	INSERT INTO @TABLE2
	SELECT  
		T.Y,
		T.M,
		COALESCE(B.LINK_KBK,@KBK_DEF),
		SUMMA_ZP = SUM( CASE WHEN coalesce(PAYMENT,0) not in (7,12) THEN coalesce(SUMMA,0) ELSE 0 END),
		SUMMA_PR = SUM( CASE WHEN coalesce(PAYMENT,0) = 7 THEN coalesce(SUMMA,0) ELSE 0 END),
		SUMMA_MAT = SUM( CASE WHEN coalesce(PAYMENT,0) = 12 THEN coalesce(SUMMA,0) ELSE 0 END),
		COALESCE(DAYS,0),COALESCE(HOURS,0),COALESCE(DAYS_NORM,0),COALESCE(HOURS_NORM,0), COALESCE(KDAYS,0), COALESCE(KDAYS_N,0)
	FROM 
		@WTIME T LEFT JOIN 
		(
		Select PERIOD = DATEADD(MONTH,0,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,0,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,0,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA1,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA1,0) <> 0
	UNION ALL 
		Select PERIOD = DATEADD(MONTH,1,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,1,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,1,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA2,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA2,0) <> 0
	UNION ALL 
		Select PERIOD = DATEADD(MONTH,2,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,2,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,2,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA3,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA3,0) <> 0
	UNION ALL 
		Select PERIOD = DATEADD(MONTH,3,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,3,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,3,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA4,0)  
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA4,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,4,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,4,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,4,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA5,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA5,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,5,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,5,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,5,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA6,0)  
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA6,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,6,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,6,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,6,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA7,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA7,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,7,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,7,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,7,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA8,0) 
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA8,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,8,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,8,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,8,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA9,0)  
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA9,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,9,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,9,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,9,@DATE_BEGIN_RP)),	

			SUMMA = COALESCE(T3.KSUMMA10,0) 
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA10,0) <> 0 
	UNION ALL
		Select PERIOD = DATEADD(MONTH,10,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,10,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,10,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA11,0)  
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3  WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA11,0) <> 0
	UNION ALL
		Select PERIOD = DATEADD(MONTH,11,@DATE_BEGIN_RP), REF_PAY, LINK_KBK, PAYMENT,
			DATE1 = dbo.DateBeginOfMonth(DATEADD(MONTH,11,@DATE_BEGIN_RP)), 
			DATE2 = dbo.DateEndOfMonth(DATEADD(MONTH,11,@DATE_BEGIN_RP)),	
			SUMMA = COALESCE(T3.KSUMMA12,0)
		FROM dbo.DOCUMENTS_ADD_FUR_TABLE1 T3 WHERE LINK = @LINK_DOC AND COALESCE(T3.KSUMMA12,0) <> 0
	) AS B ON T.Y = YEAR(B.PERIOD) AND T.M = MONTH(B.PERIOD)
	GROUP BY
		T.Y, T.M, B.LINK_KBK, DAYS,HOURS, DAYS_NORM, HOURS_NORM, KDAYS, KDAYS_N	

	-----
	DELETE FROM dbo.SDOC_AVAC_TABLE2  WHERE LINK_UP = @LINK_DOC

	INSERT INTO dbo.SDOC_AVAC_TABLE2 (LINK_UP, ORDERS, PERIOD, LINK_KBK, SUMMA, PREM, DAYS, HOURS, DAYS_N, HOURS_N, KDAYS, KDAYS_N, MATER)
	SELECT  @LINK_DOC, 0, dbo.ConvertDMY2Date(1, M, Y), 
	LINK_KBK, SUMMA_ZP, SUMMA_PR, DAYS,HOURS,DAYS_NORM,HOURS_NORM, KDAYS, KDAYS_N, SUMMA_MAT
	FROM @TABLE2
	ORDER BY Y, M, LINK_KBK

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

END	--IF @RECALC < = 1

IF @RECALC < = 2 --- Расчет периодов больничного и определение средних сум
BEGIN		

	---Периоды отпуска
	DECLARE @PERIODY TABLE (DATE_BEGIN DATETIME, DATE_END DATETIME, INDEX_VAL NUMERIC(18,10), DH_NORM NUMERIC(18,2))
	DECLARE @PERIODY_DOP TABLE (NUM INT IDENTITY(1,1), DATE_BEGIN DATETIME, DATE_END DATETIME, T TINYINT)

		--- 1. Разбивка на периоды по месяцам
	if @DATE_BREAK IS NULL
		INSERT INTO @PERIODY_DOP (DATE_BEGIN, DATE_END, T)
		SELECT 
			DATE_BEGIN = (CASE WHEN @DATE_BEGIN > DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END), 
			DATE_END = (CASE WHEN @DATE_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
			1 --Первый тип периодов
		from dbo.months_ex(@DATE_BEGIN, @DATE_END)
	ELSE
	BEGIN
		SET @DATE_BREAK = @DATE_BREAK -1
		
		INSERT INTO @PERIODY_DOP (DATE_BEGIN, DATE_END, T)
		select 
			DATE_BEGIN = (CASE WHEN @DATE_BEGIN > DATE_BEGIN THEN @DATE_BEGIN ELSE DATE_BEGIN END), 
			DATE_END = (CASE WHEN  @DATE_BREAK < dbo.DateEndOfMonth(DATE_BEGIN) THEN  @DATE_BREAK ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
			1 --Первый тип периодов
		from dbo.months_ex(@DATE_BEGIN, @DATE_BREAK)
		UNION ALL
		select 
			DATE_BEGIN = (CASE WHEN @DATE_BREAK_NEW_BEGIN > DATE_BEGIN THEN @DATE_BREAK_NEW_BEGIN ELSE DATE_BEGIN END), 
			DATE_END = (CASE WHEN @DATE_END < dbo.DateEndOfMonth(DATE_BEGIN) THEN @DATE_END ELSE dbo.DateEndOfMonth(DATE_BEGIN) END),
			1 --Первый тип периодов			
		from dbo.months_ex(@DATE_BREAK_NEW_BEGIN, @DATE_END)

	END

	--Второй тип периодов
	INSERT INTO @PERIODY_DOP (DATE_BEGIN, DATE_END, T)
	SELECT DATE_BEGIN = [DATE], DATE_END = [DATE2], 2 FROM @INDEX	

	DECLARE @A TABLE (NUM INT, [DATE] DATETIME, T INT)
	DECLARE @MIN_D DATETIME, @MAX_D DATETIME
	SELECT @MIN_D = MIN(DATE_BEGIN), @MAX_D = MAX(DATE_END) FROM @PERIODY_DOP

	INSERT INTO @A (NUM, [DATE], T)
	SELECT P.NUM, [DATE], T 
	FROM
		@PERIODY_DOP P
		INNER JOIN dbo.days_ex(@MIN_D, @MAX_D) D ON D.[DATE] BETWEEN P.DATE_BEGIN AND P.DATE_END
	ORDER BY P.NUM		

	DECLARE @T1 TABLE (NUM1 INT, [DATE] DATETIME, NUM2 INT)

	INSERT INTO @T1 (NUM1, [DATE], NUM2)
	SELECT A1.NUM, A1.[DATE], A2.NUM
	FROM @A A1 INNER JOIN @A A2 ON A1.[DATE] = A2.[DATE]
	WHERE A1.T = 1 AND A2.T = 2
	UNION
	SELECT A2.NUM, A2.[DATE], A1.NUM
	FROM @A A1 INNER JOIN @A A2 ON A1.[DATE] = A2.[DATE]
	WHERE A1.T = 1 AND A2.T = 2

	INSERT INTO @PERIODY (DATE_BEGIN, DATE_END, INDEX_VAL)
	SELECT 
		DATE_BEGIN, DATE_END,
		INDEX_VAL = ISNULL((SELECT INDEX_VAL FROM @INDEX I WHERE T.[DATE_BEGIN] BETWEEN I.DATE AND I.DATE2 AND T.[DATE_END] BETWEEN I.DATE AND I.DATE2),1)
	FROM (
		SELECT DISTINCT DATE_BEGIN = MIN([DATE]), DATE_END = MAX([DATE]) FROM @T1 GROUP BY NUM1, NUM2	
		) T	

--SELECT * FROM @INDEX	
--SELECT * FROM @PERIODY	
	----
	UPDATE @PERIODY
	SET DH_NORM = 
			  CASE WHEN @VID_DAYS = 1 
				THEN ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAY_DH(@LINK_EMPL,DATE_BEGIN,DATE_END)),0) + (CASE WHEN DATE_BEGIN = (SELECT MAX(DATE_BEGIN) FROM @PERIODY) THEN @PDAY ELSE 0 END)
			  ELSE	
				DATEDIFF(DAY,DATE_BEGIN, DATE_END)+1 - (CASE WHEN @HOLIDAY = 1 THEN dbo.SA_HOLIDAY_COUNT_FN(DATE_BEGIN,DATE_END) ELSE 0 END) + (CASE WHEN DATE_BEGIN = (SELECT MAX(DATE_BEGIN) FROM @PERIODY) THEN @PDAY ELSE 0 END)
			  END

	---
	DECLARE @REP_SUMMA_PR NUMERIC(18,2), @SUMMA_ZP NUMERIC(18,2), @SUMMA_PR NUMERIC(18,2), @PNORM NUMERIC(18,2), @PWORK NUMERIC(18,2), 
		@SR_ZP NUMERIC(18,2), @AvgDays NUMERIC(18,2), @DAYS_SZ NUMERIC(18,2)
	SET @AvgDays = COALESCE(dbo.sa_get_option_by_code('FURLOUGH_OPT4'),29.4)
	
	--- Время за расчетный период
	SELECT  [PERIOD],
		[DAYS_N] = MAX(DAYS_N),
		[HOURS_N] = MAX(HOURS_N),
		[DAYS] = MAX(DAYS),
		[HOURS] = MAX(HOURS),
		[KDAYS] = MAX(KDAYS),
		[KDAYS_N] = MAX(ISNULL(CONVERT(NUMERIC(4,0),DAY(dbo.DateEndOfMonth(PERIOD))),0))
	INTO #TMP
	FROM dbo.SDOC_AVAC_TABLE2 WHERE LINK_UP = @LINK_DOC
	GROUP BY [PERIOD]

	SELECT  
		@PNORM = SUM(CASE WHEN @SystPay = 1 THEN DAYS_N ELSE  HOURS_N END),
		@PWORK = SUM(CASE WHEN @SystPay = 1 THEN DAYS ELSE HOURS END),
		@DAYS_SZ = SUM(
			CASE WHEN @VID_DAYS = 1 THEN--В рабочих днях 
				CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
					CASE WHEN COALESCE(DAYS,0.00) >= COALESCE(DAYS_N,0.00) THEN COALESCE(DAYS_N,0.00) else COALESCE(DAYS,0.00) * 1.2 END
				ELSE DAYS --Рассчитываются не отпускные, а прочие начисления по среднему
				END
			ELSE --В календарных днях
				CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
					CASE WHEN COALESCE(KDAYS,0.00) <> 0 AND COALESCE(KDAYS,0.00) >= COALESCE(KDAYS_N,0.00) THEN @AvgDays else @AvgDays * (CASE WHEN COALESCE(KDAYS_N,0.00) <> 0.00 THEN COALESCE(KDAYS,0.00) / COALESCE(KDAYS_N,0.00) else 0.00 END) END
				ELSE KDAYS --Рассчитываются не отпускные, а прочие начисления по среднему
				END				
			END)
	FROM #TMP

	---	
	SELECT 
		@SUMMA_ZP = SUM(SUMMA) + SUM(MATER), 
		@SUMMA_PR = CASE WHEN SUM(@PNORM) > 0 THEN SUM(PREM) / SUM(@PNORM) * SUM(@PWORK) ELSE 0 END,
		@REP_SUMMA_PR = CASE WHEN SUM(@PNORM) > 0 THEN SUM(PREM) / SUM(@PNORM) * SUM(@PWORK) ELSE 0 END
	FROM dbo.SDOC_AVAC_TABLE2 WHERE LINK_UP = @LINK_DOC

	---	
	SET @SR_ZP = CASE WHEN @DAYS_SZ <> 0 THEN (@SUMMA_ZP + @SUMMA_PR) / @DAYS_SZ ELSE 0 END
		
	DECLARE @KBK_KOEF TABLE (LINK_KBK INT, KOEF NUMERIC(18,4))
	DECLARE @S NUMERIC(18,2)
	SET @S = COALESCE((SELECT SUM(SUMMA) + (CASE WHEN SUM(@PNORM) > 0 THEN SUM(PREM) / SUM(@PNORM) * SUM(@PWORK) ELSE 0 END) FROM dbo.SDOC_AVAC_TABLE2 WHERE LINK_UP = @LINK_DOC),0)

	INSERT INTO @KBK_KOEF (LINK_KBK, KOEF) 
	SELECT LINK_KBK, CASE WHEN @S <> 0 THEN (SUM(SUMMA) + (CASE WHEN SUM(@PNORM) > 0 THEN SUM(PREM) / SUM(@PNORM) * SUM(@PWORK) ELSE 0 END)) / @S ELSE 0 END
	FROM dbo.SDOC_AVAC_TABLE2  WHERE LINK_UP = @LINK_DOC 
	GROUP BY LINK_KBK
	
	---
	DELETE FROM dbo.SDOC_AVAC_TABLE1  WHERE LINK_UP = @LINK_DOC

	INSERT INTO dbo.SDOC_AVAC_TABLE1 (LINK_UP, ORDERS, DATE1, DATE2, DAYS, HOURS, SR_ZP, SUMMA, LINK_KBK, KOEF_KBK, KOEF_IDX)
	SELECT @LINK_DOC, 0, DATE_BEGIN, DATE_END, 
		DH_NORM,
		ISNULL(CONVERT(NUMERIC(10,2),dbo.NORM_HOUR_DH(@LINK_EMPL,DATE_BEGIN,DATE_END)),0),
		SR_ZP = @SR_ZP,
		0,
		K.LINK_KBK,	
		K.KOEF,
		ISNULL(P.INDEX_VAL,1)
	FROM @PERIODY P INNER JOIN @KBK_KOEF K ON 1=1
	ORDER BY DATE_BEGIN

	UPDATE sdoc_avac WITH (ROWLOCK) 
	SET 	LINK_EMPL = @LINK_EMPL, LINK_PAY=@LINK_PAYS, DATE_BEGIN=@DATE_BEGIN_RP, SUMMA_TOTAL = @SUMMA_ZP, SR_PREM=@SUMMA_PR, 
			TYP_PERIOD=@TYP_PERIOD, SUMMA_BASE = @SR_ZP, 
			PAYMENT=@VID_DAYS, REF_DOC = @LINK_VAC, DATE1 = @DATE_BEGIN, DATE2 = @DATE_END, TYPE = @SR_VID
	WHERE LINK_UP = @LINK_DOC

	--Дневное пособие не может быть менее дневного пособия, рассчитанного исходя из МРОТ
	IF dbo.sa_get_option_by_code('FURLOUGH_OPT6') = 1 AND (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1)
	BEGIN
		IF @VID_DAYS = 1 --Если расчет в рабочих днях
			UPDATE dbo.SDOC_AVAC_TABLE1
			SET SR_ZP = (case when 
		 			(CASE WHEN @SystPay = 1 
		 				THEN ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 
		 				ELSE ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_HOURS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 	
		 			END)  > 0
		 
		 		then 
						case when SR_ZP < CONVERT(NUMERIC(18,2), dbo.minrot2(DATE1) / 
												(CASE WHEN @SystPay = 1 
													THEN ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 
													ELSE ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_HOURS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 	
												END) )
							then	
								CONVERT(NUMERIC(18,2), dbo.minrot2(DATE1) / 
									(CASE WHEN @SystPay = 1 
										THEN ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 
										ELSE ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_HOURS(@LINK_EMPL, MONTH(DATE1), YEAR(DATE1) )),0) 	
									END) )
							else SR_ZP end
		 		else SR_ZP end)
			WHERE LINK_UP = @LINK_DOC
		ELSE	--Если расчет в календарных днях
			IF dbo.sa_get_option_by_code('FURLOUGH_OPT6') = 1 AND (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1)
			UPDATE dbo.SDOC_AVAC_TABLE1
			SET SR_ZP = case when SR_ZP < dbo.minrot2(DATE1) / (datediff(day,dbo.DateBeginOfMonth(DATE1),dbo.DateEndOfMonth(DATE1)) + 1) 
				then	
					dbo.minrot2(DATE1) / (datediff(day,dbo.DateBeginOfMonth(DATE1),dbo.DateEndOfMonth(DATE1)) + 1)
				else	
					SR_ZP 
				end
			WHERE LINK_UP = @LINK_DOC	
	END
END --@RECALC <= 2 


Select CJ.DATE_BEGIN, CJ.DATE_END, CJ.LINK_VKR, DAYS = SUM(CJ.DAYS) , HOURS = SUM(CJ.HOURS), SUMMA = SUM(SUMMA)
INTO #SUM_OLD
from 
	dbo.SDOC_AVAC SA inner join dbo.CALCULATE_JURNAL CJ on CJ.LINK_DOC = SA.LINK_UP
	inner join dbo.sdoc d on CJ.LINK_DOC = d.link 
where
	COALESCE(@LINK_VAC,0) > 0
	AND
	SA.REF_DOC = @LINK_VAC
	and
	d.object = (Select top 1 link from s_objects where code = @OBJ_CODE)
GROUP BY
	CJ.DATE_BEGIN, CJ.DATE_END, CJ.LINK_VKR

---- сопоставить старые
UPDATE dbo.SDOC_AVAC_TABLE1
SET 
	SUMMA_NEW = CONVERT(NUMERIC(18,2), T.SR_ZP * T.DAYS * KOEF_KBK 
					* --индексация суммы во время отпуска
						(CASE WHEN KOEF_IDX >= 1 THEN KOEF_IDX ELSE 1 END)
						), 
	SUMMA_OLD = COALESCE(SO.SUMMA,0),
	DAYS = COALESCE(T.DAYS,0) - COALESCE(SO.DAYS,0), 
	HOURS = COALESCE(T.HOURS,0) - COALESCE(SO.HOURS,0)
FROM dbo.sdoc_avac A INNER JOIN dbo.SDOC_AVAC_TABLE1 T ON A.LINK_UP = T.LINK_UP
	LEFT JOIN #SUM_OLD SO ON T.DATE1 = SO.DATE_BEGIN AND T.DATE2 = SO.DATE_END AND T.LINK_KBK = SO.LINK_VKR
WHERE T.LINK_UP = @LINK_DOC AND KOEF_KBK IS NOT NULL AND SR_ZP IS NOT NULL

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

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

---
SET @I = 0
UPDATE dbo.SDOC_AVAC_TABLE1  
SET @I = @I+1, ORDERS = @I
WHERE LINK_UP = @LINK_DOC

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

---
SELECT @NUMBER = NUMBER,  @DATE_DOC = [DATE] from dbo.SDOC WHERE LINK = @LINK_DOC
--- Сохрание расчета
SELECT @varKSsoLink = LINK FROM s_objects  WHERE CODE = @OBJ_CODE
EXECUTE dbo.SALARY_UPD_SDOC @LINK_DOC OUTPUT, @varKSsoLink, @NUMBER,@DATE_DOC,@comment,0,null,@SUMMA, @LINK_DEP

IF @OPER = 1 
	exec dbo.SD_N_VACATION_PROV @LINK_DOC, @OBJ_CODE
	
SET NOCOUNT OFF



GO


GRANT EXECUTE ON dbo.[SA_N_VAC_FILL1] TO PUBLIC

GO

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

GO
CREATE   PROCEDURE [dbo].SD_EMPL_INCOM_VKR
	@VARKSNMODE	SMALLINT	= 0, 
	@VARKSNMONTH INT		= 0,
	@VARKSNYEAR	INT		= 0,
	@DEP_LINK INT = NULL,
	@DO_EKR TINYINT = 0 -- вразрезе ЭКР
AS

IF @DEP_LINK IS NULL
	EXEC DBO.XD_WHATS_ZB @DEP_LINK OUTPUT
	
DECLARE @LINK_211EKR INT, @LINK_212EKR INT, @SHOW_212 TINYINT, @LINK_213EKR INT
		  
SET @LINK_211EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '211')
SET @LINK_212EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '212')
SET @LINK_213EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '213')
SET @SHOW_212 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_3')

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

SELECT DISTINCT
	LINK= E.PERS_LINK,
	LINK_EMPL= E.LINK,
	TAB_NUM= E.TAB,
	[NAME_EMPL]= RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.', 
	[STATUS] = 1,
	NUM_STAKE = 1,	
	JC.LINK_VKR, 
	NAME_VKR = KBK.CODE,
	LINK_EKR = EKR.LINK,
	CODE_EKR = EKR.CODE
FROM
	DBO.PERSON P with (nolock)
	INNER JOIN DBO.EMPL E with (nolock) ON E.PERS_LINK = P.LINK AND E.DEP_LINK = COALESCE(@DEP_LINK,E.DEP_LINK)
	INNER JOIN dbo.CALCULATE_JURNAL JC ON JC.LINK_EMPL = E.LINK
	INNER JOIN dbo.PAYS PS ON JC.LINK_PAYS = PS.LINK
	INNER JOIN DBO.SAL_SFIN KBK ON JC.LINK_VKR = KBK.LINK
	INNER JOIN DBO.KOSGU EKR ON 
		@SHOW_212 = 1 AND (EKR.LINK = JC.LINK_EKR OR (JC.LINK_EKR = @LINK_212EKR AND EKR.LINK = @LINK_211EKR)) --Источники с 212 ЭКР дублируем с 211 ЭКР --Временно до конца года
		OR 
		@SHOW_212 = 0 AND EKR.LINK = (CASE WHEN JC.LINK_EKR <> @LINK_212EKR THEN JC.LINK_EKR ELSE @LINK_211EKR END)	
		OR 
		@DO_EKR = 1 AND EKR.LINK = JC.LINK_EKR
WHERE
	E.DEP_LINK = @DEP_LINK
	AND
	PS.[OBJECT] IN (1,2)
	AND
	YEAR(JC.PERIOD_BEGIN) = @VARKSNYEAR
	AND
	JC.SUMMA<>0
	AND
	(
		(MONTH(JC.PERIOD_BEGIN) <= @VARKSNMONTH AND @VARKSNMODE <> 0)
		OR
		(MONTH(JC.PERIOD_BEGIN) = @VARKSNMONTH AND @VARKSNMODE = 0)
	)
	AND
	(@ESN_213 = 1 OR @ESN_213 = 0 AND EKR.LINK <> @LINK_213EKR)
		
ORDER BY
	4,6,8

GO


GRANT EXECUTE ON dbo.[SD_EMPL_INCOM_VKR] TO PUBLIC

GO

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

GO
CREATE PROCEDURE dbo.BK_EXPORT_F1152004_502
	(@iLINK_FORM INT)
AS
BEGIN

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

	DECLARE
		@FNAME VARCHAR (254),
		@FNAME_ID VARCHAR (254),

		@PART_NAME_NNN VARCHAR (100),

		@DEP_LINK	INT,
		@INN	VARCHAR (12),
		@KPP VARCHAR (9),
		@IMNS VARCHAR (4),
		@OKVED VARCHAR (8),
		@TLF_GL_BUH	VARCHAR (10),
		@POST_GL_BUH	VARCHAR (254),
		@DEP_NAME VARCHAR (254),

		@DOC_ID		VARCHAR (36),

		@NAME_RUK	VARCHAR (60),
		@FAM_RUK	VARCHAR (60),
		@OT_RUK		VARCHAR (60),

		@NAME_GL_BUH	VARCHAR (60),
		@FAM_GL_BUH	VARCHAR (60),
		@OT_GL_BUH	VARCHAR (60),

		@dDATE_FORM	DATETIME,
		@PERIOD_TYPE	INT,
		@PERIOD_NUM	INT,
		@cPERIOD_NUM	VARCHAR (2),

		@iLINK_TABLE	INT,
		@PROC_NAME	VARCHAR (254),

		--- Раздел 1 ---
		@KBK VARCHAR (20),
		@OKTMO VARCHAR (15),
		@OKTMO_DIC VARCHAR (15),
		@SUMMA	NUMERIC (15,0),

		@SUM_AV NUMERIC (15,0),
		@SUM_PAY NUMERIC (15,0),
		@SUM_LOW NUMERIC (15,0),

		@LINK_COL_CODE INT,
		@NUM_KOR NUMERIC (20),
		
		@strNUM_COR	VARCHAR (3),
		@C_PLACE	VARCHAR (3),
		
		@cREORG_CODE	VARCHAR (1),
		@cREORG_INN	VARCHAR (12),
		@cREORG_KPP	VARCHAR (12),
		
		@SUM1	NUMERIC (15,0),
		@SUM11	NUMERIC (15,0),
		@SUM12	NUMERIC (15,0),
		@SUM13	NUMERIC (15,0),
		@SUM2	NUMERIC (15,0),

		--- Раздел 2 ---
		@LINK_COL_VIDTS	INT,
		@LINK_COL_VIN	INT,
		@LINK_COL_MARKA	INT,
		@LINK_COL_REGNO	INT,
		@LINK_COL_NALBAS INT,
		@LINK_COL_OKEI	INT,
		@LINK_COL_SROK	INT,
		@LINK_COL_K3623	INT,
		@LINK_COL_STAVKA INT,
		@LINK_COL_SUM_IS	INT,
		@LINK_COL_LGOTA	INT,
		@LINK_COL_SUM_LGOTA	INT,
		@LINK_COL_SUM_UPL	INT,

		@strEXEC	VARCHAR (8000)

	--- Данные организации ---
	SELECT
		@DEP_LINK = RSF.LINK_ORGANIZATION,
		@dDATE_FORM	= RSF.BEGIN_DATE,
		@PERIOD_TYPE = RSF.PERIOD_TYPE,
		@PERIOD_NUM	= RSF.PERIOD_NUMBER,
		
		@INN	= CONVERT (VARCHAR (10), DEP.INN_LONG),
		@KPP = CONVERT (VARCHAR (9), DEP.KPP),
		@IMNS = CONVERT (VARCHAR (4), DEP.IMNS),
		@OKVED = CONVERT (VARCHAR (8), DEP.OKVED),
		@DEP_NAME = DEP.[NAME],
		@OKTMO_DIC = CONVERT (VARCHAR (11), REPLACE (DEP.OKTMO, ' ', ''))
		
	FROM dbo.REPORT_SAVED_FORMS RSF
	INNER JOIN dbo.DICTIONARY_DEPARTMENT DEP ON (DEP.LINK = RSF.LINK_ORGANIZATION)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	SET @cPERIOD_NUM = CASE
							WHEN @PERIOD_NUM = 1 THEN '21'
							WHEN @PERIOD_NUM = 2 THEN '22'
							WHEN @PERIOD_NUM = 3 THEN '23'
						END

	EXEC dbo.GetRandStr
			36,
			@DOC_ID OUTPUT

	SELECT
		@PART_NAME_NNN = @DOC_ID

	SELECT
		@TLF_GL_BUH = A.PHONE,
		@POST_GL_BUH = B.POST_NAME,

		@NAME_GL_BUH = B.IM,
		@FAM_GL_BUH = B.FM,
		@OT_GL_BUH = B.OT
	FROM dbo.DICTIONARY_OTV_FACE A
	LEFT JOIN dbo.KU_EMPL_PLACING B ON (B.LINK = A.FACE_LINK)
	WHERE A.DEP_LINK = @DEP_LINK
		AND A.[NAME] = 'Главный бухгалтер'
		
	SELECT
		@NAME_RUK = IM,
		@FAM_RUK = FM,
		@OT_RUK = OT
	FROM dbo.KU_EMPL_PLACING 
	WHERE LINK = (SELECT
						FACE_LINK
					FROM dbo.DICTIONARY_OTV_FACE
					WHERE DEP_LINK = @DEP_LINK
						AND [NAME] = 'Руководитель')

	--- !!!РАСЧЕТ!!! ---
	-- Данные раздела 1 --
	SELECT 
		@iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM
		AND ORDERS = 1

	CREATE TABLE #TAB1
		(
		CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(100),	-- 
		FCOL2 VARCHAR (1000),
		COL3 NUMERIC (20), 	-- 
		FCOL3 VARCHAR (1000),
		COL4 NUMERIC(20), 	-- 
		FCOL4 VARCHAR (1000),
		COL5 NUMERIC(20),	-- 
		FCOL5 VARCHAR (1000),
		COL6 NUMERIC (20), 	-- 
		FCOL6 VARCHAR (1000),
		COL7 NUMERIC (20), 	-- 
		FCOL7 VARCHAR (1000),
		COL8 NUMERIC(20),	-- 
		FCOL8 VARCHAR (1000),
		COL9 VARCHAR(100),	-- 
		FCOL9 VARCHAR (1000),
		COL10 VARCHAR (100),	-- 
		FCOL10 VARCHAR (1000),
		COL11 VARCHAR(100),	-- 
		FCOL11 VARCHAR (1000),
		COL12 VARCHAR(100),	-- 
		FCOL12 VARCHAR (1000),
		COL13 VARCHAR(100),	-- 
		FCOL13 VARCHAR (1000),
		COL14 VARCHAR(100),	-- 
		FCOL14 VARCHAR (1000),
		COL15 VARCHAR(100),	-- 
		FCOL15 VARCHAR (1000),
		ITOG NUMERIC(20)
		)
	
	IF @iLINK_TABLE > 0
	BEGIN
	
		SET @strEXEC = 'INSERT INTO #TAB1 (CHECKED, UPD, DEL,
							LINK_SAVED_FORM, LINK_ROW,
							ORDERS, CALC_ORDERS, PRINT_NULL,
							CODE, COL1, COL2, FCOL2, COL3, FCOL3,
							COL4, FCOL4, COL5, FCOL5, COL6, FCOL6,
							COL7, FCOL7, COL8, FCOL8, COL9, FCOL9,
							COL10, FCOL10, COL11, FCOL11, COL12, FCOL12,
							COL13, FCOL13, COL14, FCOL14, COL15, FCOL15,
							ITOG)
				EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
					+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--		SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--					+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

		EXECUTE (@strEXEC)
		
-- SELECT * FROM #TAB1
		
	END
	
	SELECT
		@OKTMO = ISNULL (COL2, ''),
		@KBK = ISNULL (COL9, ''),
		@strNUM_COR = ISNULL (COL10, ''),
		@C_PLACE = ISNULL (COL11, ''),
		@cPERIOD_NUM = ISNULL (COL12, ''),
		@cREORG_CODE = ISNULL (COL13, ''),
		@cREORG_INN = ISNULL (COL14, ''),
		@cREORG_KPP = ISNULL (COL15, ''),
		
		@SUM1	= ISNULL (COL3, 0),
		@SUM11	= ISNULL (COL4, 0),
		@SUM12	= ISNULL (COL5, 0),
		@SUM13	= ISNULL (COL6, 0),
		@SUM2	= ISNULL (COL7, 0) - ISNULL (COL7, 0)
	FROM #TAB1

	-- Данные раздела 2 --
	SET @iLINK_TABLE = 0
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM
		AND ORDERS = 2
		
	CREATE TABLE #TAB2
		(
		CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(100),	-- 
		FCOL2 VARCHAR (1000),
		COL3 VARCHAR(100),	-- 
		FCOL3 VARCHAR (1000),
		COL4 VARCHAR(100),	-- 
		FCOL4 VARCHAR (1000),
		COL5 VARCHAR(100),	-- 
		FCOL5 VARCHAR (1000),
		COL6 NUMERIC (20, 2), 	-- 
		FCOL6 VARCHAR (1000),
		COL7 VARCHAR(100), --
		FCOL7 VARCHAR (1000),
		COL8 VARCHAR(100), --
		FCOL8 VARCHAR (1000),
		COL9 NUMERIC (20), 	-- 
		FCOL9 VARCHAR (1000),
		COL10 NUMERIC (20), 	-- 
		FCOL10 VARCHAR (1000),
		COL11 NUMERIC (20, 4), -- 
		FCOL11 VARCHAR (1000),
		COL12 NUMERIC (20, 4), -- 
		FCOL12 VARCHAR (1000),
		COL13 NUMERIC (20), -- 
		FCOL13 VARCHAR (1000),
		COL14 NUMERIC (20),	-- 
		FCOL14 VARCHAR (1000),
		COL15 NUMERIC (20, 4), -- 
		FCOL15 VARCHAR (1000),
		
		COL16 VARCHAR(100), --
		FCOL16 VARCHAR (1000),
		COL17 NUMERIC (20), 	-- 
		FCOL17 VARCHAR (1000),
		COL18 VARCHAR(100), --
		FCOL18 VARCHAR (1000),
		COL19 NUMERIC (20), 	-- 
		FCOL19 VARCHAR (1000),
		COL20 VARCHAR(100), --
		FCOL20 VARCHAR (1000),
		COL21 NUMERIC (20), -- 
		FCOL21 VARCHAR (1000),
		COL22 NUMERIC (20), -- 
		FCOL22 VARCHAR (1000),
		
		ITOG NUMERIC(20) DEFAULT (0)
		)

	IF @iLINK_TABLE > 0
	BEGIN
		SET @strEXEC = 'INSERT INTO #TAB2 (CHECKED, UPD, DEL,
							LINK_SAVED_FORM, LINK_ROW,
							ORDERS, CALC_ORDERS, PRINT_NULL,
							CODE, COL1, COL2, FCOL2, COL3, FCOL3,
							COL4, FCOL4, COL5, FCOL5, COL6, FCOL6,
							COL7, FCOL7, COL8, FCOL8, COL9, FCOL9,
							COL10, FCOL10, COL11, FCOL11, COL12, FCOL12,
							COL13, FCOL13, COL14, FCOL14, COL15, FCOL15,
							COL16, FCOL16, COL17, FCOL17, COL18, FCOL18,
							COL19, FCOL19, COL20, FCOL20, COL21, FCOL21,
							COL22, FCOL22
							)
				EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
					+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'
		EXECUTE (@strEXEC)
	END

	--- Формирование XML ---
	SELECT @FNAME_ID = 'NO_TRAND_' + ISNULL (RTRIM (@IMNS), '0000') + '_' + ISNULL (RTRIM (@IMNS), '0000') + '_'
		+ ISNULL (RTRIM (@INN), '0000000000') + ISNULL (RTRIM (@KPP), '000000000')
		+ '_' + CONVERT (VARCHAR (10), GETDATE (), 112) + '_'
		+ SUBSTRING (@PART_NAME_NNN, LEN (@PART_NAME_NNN) - 36, 36) 

	SELECT @FNAME = RTRIM (@FNAME_ID) + '.XML'

	DECLARE @OUTPUT TABLE
		(
		ID int identity(1,1),
		F_NAME VARCHAR(254) DEFAULT (''),
		OUT_TEXT TEXT DEFAULT ('')
		)

	--Строка заголовка
	CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))

	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

	DECLARE
		@NAME_PROG varchar(254),
		@VERS_PROG VARCHAR(254)
		
	SELECT
		@NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
		@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
		+ '.' + (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
		+ '.' + (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
	FROM dbo.DICTIONARY_TASK
	WHERE CODE = 'SMETA'

	SET @NAME_PROG = RTRIM (@NAME_PROG) + ' ' + @VERS_PROG
	
	-- Заголовок --
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'OEM')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<?xml version ="1.0" encoding ="windows-1251"?>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Файл xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИдФайл="' + RTRIM (@FNAME_ID) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсПрог="' + RTRIM (LEFT (@NAME_PROG, 40)) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсФорм="5.02">')
	
	-- Документ -- 
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Документ КНД="1152004"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ДатаДок="' + CONVERT (VARCHAR (10), GETDATE (), 104) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Период="' + @cPERIOD_NUM + '"')	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ОтчетГод="' + LTRIM (STR (YEAR (@dDATE_FORM))) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КодНО="' + ISNULL (@IMNS, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НомКорр="' + ISNULL (@strNUM_COR, '0') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ПоМесту="' + ISNULL (@C_PLACE, '') + '">')

	-- Сведения о налогоплательщике --
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СвНП ОКВЭД="' + ISNULL (@OKVED, '') + '"')
	IF ISNULL (@TLF_GL_BUH, '') <> ''
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Тлф="' + RTRIM (ISNULL (@TLF_GL_BUH, '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '>')

	-- Сведения об организации --
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НПЮЛ НаимОрг="'
			 + RTRIM (ISNULL (REPLACE (@DEP_NAME, '"', '&quot;'), '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИННЮЛ="' + ISNULL (@INN, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КПП="' + ISNULL (@KPP, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '>')

	-- Сведения о реорганизованной (ликвидированной) организации (СвРеоргЮЛ) --
	IF LEN (@cREORG_CODE) > 0	
	BEGIN
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СвРеоргЮЛ ФормРеорг="'
			+ ISNULL (@cREORG_CODE, '') + '"')

		IF @cREORG_CODE LIKE '[1-3, 5-6]'
		BEGIN
			INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИННЮЛ="' + @cREORG_INN + '"')
			INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КПП="' + @cREORG_KPP + '"')
		END	
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '/>')
	END

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</НПЮЛ>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СвНП>')
	
	-- Лицо, подписавшее документ (Подписант) --
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Подписант ПрПодп="1">')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ФИО Фамилия="' + RTRIM (ISNULL (@FAM_RUK, '')) 
					+ '" Имя="' + RTRIM (@NAME_RUK) + '"'
					+ CASE WHEN ISNULL (@OT_RUK, '') <> '' THEN ' Отчество="' + RTRIM (ISNULL (@OT_RUK, '')) + '"'
							ELSE '' END
					+ '/>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Подписант>')

	-- Налоговая декларация по транспортному налогу (ТрНалНД) --
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ТрНалНД>')
	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СумНалПУ КБК="' + @KBK + '">')
	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СумПУ ОКТМО="' + @OKTMO + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалИсчисл="' + CONVERT (VARCHAR (15), @SUM1) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'АвПУКв1="' + CONVERT (VARCHAR (15), @SUM11) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'АвПУКв2="' + CONVERT (VARCHAR (15), @SUM12) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'АвПУКв3="' + CONVERT (VARCHAR (15), @SUM13) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + CONVERT (VARCHAR (15), @SUM2) + '">')

	-- Расчет суммы транспортного налога по каждому транспортному средству (РасчНалТС) --
--	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасчНалТС>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT)
	SELECT
		@FNAME,
		'<РасчНалТС КодВидТС="' + LTRIM (ISNULL (COL2, '')) 
		+ '" ИдНомТС="' + LTRIM (ISNULL (COL3, '')) 
		+ '" МаркаТС="' + LTRIM (ISNULL (COL4, '')) 
		+ '" РегЗнакТС="' + LTRIM (ISNULL (COL5, '')) 
		+ '" НалБаза="' + LTRIM (STR (ISNULL (COL6, 0), 16, 2))  
		+ '" ОКЕИНалБаза="' + LTRIM (ISNULL (COL7, ''))
		+ '" ЭкологКл="' + LTRIM (ISNULL (COL8, ''))
		+ '" ВыпускТС="' + LTRIM (STR (ISNULL (COL9, 0)))
		+ '" ВладенТС="' + LTRIM (STR (ISNULL (COL10, 0)))
		+ '" КоэфКв="' + LTRIM (STR (ISNULL (COL11, 0), 6, 4))  
		+ '" НалСтавка="' + LTRIM (STR (ISNULL (COL12, 0), 10, 2))
		+ '" СумИсчисл="' + LTRIM (STR (ISNULL (COL13, 0)))
		+ '" ЛьготМесТС="' + LTRIM (STR (ISNULL (COL14, 0)))
		+ '" КоэфКл="' + LTRIM (STR (ISNULL (COL15, 0), 6, 4))  
		+ '" СумИсчислУпл="' + LTRIM (STR (ISNULL (COL22, 0))) + '">'
		+ '<ЛьготОсвНал КодОсвНал="' + LTRIM (ISNULL (COL16, ''))
		+ '" СумОсвНал="' + LTRIM (STR (ISNULL (COL17, 0))) + '"/>'
		+ '<ЛьготУменСум КодУменСум="' + LTRIM (ISNULL (COL18, ''))
		+ '" СумУменСум="' + LTRIM (STR (ISNULL (COL19, 0))) + '"/>'
		+ '<ЛьготСнижСтав КодСнижСтав="' + LTRIM (ISNULL (COL20, ''))
		+ '" СумУменСум="' + LTRIM (STR (ISNULL (COL21, 0))) + '"/>'
		+ '</РасчНалТС>'
	FROM #TAB2 

--	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасчНалТС>')
	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СумПУ>')
	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СумНалПУ>')
	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ТрНалНД>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Документ>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Файл>')

	SELECT *
	FROM @OUTPUT
	ORDER BY ID

	DROP TABLE #TAB1
	DROP TABLE #TAB2
	DROP TABLE #TASK_PROP

END 

GO

GRANT EXECUTE ON dbo.[BK_EXPORT_F1152004_502] TO PUBLIC

GO

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


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[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 @D1	DATETIME,
	@D2	DATETIME,
	@DBYEAR DATETIME

/* ДАЖЕ ЕСЛИ КВАРТАЛЬНАЯ ФОРМА, МЕСЯЧНЫЕ ДАНЫЕ БЕРУТСЯ ЗА ПОСЛЕДНИЙ МЕС. КВАРТАЛА */
SET @D1 = DBO.DATEBEGINOFMONTH (@ENDDATE) 
SET @D2 = DATEADD(MONTH,1,@D1)-1
SET @DBYEAR = DBO.DATEBEGINOFYEAR(@BDATE)

DECLARE @SALARY_OPTIONS_OPT8_1 INT 
SET @SALARY_OPTIONS_OPT8_1 =  dbo.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPT8_1')

DECLARE @NAME VARCHAR(100)

INSERT INTO DBO.BUFFER (ID, LINK)
SELECT @BUFFER_SUBDIV, LINK FROM @SUBDIV WHERE @BUFFER_SUBDIV IS NOT NULL

DECLARE @CNT INT
SET @CNT = CONVERT(NUMERIC(18,1), DBO.SA_SCH_EMPLS(@D2, @DEP_LINK, 0, 0, 0, @BUFFER_SUBDIV))

DECLARE @CODE_FORM varchar(10)
SET @CODE_FORM  = (select top 1 Ltrim(code) from RN_REPORT_SAVED_FORMS_ARH where link_SAVED_form = @VARILSF)

/*** НАЧАЛЬНЫЕ УСТАНОВКИ ***/
/* ТАБЛИЦА РЕЗУЛЬТАТОВ РАСЧЕТА (СТОЛБЕЦ/ЗНАЧЕНИЕ) */
CREATE  TABLE #NZP_PART1(CODE_STR VARCHAR(10) , COL	INT, VAL NUMERIC(18,2), VAL_STR VARCHAR(20))

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

--- Таблица категорий для формы
CREATE TABLE #CAT_CODES (link int, code varchar (10), name_cat varchar (256) )
declare @STR varchar(8000),
		@SPHERE tinyint 
	set @STR  = ' insert #CAT_CODES
					select link , code, name_cat
					from PERS_CATEGORY_BY_SPHERE 
				 where '

	set @STR  =  @STR  + CASE when @CODE_FORM = '0606045'  then ' ZDRAV = 1' 
						  when @CODE_FORM = '0606046'  then ' KULT = 1' 
						  when @CODE_FORM = '0606047'  then ' SCIENCE = 1' 
						  when @CODE_FORM = '0606048'  then ' EDUC = 1'
						  when @CODE_FORM = '0606049'  then ' SOC = 1' end
	exec(@str)

	--- Определим сферу деятельности
	SET @SPHERE = CASE WHEN @CODE_FORM = '0606045' then  (select link from STO_SPHERES where NAME = 'Медицина')
					   WHEN @CODE_FORM = '0606046' then  (select link from STO_SPHERES where NAME = 'Культура')
					   WHEN @CODE_FORM = '0606047' then  (select link from STO_SPHERES where NAME = 'Наука')
					   WHEN @CODE_FORM = '0606048' then  (select link from STO_SPHERES where NAME = 'Образование')
					   WHEN @CODE_FORM = '0606049' then  (select link from STO_SPHERES where NAME = 'Социальная сфера') end 

--- Обновим одинаковые коды в зависимости от наименования категории
update #CAT_CODES
	set code = '3011'
	where code = '301' and name_cat = 'Научные работники учреждений ВПО'
update #CAT_CODES
	set code = '3012'
	where code = '301' and name_cat = 'Научные работники учреждений дополнительного профессионального образования'	
update #CAT_CODES
	set code = '3013'
	where code = '301' and name_cat = 'Научные работники'	
update #CAT_CODES
	set code = '3014'
	where code = '301' and name_cat = 'научные работники (исследователи)'	
update #CAT_CODES
	set code = '3111'
	where code = '311' and name_cat = 'Научные сотрудники (ВПО)'	
update #CAT_CODES
	set code = '3112'
	where code = '311' and name_cat = 'Научные сотрудники (ДПО)'	
update #CAT_CODES
	set code = '3113'
	where code = '311' and name_cat = 'Научные сотрудники '	


-- КОД КАТЕГОРИИ '100' - ВСЕГО  
/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */
--- Списочность считаем с начала года 
/*IF @CNT > 15 
	INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@D1, @D2, @DEP_LINK, 0, 1, 0, @BUFFER_SUBDIV))
ELSE	*/
	INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@DBYEAR, @D2, @DEP_LINK, 0, 1, 0, @BUFFER_SUBDIV))

/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */
/*IF @CNT > 15 
	INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 5, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@D1, @D2, @DEP_LINK, 0, 3, 0, @BUFFER_SUBDIV))
ELSE*/
	INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 5, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@DBYEAR, @D2, @DEP_LINK, 0, 3, 0, @BUFFER_SUBDIV))



SELECT * 
	INTO  #ssch_empls_nzp_ALL 
	FROM sa_ssch_empls_nzp_ALL(@DBYEAR, @D2, @DEP_LINK, @BUFFER_SUBDIV)


/* Разбивка по категориям */
DECLARE @Cur1 CURSOR, @LINK_CAT INT , @CODE_CAT varchar(10), @NAME_CAT varchar(254)
SET @Cur1 = CURSOR FORWARD_ONLY

FOR SELECT LINK, CODE, NAME_CAT FROM #CAT_CODES order by link

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @LINK_CAT, @CODE_CAT, @NAME_CAT
WHILE (@@fetch_status <> -1)
BEGIN

	IF (@@fetch_status <> -2)
	BEGIN
		
		SET @CODE_CAT = LTRIM(@CODE_CAT)
		SET @NAME_CAT = LTRIM(@NAME_CAT)
		
		IF @CODE_CAT like ('%301%') 
		BEGIN
			/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */
			/*IF @CNT > 15 
				INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS_NZP(@D1, @D2, @DEP_LINK, 0, 1, 0,@SPHERE, @BUFFER_SUBDIV,'301',@NAME_CAT))
			ELSE*/
				INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT @CODE_CAT, 4,  ISNULL((SELECT CONVERT(NUMERIC(18),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),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),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),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),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 @CNT > 15
	SELECT --За месяц
		@M=SUM(CASE 
			WHEN DGH.DATE1<=@D1 AND COALESCE(DGH.DATE2,@D2)>=@D2 THEN DATEDIFF(DAY,@D1,@D2)		-- РАБОТАЛ ВЕСЬ ПЕРИОД
			WHEN DGH.DATE1<=@D1 AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE2>@D1 THEN DATEDIFF(DAY,@D1,DGH.DATE2)+1	-- УВОЛЕН В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@D1  AND COALESCE(DGH.DATE2,@D2)>=@D2 AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,@D2) 		-- ПРИНЯТ В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@D1  AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,DGH.DATE2)+1	-- ПРИНЯТ И УВОЛЕН В РАБОЧИЙ ПЕРИОД
			 ELSE 0
		END)
	FROM 
		dbo.REESTR_DGH DGH
	WHERE
			DEP_LINK = @DEP_LINK 
		AND
			DGH.DATE1 <= @D2 AND DGH.DATE2 >= @D1
		AND
		NOT EXISTS (
			SELECT E.PERS_LINK FROM DBO.SD_EMPL_FN(DEFAULT,@D2,DEFAULT,@DEP_LINK) E
			WHERE DGH.PERS_LINK = E.PERS_LINK AND DGH.DATE1 <= ISNULL(E.DATE_END,ISNULL(DGH.DATE2,@D2)) AND ISNULL(DGH.DATE2,@D2) >= E.DATE_BEGIN 
			)
ELSE
	SELECT --С начала года
		@M=SUM(CASE 
			WHEN DGH.DATE1<=@DBYEAR AND COALESCE(DGH.DATE2,@D2)>=@D2 THEN DATEDIFF(DAY,@DBYEAR,@D2)		-- РАБОТАЛ ВЕСЬ ПЕРИОД
			WHEN DGH.DATE1<=@DBYEAR AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE2>@DBYEAR THEN DATEDIFF(DAY,@DBYEAR,DGH.DATE2)+1	-- УВОЛЕН В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@DBYEAR  AND COALESCE(DGH.DATE2,@D2)>=@D2 AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,@D2) 		-- ПРИНЯТ В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@DBYEAR  AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,DGH.DATE2)+1	-- ПРИНЯТ И УВОЛЕН В РАБОЧИЙ ПЕРИОД
			 ELSE 0
		END)
	FROM 
		dbo.REESTR_DGH DGH
	WHERE
			DEP_LINK = @DEP_LINK 
		AND
			DGH.DATE1 <= @D2 AND DGH.DATE2 >= @DBYEAR
		AND
		NOT EXISTS (
			SELECT E.PERS_LINK FROM DBO.SD_EMPL_FN(DEFAULT,@D2,DEFAULT,@DEP_LINK) E
			WHERE DGH.PERS_LINK = E.PERS_LINK AND DGH.DATE1 <= ISNULL(E.DATE_END,ISNULL(DGH.DATE2,@D2)) AND ISNULL(DGH.DATE2,@D2) >= E.DATE_BEGIN 
			)				

DECLARE	@NDAYSFEBR	INT
IF @CNT > 15
	SET @NDAYSFEBR = DAY(DBO.DATEENDOFMONTH(@D1))
ELSE
	SET @NDAYSFEBR = ISNULL((SELECT SUM(DAY(DBO.DATEENDOFMONTH(DATE_BEGIN))) FROM dbo.MONTHS_EX(@DBYEAR, @D2)),99999999)


----INSERT INTO #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! РАЗБИВКА ПО КОДАМ */		
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT c.code, 6, 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 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, 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)
																		
																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)
					

	/* COL7! РАЗБИВКА ПО КОДАМ*/
	--INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL)
	--	SELECT c.code, 7, 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=7 AND s.STAT_OTCHET=1 AND s.DEP_TYPE<>5
	--		AND s.CAT_NZP_LINK IS NOT NULL
	--		AND
	--		(	@CNT <= 15 AND MONTH(s.PERIOD_END) <= MONTH(@ENDDATE)
	--			OR
	--			@CNT > 15 AND MONTH(s.PERIOD_END) = MONTH(@ENDDATE)
	--		)
	--	GROUP BY c.code
	
		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)
																		
																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)
			
	/* 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)
																		
																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)
			
	/* 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)
																		
																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)
			
	/* 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)
																		
																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)
			
	/* 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)
																		
																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)
			
	/* 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)
																		
																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)
			
	/* 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)
																		
																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)
			
	/* 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)
																		
																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.[BK_UPDATE_G_PROV_CARD]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_UPDATE_G_PROV_CARD]

GO






/*
© Кейсистемс (Keysystems), 2005
*/
CREATE   PROCEDURE dbo.BK_UPDATE_G_PROV_CARD
	@varKSintDOC_LINK	int,
	@varKSintOBJECT		int,
	@varKSintDICTION		int
AS
DECLARE
	@varKSERROR	int,
	@varKSRowCount	int,
	@varKStrancount	int
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
	IF @varKSintDICTION is null
	BEGIN
		DELETE FROM G_PROV_CARD WHERE DOC_LINK = @varKSintDOC_LINK AND OBJECT = @varKSintOBJECT
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN 7
		END
	END
	ELSE
	BEGIN
		SELECT @varKSintDICTION = (Select LINK FROM CARDS WITH (ROWLOCK) WHERE LINK = @varKSintDICTION)
		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK TRAN
			RETURN 3
		END
		UPDATE G_PROV_CARD
			SET CARD = @varKSintDICTION
			WHERE DOC_LINK = @varKSintDOC_LINK AND OBJECT = @varKSintOBJECT
		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			INSERT INTO G_PROV_CARD (DOC_LINK, OBJECT, CARD)
			VALUES (@varKSintDOC_LINK, @varKSintOBJECT, @varKSintDICTION)
			IF @@ERROR <> 0
			BEGIN
				ROLLBACK TRAN
				RETURN 7
			END
		END
	END
IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0





GO


GRANT EXECUTE ON dbo.[BK_UPDATE_G_PROV_CARD] TO PUBLIC

GO


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


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

GO

CREATE PROCEDURE dbo.RSD_REPORT_FORMULA_AVPAT3_NASTR_VALUE  
	@res varchar(250) output, @varcStr varchar(250), @vardBegin datetime = '20050101', @vardEnd datetime = '20051231', @variCol int, @variRow int, @variLSF int
AS
	DECLARE @intPER_TYPE	INT,
		@intPER_NUM	INT

	set @res = ''
	if @varcStr = 'ОКАТО'
	begin
		SELECT @Res = REPLACE(DEP.OKATO, ' ', '') FROM DICTIONARY_DEPARTMENT DEP inner join report_saved_forms RSF on RSF.Link_Saved_Form = @variLSF and DEP.link = RSF.Link_Organization
		return 0
	end
	if @varcStr = 'БЛОК1'
	begin
		SELECT @res = CASE WHEN LEN(ISNULL(DOH_CODE, '')) = 0 THEN '-' ELSE DOH_CODE END FROM AVANSE_ASSETS_OPTIONS
		return 0
	end
	if @varcStr = '160'
	begin
		SELECT @res = ISNULL(CODE520, '') FROM AVANSE_ASSETS_OPTIONS
		return 0
	end
	if @varcStr = '200'
	begin
		SELECT @res = ISNULL(CODE200, '') FROM AVANSE_ASSETS_OPTIONS
		return 0
	end
	if @varcStr = '210'	
	begin
		SELECT @res = ISNULL([PERCENT], 0.00) FROM AVANSE_ASSETS_OPTIONS
		return 0
	end
	if @varcStr = '240'
	begin
		SELECT @res = ISNULL(CODE240, '') FROM AVANSE_ASSETS_OPTIONS
		return 0
	end
	if @varcStr = 'Т.Н.ДОХ.КОД'
	begin
		SELECT @Res = ISNULL(TDOH_CODE, '') FROM AVANSE_ASSETS_OPTIONS
		return 0
	end

	-- Код налогового периода --
	IF @varcStr = 'КОД_НАЛ_ПЕР'
	BEGIN
		SELECT @intPER_TYPE	=	PERIOD_TYPE,
			@intPER_NUM	=	PERIOD_NUMBER
		FROM dbo.REPORT_SAVED_FORMS RSF 
		WHERE RSF.Link_Saved_Form = @variLSF
		
		IF @intPER_TYPE	= 1
			SET @Res = '34'

		IF @intPER_TYPE	= 2
			SET @Res =
				CASE
					WHEN @intPER_NUM = 1 THEN '21'
					WHEN @intPER_NUM = 2 THEN '31'
					WHEN @intPER_NUM = 3 THEN '33'
					ELSE '34'
				END	
		RETURN 0
	END

	if @varcStr = 'О_К_Т_М_О'
	begin
		SELECT
			@Res = REPLACE(DEP.OKTMO, ' ', '')
		FROM dbo.DEPARTMENTS DEP
		INNER JOIN dbo.REPORT_SAVED_FORMS RSF ON RSF.Link_Saved_Form = @variLSF and DEP.link = RSF.Link_Organization
		return 0
	end

GO


GRANT EXECUTE ON dbo.[RSD_REPORT_FORMULA_AVPAT3_NASTR_VALUE] TO PUBLIC

GO


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


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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

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

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

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



-- Таблица 2 (FROM)
SELECT BUDG_LEVEL  = case D.BUH_TYPE WHEN 1 then cast(replace(B.CODE_EL,'0','') as char(1)) else '6' end,
		KOD_UBP 	= case cast(replace(B.CODE_EL,'0','') as char(1)) when 1 then D.CODE_UBP else BUDG end,
		NAME_UBP	= D.FULL_NAME
from dbo.DEPARTMENTS D
left join dbo.KL_ADMIN_BS V WITH (NOLOCK) on V.LINK = D.VED_LINK
left join dbo.KL_BUDG_TYPE B WITH (NOLOCK) on V.Link_Budg = B.LINK
where D.LINK = @iDepLink


-- Таблица 3 (TO)
SELECT 	KOD_TOFK  = TOFK.CODE,
		NAME_TOFK = TOFK.FULL_NAME
from dbo.DEPARTMENTS D
inner join dbo.TREASURY TOFK on D.TOFK_LINK = TOFK.LINK
where D.LINK = @iDepLink



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


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

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

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

		select * from @tBlok5 order by LINK_UP, orders 

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

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


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

		from dbo.RECEPTION_CASH_table_view ZT
		inner join @tBlok5 CH ON CH.LINK_UP = ZT.LINK_UP and (ZT.KP = CH.CHECK_KAS or ZT.KP ='')
		where ZT.LINK_UP in (select LINK from dbo.BufferGetTableByID(@cBuffId))
end







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





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



CREATE	PROCEDURE X_UPDATE_FINANSE_CONTRACT
	@varKSintLINK	int	OUTPUT,
	@varKSintLINK_UP	int,
--	@varKSnRECORD_NO	NUMERIC(10),
--	@varKSnREC_CH_NO	NUMERIC(10),
	@varKScRECORD_NO	char(10),
	@varKScREC_CH_NO	char(10),
	@varKSintVKR		int,
	@varKSintEKR		int,
	@varKSintDop_Class	int,
	@i@iOKDP		int,
	@nQuantity		numeric(19,4),
	@nCost			numeric(19,2),
	@nSumma			numeric(19,2),
	@varKSP1		numeric(19,2),
	@varKSP2		numeric(19,2),
	@varKSP3		numeric(19,2),
	@varKSP4		numeric(19,2),
	@varKSP5		numeric(19,2),
	@varKSP6		numeric(19,2),
	@varKSP7		numeric(19,2),
	@varKSP8		numeric(19,2),
	@varKSP9		numeric(19,2),
	@varKSP10		numeric(19,2),
	@varKSP11		numeric(19,2),
	@varKSP12		numeric(19,2)
	
AS
Declare
	@varKSERROR	int,
	@varKSRowCount	int,
	@varKStrancount	int
--	@varKScRECORD_NO	char(10),
--	@varKScREC_CH_NO	char(10)

--SET @varKScRECORD_NO = STR(@varKSnRECORD_NO)
--SET @varKScREC_CH_NO = STR(@varKSnREC_CH_NO)
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
	IF @varKSintLINK is null OR @varKSintLINK = 0
	BEGIN
		INSERT INTO FINANSE_CONTRACT(LINK_UP, RECORD_NO, RECORD_CH_NO, VKR, EKR, Dop_Classif, OKDP, QUANTITY, COST, SUMMA, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)
			VALUES (@varKSintLINK_UP, @varKScRECORD_NO, @varKScREC_CH_NO, @varKSintVKR, @varKSintEKR, @varKSintDop_Class, @i@iOKDP, @nQuantity, @nCost, @nSumma, @varKSP1, @varKSP2, @varKSP3, @varKSP4, @varKSP5, @varKSP6, @varKSP7, @varKSP8, @varKSP9, @varKSP10, @varKSP11, @varKSP12)
		SELECT @varKSERROR = @@ERROR, @varKSintLINK = @@IDENTITY
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	ELSE
	BEGIN
		UPDATE FINANSE_CONTRACT
			SET LINK_UP 	     = @varKSintLINK_UP,
				RECORD_NO    = @varKScRECORD_NO,
				RECORD_CH_NO =@varKScREC_CH_NO,
				VKR 	     = @varKSintVKR,
				EKR 	     = @varKSintEKR,
				Dop_Classif  = @varKSintDop_Class,
				OKDP 	     = @i@iOKDP, 
				QUANTITY     = @nQuantity, 
				COST	     = @nCost,
				SUMMA	     = @nSumma,
				P1  = @varKSP1,
				P2  = @varKSP2,
				P3  = @varKSP3,
				P4  = @varKSP4,
				P5  = @varKSP5,
				P6  = @varKSP6,
				P7  = @varKSP7,
				P8  = @varKSP8,
				P9  = @varKSP9,
				P10 = @varKSP10,
				P11 = @varKSP11,
				P12 = @varKSP12
		
		WHERE LINK = @varKSintLINK
		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END
IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO

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

GO

CREATE PROCEDURE dbo.SD_PAYS_EMPL_INDEX
@varKSStrReturn VARCHAR(150) OUTPUT,
 @varKSparLinkEmpl int,
 @varKSparLinkPays int,
 @varKSparDateBegin datetime,
 @varKSparSumma numeric(15,6) = 0,
 @ROUND_MODE tinyint = 1, --1 - не округлять, 2 - окр до 10 коп, 3 окр до руб, 4 окр до 10 руб, ...
 @roundFunction tinyint = 0 -- 0 - округлять, 1 - вниз, 2 - вверх
AS

--Параметры округления
SET @ROUND_MODE = COALESCE(@ROUND_MODE,1)
SET @roundFunction = COALESCE(@roundFunction,0)

DECLARE  
	@varKSNameEmpl Varchar(30),
	@varKSEventText Varchar(150),
	@varKSNamePays  Varchar(60),
	@varKSsoDictPE	int,	
	@varKSDate DATETIME,	
	@varKSSumma numeric(15,4),
	@LINK_KBK INT

SET @varKSNameEmpl = dbo.sd_GetEmplName(@varKSparLinkEmpl)
SELECT @varKSNamePays =  NAME FROM dbo.PAYS WHERE LINK = @varKSparLinkPays
SELECT @varKSsoDictPE = LINK  FROM S_OBJECTS WHERE CODE = 'DICTIONARY_PAYS_EMPL'

DECLARE @PART NUMERIC(18,2)
SET @PART = (CASE @ROUND_MODE 
				WHEN 1 THEN 0 --Не округлять
				WHEN 2 THEN 0.10 --Округлять до 10 копеек				
				WHEN 3 THEN 1 --Округлять до 1 рубля
				WHEN 4 THEN 5 --Округлять до 5 рублей
				WHEN 5 THEN 10 --Округлять до 10 рублей
				WHEN 6 THEN 50 --Округлять до 50 рублей
				WHEN 7 THEN 100 --Округлять до 100 рублей
				WHEN 8 THEN 1000 --Округлять до 1000 рублей
				WHEN 9 THEN 10000 --Округлять до 10000 рублей
				ELSE 0 --Не округлять
			END)

DECLARE @TABLE TABLE(LINK_EMPL INT,LINK_SOVM INT,LINK_PAYS INT,[DATE] DATETIME)

;WITH PE (LINK_EMPL, LINK_SOVM, LINK_PAYS, DATE_BEG)
AS (
	SELECT LINK_EMPL, ISNULL(LINK_SOVM,0), LINK_PAYS, MAX(DATE)
	FROM 
		dbo.PAYS_EMPL PE
	WHERE
		PE.LINK_EMPL = @varKSparLinkEmpl
		AND
		PE.LINK_PAYS = @varKSparLinkPays
		AND
		PE.DATE <= @varKSparDateBegin
	GROUP BY
		LINK_EMPL, ISNULL(LINK_SOVM,0), LINK_PAYS	
)		
INSERT INTO dbo.PAYS_EMPL(LINK_EMPL,LINK_SOVM,LINK_PAYS,[DATE],SUMMA, LINK_KBK)
OUTPUT INSERTED.LINK_EMPL, INSERTED.LINK_SOVM, INSERTED.LINK_PAYS, INSERTED.[DATE] INTO @TABLE
SELECT 
	PE.LINK_EMPL, 
	PE.LINK_SOVM, 
	PE.LINK_PAYS, 
	@varKSparDateBegin, 
	NEW_SUMMA = dbo.SA_ROUND( (PE2.SUMMA * (1+@varKSparSumma/100)), @PART, @roundFunction), 
	ISNULL(@LINK_KBK,PE2.LINK_KBK)
FROM 
	PE 
	INNER JOIN dbo.PAYS_EMPL AS PE2 ON PE2.LINK_EMPL = PE.LINK_EMPL AND ISNULL(PE2.LINK_SOVM,0) = PE.LINK_SOVM AND PE2.LINK_PAYS = PE.LINK_PAYS AND PE2.[DATE] = PE.DATE_BEG
WHERE
	PE.DATE_BEG < @varKSparDateBegin	

IF EXISTS (SELECT * FROM @TABLE) BEGIN
	SET @varKSEventText = 'Индексация начисления: ('+ LTRIM(RTRIM(@varKSNamePays))+') ' +  RTRIM(LTRIM(@varKSNameEmpl)) + '  на  ' + LTRIM(RTRIM(STR(@varKSparSumma))) +'%' 
	EXECUTE WF_GENERATEEVENT 'Индексация начисления', @varKSEventText, @varKSsoDictPE, 'PAYS_EMPL'
END

GO


GRANT EXECUTE ON dbo.[SD_PAYS_EMPL_INDEX] 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_FINANS_CONTRACT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[X_SAVE_FINANS_CONTRACT]
GO







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

CREATE             

PROCEDURE dbo.X_SAVE_FINANS_CONTRACT
	@varKSpLINK		int	OUTPUT,
	@varKSpNUMBER	char(25) = null,
	@varKSpDATE		datetime = null,
	@varKSpDATE_PROV	datetime = null,
	@varKSpSumma		numeric(19,2) = 0,
	@varKSpComment		varchar(254) = null,
	@varKSpSUMMA_F        NUMERIC(18,2) = null,
	@varKSpDEP_LINK       INT = null,
	@varKSpPER_ACC_LINK   INT = null,
	@varKSpDEP_LINK_P     INT = null,
	@varKSpDATE_NA        DATETIME = null,
	@varKSpDATE_ACCEPT    DATETIME = null,
	@varKSpCON_PAY        TINYINT = null,
	@varKSpMAINTENANCE    VARCHAR(7500) = null,
	@varKSpDATE_BEGIN     DATETIME = null,
	@varKSpDATE_END       DATETIME = null,
	@varKSpDOG_LINK       INT = null,
	@varKSpSUMMA_DB       NUMERIC(18,2) = null,
	@varKSpSUMMA_KT       NUMERIC(18,2) = null,
	@varKSpNUMBER_BO      char(10) = null,
	@varKSpFIN_SOURCE     TINYINT = 1,
	@iGZ     	      TINYINT = 0,
	@iTYPE  	      TINYINT
	

AS
SET LOCK_TIMEOUT 30000
SET IMPLICIT_TRANSACTIONS ON
DECLARE @varKSERROR	tinyint,
		@varKSstrVALUE	varchar(7000),
		@varKSEventText	varchar(254),
		@varKStrancount	int,
		@varKSpObj_LINK	INT,
		@varKSOurDep 	int


SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	
	IF @varKSpDATE_PROV is not null and not exists(Select * from admin_info Where @varKSpDATE_PROV BETWEEN BEGINDATE AND ENDDATE)
	BEGIN
		ROLLBACK
		RETURN 15
	END

	select @varKSpObj_LINK = LINK, @varKSEventText = RTRIM(NAME) from s_objects where (code = 'FINANS_CONTRACT' and @varKSpDOG_LINK is null) or (code = 'FINANS_CONTRACT_CHANGE' and @varKSpDOG_LINK is not null)


	EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV @varKSpLINK OUTPUT, @varKSpNUMBER, @varKSpDATE, @varKSpObj_LINK,
	 @varKSpDATE_PROV, @varKSpSumma, @varKSpComment,0,@varKSpDEP_LINK, @varKSpPER_ACC_LINK
	IF @varKSERROR <> 0
		RETURN @varKSERROR	
	
	IF exists (select * from FINANSE_CONTRACT_HEAD where link_g_prov = @varKSpLINK)
		UPDATE FINANSE_CONTRACT_HEAD
			SET CON_PAY = @varKSpCON_PAY,
			DATE_ACCEPT = @varKSpDATE_ACCEPT,
			DATE_BEGIN = @varKSpDATE_BEGIN,
			DATE_END = @varKSpDATE_END,
			DATE_NA = @varKSpDATE_NA,
			DEP_LINK_P = @varKSpDEP_LINK_P,
			MAINTENANCE = @varKSpMAINTENANCE,
			SUMMA_DB = @varKSpSUMMA_DB,
			SUMMA_F = @varKSpSUMMA_F,
			SUMMA_KT = @varKSpSUMMA_KT,
			DOG_LINK = @varKSpDOG_LINK,
			NUMBER_BO = @varKSpNumber_bo,
			FIN_SOURCE = @varKSpFIN_SOURCE,
			GZ = @iGZ,
			TYPE = @iTYPE
		WHERE link_g_prov = @varKSpLINK
	ELSE
		INSERT INTO FINANSE_CONTRACT_HEAD (link_g_prov, CON_PAY, DATE_ACCEPT, DATE_BEGIN, DATE_END, 
			DATE_NA,  DEP_LINK_P, MAINTENANCE,  SUMMA_DB, SUMMA_F, SUMMA_KT, DOG_LINK, Number_BO, FIN_SOURCE, GZ, TYPE)
		VALUES (@varKSpLINK, @varKSpCON_PAY, @varKSpDATE_ACCEPT, @varKSpDATE_BEGIN, 
			@varKSpDATE_END, @varKSpDATE_NA, @varKSpDEP_LINK_P, @varKSpMAINTENANCE, 
			 @varKSpSUMMA_DB, @varKSpSUMMA_F, @varKSpSUMMA_KT, @varKSpDOG_LINK, @varKSpNumber_bo, @varKSpFIN_SOURCE, @iGZ, @iTYPE)

	SET @varKSEventText = @varKSEventText + ' №' + RTRIM(@varKSpNUMBER) + ' от ' + convert(varchar, @varKSpDATE, 104)
	EXECUTE WF_GENERATEEVENT 'Сохранение документа', @varKSEventText, @varKSpObj_LINK, 'G_PROV', @varKSpLINK
IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

GO
CREATE PROCEDURE dbo.SA_4FSS_28022011_PREPARE_INV @LSF INT
AS

DECLARE 
	@START_DATE DATETIME, @END_DATE DATETIME, @DEP_LINK INT, @BYearDate DATETIME,
	@nYEAR INT, @nMONTH1 INT, @nMONTH2 INT, @nMONTH3 INT

SELECT
	@DEP_LINK = Link_Organization,
	@START_DATE = BEGIN_DATE
FROM
	report_saved_forms 
WHERE
	link_saved_form = @LSF

SET @BYearDate = dbo.DateBeginOfYear (@START_DATE)

SELECT 
	@nYEAR = YEAR(@START_DATE),
	@nMONTH1 = MONTH(@START_DATE)-2,
	@nMONTH2 = MONTH(@START_DATE)-1,
	@nMONTH3 = MONTH(@START_DATE)

DECLARE @varKSname VARCHAR(100), @varKSSQL VARCHAR(8000)
SET @varKSname = (SELECT ID FROM BUFFER WHERE LINK = -116 AND SID = SUSER_SID() )

CREATE TABLE #RAZD31 (LINK INT, COL2 VARCHAR(100),COL5 NUMERIC(18,2), COL6 NUMERIC(18,2), COL7 NUMERIC(18,2), COL8 NUMERIC(18,2))

SET @varKSSQL = '
	INSERT INTO #RAZD31 (LINK, COL2, COL5, COL6, COL7, COL8)
	SELECT
		I.LINK,  
		LEFT(LTRIM(RTRIM(P.FM)) + '' '' + LTRIM(RTRIM(P.IM)) + '' '' + LTRIM(RTRIM(P.OT)),100),
		I.COL5, I.COL6, I.COL7, I.COL8
	FROM ' + @varKSname + ' I
		INNER JOIN dbo.PERSON P ON P.LINK = I.LINK
	ORDER BY
		P.FM, P.IM, P.OT'

EXEC (@varKSSQL)

SELECT 
	CODE = CONVERT(VARCHAR(4),RANK() OVER (ORDER BY COL2,DOC_DATE)),
	COL1 = CONVERT(VARCHAR(4),RANK() OVER (ORDER BY COL2,DOC_DATE)),
	COL2,
	COL3 = ISNULL(CONVERT(VARCHAR(10),DOC_DATE,104),''),
	COL4 = ISNULL(CONVERT(VARCHAR(10),DATE_END,104),''),
	COL5, COL6, COL7, COL8
FROM
	#RAZD31 E
	INNER JOIN dbo.pers_invalid I ON E.LINK = I.PERS_LINK
	INNER JOIN 
		(SELECT I1.PERS_LINK, DATE_BEGIN = MAX(I1.DATE_BEGIN) FROM dbo.pers_invalid I1 WHERE 
				YEAR(ISNULL(I1.DATE_BEGIN, @START_DATE)) * 100 + MONTH(ISNULL(I1.DATE_BEGIN, @START_DATE)) <= @nYEAR * 100 + @nMONTH3
				AND
				YEAR(ISNULL(I1.DATE_END, @START_DATE)) * 100 + MONTH(ISNULL(I1.DATE_END, @START_DATE)) >= @nYEAR * 100 + 1
			GROUP BY I1.PERS_LINK	
		) I2 ON I.PERS_LINK = I2.PERS_LINK AND I.DATE_BEGIN = I2.DATE_BEGIN	
WHERE
	YEAR(ISNULL(I.DATE_BEGIN, @START_DATE)) * 100 + MONTH(ISNULL(I.DATE_BEGIN, @START_DATE)) <= @nYEAR * 100 + @nMONTH3
	AND
	YEAR(ISNULL(I.DATE_END, @START_DATE)) * 100 + MONTH(ISNULL(I.DATE_END, @START_DATE)) >= @nYEAR * 100 + 1
ORDER BY
	COL2, DOC_DATE

DROP TABLE #RAZD31
	

RETURN 0

GO


GRANT EXECUTE ON dbo.[SA_4FSS_28022011_PREPARE_INV] TO PUBLIC

GO




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

GO

CREATE PROCEDURE dbo.SD_REP_2NDFL
	@varKScYear varchar(4),			
	@varKSnFirstNum INT,	
	@nCHECK_S int = 0,					   /*Определить перечисленную сумму по проводкам*/
	@nSumm_For_Check numeric(18,2) = null, /*Перечисленная сумма НДФЛ за период*/			
	@varKScVal1 char(1), @varKSnOtborLink1 int,	
	@varKScVal2 char(1), @varKSnOtborLink2 int,
	@nLinkEmpl int = 0,
	@nMonth int = 12,
	@LINK_PERS INT = NULL

	
AS BEGIN

SET NOCOUNT ON
	Set @nMonth = ISNULL(@nMonth,12)

	DECLARE @varKSnYear INT
	SET @varKSnYear = CAST(@varKScYear AS INT)

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

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK OUTPUT
	


	

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

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

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

		ksv1 varchar(3), ssv1 numeric(11,2),
		ksv2 varchar(3), ssv2 numeric(11,2),
		ksv3 varchar(3), ssv3 numeric(11,2),
		ksv4 varchar(3), ssv4 numeric(11,2),
		ksv5 varchar(3), ssv5 numeric(11,2),
		ksv6 varchar(3), ssv6 numeric(11,2),
		ksv7 varchar(3), ssv7 numeric(11,2),
		ksv8 varchar(3), ssv8 numeric(11,2),
		ksv9 varchar(3), ssv9 numeric(11,2),
		ksv10 varchar(3), ssv10 numeric(11,2),
		ksv11 varchar(3), ssv11 numeric(11,2),
		ksv12 varchar(3), ssv12 numeric(11,2),
		ssv numeric(11,2), siv numeric(11,2),
		osd13 numeric(11,2), sdo13 numeric(11,2), 
		nalogn13 numeric(18), nalogu13 numeric(18),
		NALOG13S numeric(18),
		err int,
		S_5_6 NUMERIC(18,2), S_5_7 NUMERIC(18,2),		
		dolg_np numeric(8), dolg_na numeric(8),
		kbkcode1 varchar(20), kbkcode2 varchar(20), kbkcode3 varchar(20), kbkcode4 varchar(20), 
		kbksum1 numeric(18,2), kbksum2 numeric(18,2),kbksum3 numeric(18,2),kbksum4 numeric(18,2),
		VIFNSPL numeric(18,2),
		ZSummPL numeric(18,2),
		UdSumPL numeric(18,2),
		VzkIFNS numeric(18,2)

	)	


	CREATE TABLE #FACES (LINK int,PERS_LINK int)

	IF @nLinkEmpl = 0
	BEGIN

		IF (len(@varKScVal1) = 0) AND (len(@varKScVal2) = 0 )
			INSERT INTO #FACES
			SELECT distinct PERS_LINK,PERS_LINK FROM dbo.empl WHERE DEP_LINK = @DEP_LINK --AND dbo.ku_GetEmplSack(link,default) = 0
		ELSE 
		if len(@varKScVal1) <> 0
			INSERT INTO #FACES 
			SELECT distinct Min(RECORD),E.PERS_LINK 
			FROM dbo.EMPL E INNER JOIN dbo.OBJECT_VAR_EMPL OVE ON OVE.RECORD = E.LINK
			WHERE LINK_UP = @varKSnOtborLink1
			GROUP BY E.PERS_LINK

		IF (len(@varKScVal1) = 0) AND (len(@varKScVal2) = 0 )
			INSERT INTO #FACES
			SELECT distinct PERS_LINK,PERS_LINK FROM dbo.SALARY_REESTR_DGH WHERE DEP_LINK = @DEP_LINK
				AND PERS_LINK NOT IN (SELECT PERS_LINK FROM #FACES)
		ELSE 
		IF len(@varKScVal2) <> 0
			INSERT INTO #FACES 
			SELECT distinct Min(RECORD), P.LINK 
			FROM dbo.PERSON P INNER JOIN dbo.OBJECT_VAR_PERSON OVE ON OVE.RECORD = P.LINK  
			WHERE LINK_UP = @varKSnOtborLink2 AND P.LINK NOT IN (SELECT PERS_LINK FROM #FACES)
			GROUP BY P.LINK
	END
	IF @nLinkEmpl > 0
	BEGIN
		INSERT INTO #FACES
		SELECT distinct LINK,PERS_LINK FROM dbo.empl WHERE LINK = @nLinkEmpl and DEP_LINK = @DEP_LINK
	END
	
	IF @nLinkEmpl IS NULL
		INSERT INTO #FACES (LINK, PERS_LINK)
		VALUES (0, @LINK_PERS)

	-----------------------------
	delete from dbo.SAL_DED_MONTH
	where 
	YEAR(DATE_DED) = @varKSnYear
	AND
	Month(DATE_DED) <= @nMonth
	AND
	LINK_EMPL IN (Select EM.LINK from dbo.EMPL EM INNER JOIN #FACES F on EM.PERS_LINK = F.PERS_LINK)
	AND
	LINK IN 
	(
		select D.LINK 
		from dbo.SAL_DED_MONTH D inner join dbo.empl E on D.link_empl = E.link
		where YEAR(D.DATE_DED) = @varKSnYear AND Month(D.DATE_DED) <= @nMonth
		and not exists (Select * from dbo.CALCULATE_JURNAL JC where YEAR(JC.PERIOD_BEGIN) = @varKSnYear AND Month(JC.PERIOD_BEGIN) <= @nMonth AND JC.LINK_EMPL = E.LINK AND JC.LINK_VKR = D.LINK_VKR)
	)
	-----------------------------	

	EXEC dbo.BufferClear
	EXEC dbo.BufferPushTable '#faces', 'REP2NDFL', 'pers_link'

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

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

	Insert into #S_J_C_SHORT (LINK_FACE, PERS_LINK, link_empl, link_pays, link_vkr, link_ekr, typ_per, typ_oper, summa, link_inc, period_begin, date1, link_dep)
	Select 
		E.PERS_LINK, JC.PERS_LINK, JC.LINK_EMPL, P.LINK, link_vkr, ISNULL(JC.LINK_EKR,P.LINK_EKR), P.TYP_PER, P.OBJECT, summa, P.LINK_INC,
		period_begin = (case when @isPrevPreiod = 0 then JC.period_begin 
				else (Case 
						when JC.DATE_BEGIN < JC.period_begin and year(JC.DATE_BEGIN) = year(JC.period_begin) and d.code = 'DOCUMENTS_ADD_TABEL'
						then JC.DATE_BEGIN else JC.period_begin 
					end) 
				end),
		JC.DATE_BEGIN,
		JC.LINK_DEP
	from 
		dbo.CALCULATE_JURNAL JC 
		INNER JOIN dbo.NDFL_GroupTax() T ON JC.LINK_PAYS=T.LINK_PAYS
		LEFT JOIN dbo.EMPL E ON JC.LINK_EMPL = E.LINK
		LEFT JOIN dbo.PAYS P ON JC.LINK_PAYS = P.LINK
		LEFT JOIN (Select d.link, o.code from sdoc d inner join dbo.s_objects o on d.object = o.link) d on jc.LINK_DOC = d.link
	where
		(
				(@isPrevPreiod = 0 or ISNULL(d.code,'') <> 'DOCUMENTS_ADD_TABEL') and @nMonth >= month(JC.PERIOD_BEGIN) and @varKSnYear = year(JC.PERIOD_BEGIN)
				or 
				@isPrevPreiod = 1 and ISNULL(d.code,'') = 'DOCUMENTS_ADD_TABEL'
				and (@nMonth >= month(JC.DATE_BEGIN) or @nMonth >= month(JC.PERIOD_BEGIN) )
				and (@varKSnYear = year(JC.DATE_BEGIN) or @varKSnYear = year(JC.PERIOD_BEGIN) )

			)
		AND  
			(	-->>NEW
			E.PERS_LINK in (select PERS_LINK from #FACES )
			or
			JC.PERS_LINK in (select PERS_LINK from #FACES )
			)	
		AND JC.LINK_DEP = @DEP_LINK 
	union all --Удержания
	Select LINK_FACE, PERS_LINK, link_empl, link_pays, link_vkr, link_ekr, typ_per, typ_oper, summa, link_inc, period_begin, date1, link_dep
	from dbo.S_J_C_SHORT SJC 
		LEFT JOIN DICTIONARY_TYP_INCOMS DTI ON DTI.LINK = SJC.LINK_INC 
	where 
		SJC.LINK_DEP = @DEP_LINK
		and
		(
			SJC.LINK_FACE in (select PERS_LINK from #FACES )
			or
			SJC.PERS_LINK in (select PERS_LINK from #FACES )
		)
		and YEAR(SJC.PERIOD_BEGIN) = @varKSnYear
		and Month(SJC.PERIOD_BEGIN) <= @nMonth
		and TYP_OPER = 2

-----------------------------------------------------------
--Для обособленных подразделений
DECLARE @DATE DATETIME
SET @DATE = DBO.ConvertDMY2Date(1,@nMonth, @varKSnYear)
SET @DATE = DBO.DateEndOfMonth(@DATE)

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

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

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

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

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

	select distinct LINK_FACE, Y = year(PERIOD_BEGIN), M = month(PERIOD_BEGIN),  LINK_INC, LINK_VKR  
	into #spr_pays_kbk
	from 	#S_J_C_SHORT where TYP_OPER = 1
	

	CREATE TABLE #PAYS_0_tmp
	(
		ID INT IDENTITY,
		LINK_FACE INT,
		mes int, 
		LINK_INC INT, CODE_INC VARCHAR(4), SUMMA_INC NUMERIC(13,2),
		LINK_DED INT, CODE_DED VARCHAR(3), SUMMA_DED NUMERIC(13,2)
	)

	CREATE TABLE #PAYS_0
	(
		ID INT IDENTITY,
		LINK_FACE INT, 
		mes int, 
		LINK_INC INT, CODE_INC VARCHAR(4), SUMMA_INC NUMERIC(13,2),
		LINK_DED INT, CODE_DED VARCHAR(3), SUMMA_DED NUMERIC(13,2)
	)

	INSERT INTO #PAYS_0_tmp
	(LINK_FACE, mes, 
	LINK_INC, CODE_INC, SUMMA_INC,
	LINK_DED, CODE_DED, SUMMA_DED)
	SELECT 
		F.PERS_LINK,
		mes = MONTH(SJC.PERIOD_BEGIN),
		LINK_INC, ISNULL(DTI.SNAME,'0000'),
		SUM(SUMMA) AS SUMMA_INC,
		DTI.REF_DEDUCT AS LINK_DED, DTI.COD_DED,
		CAST(0 AS NUMERIC(20,2)) AS SUMMA_DED
	FROM 
		#S_J_C_SHORT SJC 
		LEFT JOIN dbo.DICTIONARY_TYP_INCOMS DTI ON DTI.LINK = SJC.LINK_INC
		INNER JOIN #FACES F ON SJC.LINK_FACE = F.PERS_LINK
	WHERE 
		SJC.TYP_OPER = 1
		AND
		YEAR(SJC.PERIOD_BEGIN) = @varKSnYear
		and
		Month(SJC.PERIOD_BEGIN) <= @nMonth
		AND
		ISNULL(SJC.PERS_LINK,0) = 0
		AND
		SJC.LINK_DEP = @DEP_LINK 
	GROUP BY 
		F.PERS_LINK, SJC.TYP_PER, SJC.PERIOD_BEGIN, LINK_INC, DTI.REF_DEDUCT, ISNULL(DTI.SNAME,'0000'), DTI.COD_DED

	---<< Добавление информации по внештатникам	
	union all 

	SELECT 
		F.PERS_LINK,
		mes = MONTH(SJC.PERIOD_BEGIN),
		LINK_INC, ISNULL(DTI.SNAME,'0000'),
		SUM(SUMMA) AS SUMMA_INC,
		DTI.REF_DEDUCT AS LINK_DED, DTI.COD_DED,
		CAST(0 AS NUMERIC(20,2)) AS SUMMA_DED
	FROM #S_J_C_SHORT SJC 	
		LEFT JOIN dbo.DICTIONARY_TYP_INCOMS DTI ON DTI.LINK = SJC.LINK_INC --AND DTI.SNAME <> '0000'
		INNER JOIN #FACES F ON SJC.PERS_LINK = F.PERS_LINK
	WHERE 	SJC.TYP_OPER = 1
		AND
		YEAR(SJC.PERIOD_BEGIN) = @varKSnYear
		and
		Month(SJC.PERIOD_BEGIN) <= @nMonth
		AND
		ISNULL(SJC.LINK_FACE,0) = 0
		AND
		SJC.LINK_DEP = @DEP_LINK
	GROUP BY 
		F.PERS_LINK, SJC.TYP_PER, SJC.PERIOD_BEGIN, LINK_INC, DTI.REF_DEDUCT, ISNULL(DTI.SNAME,'0000'), DTI.COD_DED
	ORDER BY 
		1, ISNULL(DTI.SNAME,'0000'), COD_DED


	INSERT INTO #PAYS_0
	Select LINK_FACE, mes, LINK_INC, CODE_INC, sum(SUMMA_INC), LINK_DED, CODE_DED, sum(SUMMA_DED)
	from #PAYS_0_tmp
	group by LINK_FACE, mes, LINK_INC, CODE_INC, LINK_DED, CODE_DED
	having Sum(SUMMA_INC) <> 0

	drop table #PAYS_0_tmp

	---->>
	--СКИДКИ
	SELECT D.LINK_FACE, D.mes, SUM(D.SUMMA) as SUMMA, D.REF_DED INTO #DED 
	FROM 
		dbo.SA_NDFL_MONTH_DED_ALL(@varKSnYear) D 
		inner join #spr_pays_kbk kbk on kbk.LINK_FACE = d.LINK_FACE and kbk.m = d.mes and kbk.link_inc = d.REF_INC and kbk.LINK_VKR = d.LINK_VKR
	where 
		kbk.y = @varKSnYear
		and kbk.m <= @nMonth
	GROUP BY 
		D.LINK_FACE, d.mes, d.REF_DED

	UPDATE #PAYS_0
	SET SUMMA_DED = 
		(SELECT SUM(SUMMA) FROM #DED D WHERE D.LINK_FACE = R.LINK_FACE AND D.REF_DED = R.LINK_DED AND D.mes = R.mes ) 
	FROM #PAYS_0 R 
	WHERE LINK_DED IS NOT NULL


	update #PAYS_0 
		Set CODE_DED = ''
		where ISNULL(SUMMA_DED,0) = 0


	CREATE TABLE #P0 (LINK_FACE INT, ID1 INT)

	--- 1

	CREATE TABLE #PAYS1(LINK_FACE INT, SM NUMERIC(11,2), MONTH_NUM INT)
	INSERT INTO #PAYS1
	SELECT LINK_FACE, SM, [MONTH]
	FROM dbo.NDFL_BASE_SUM_TAX_MONTH_ALL(@nMonth, @varKSnYear)

	---<< Добавление информации по внештатникам
	insert into #pays1

	SELECT 
		F.PERS_LINK,
		SUM(SUMMA) AS SUMMA_INC,
		Month(SJC.PERIOD_BEGIN)
	FROM 
		#S_J_C_SHORT SJC 
		INNER JOIN dbo.DICTIONARY_TYP_INCOMS DTI ON DTI.LINK = SJC.LINK_INC
		INNER JOIN #FACES F ON SJC.PERS_LINK = F.PERS_LINK
	WHERE 
		YEAR(SJC.PERIOD_BEGIN) = @varKSnYear
		and Month(SJC.PERIOD_BEGIN) <= @nMonth
		AND ISNULL(SJC.LINK_FACE,0) = 0
		AND SJC.LINK_DEP = @DEP_LINK 
	GROUP BY F.PERS_LINK, SJC.PERIOD_BEGIN

	---->>

	SELECT LINK_FACE, SUM(SM) AS SM
	INTO #PAYS_R
	FROM #PAYS1
	GROUP BY LINK_FACE

	INSERT INTO #PAYS1
	SELECT 
		EP.PERS_LINK, -SUM(SUMMA), MONTH(DATE_DED)
	FROM    
		dbo.empl EP 
		inner join SAL_DED_MONTH S ON (EP.LINK = S.LINK_EMPL AND YEAR(DATE_DED) = @varKSnYear and Month(DATE_DED) <= @nMonth AND [TYPE] = 2)
		INNER JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = EP.pers_link --Было: EP.LINK
	where 
		EP.DEP_LINK = @DEP_LINK	
	GROUP BY 
		EP.PERS_LINK, MONTH(DATE_DED)

	CREATE TABLE #PAYS3(ID INT IDENTITY, LINK_FACE INT, LINK_DED INT, CODE_DED VARCHAR(6), SUMMA NUMERIC(18,2), SUMMA_FAKT NUMERIC(18,2))
	--Стандартные и скидки на мат помощь
	--ПО СОТРУДНИКАМ
	INSERT INTO #PAYS3 (LINK_FACE, LINK_DED, CODE_DED, SUMMA, SUMMA_FAKT)
	SELECT 	
		EP.PERS_LINK, min(S.REF_DED), T.CODE, 
		CONVERT(NUMERIC(18,2), SUM((case when KOEF_VKR is not null then DTD.SUMMA * KOEF_VKR else DTD.SUMMA end) * ISNULL(S.KOL,0) )), 
		SUM(S.SUMMA) 
	FROM 
		dbo.empl EP 
		INNER JOIN SAL_DED_MONTH S ON (EP.LINK = S.LINK_EMPL AND YEAR(DATE_DED) = @varKSnYear and Month(DATE_DED) <= @nMonth AND TYPE = 1)
		INNER JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = EP.pers_link --Было: EP.LINK
		INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION T ON T.LINK = S.REF_DED 
		INNER JOIN dbo.Salary_deductions(@BEGIN_YEAR) DTD on DTD.REF_PAY = S.REF_DED
	where 
		T.NUMBER IN (	1, --Стандартные
						6 --скидки на мат помощь 
						)
		AND			
		EP.DEP_LINK = @DEP_LINK	and S.SUMMA <> 0
	GROUP BY 
		EP.PERS_LINK, T.CODE

	--ПО ДОГОВОРНИКАМ
	INSERT INTO #PAYS3 (LINK_FACE, LINK_DED, CODE_DED, SUMMA, SUMMA_FAKT)
	SELECT 	
		EP.PERS_LINK, min(S.REF_DED), T.CODE, 
		CONVERT(NUMERIC(18,2), SUM((case when KOEF_VKR is not null then DTD.SUMMA * KOEF_VKR else DTD.SUMMA end) * ISNULL(S.KOL,0) )), 
		SUM(S.SUMMA) 
	FROM 
		dbo.REESTR_DGH EP 
		INNER JOIN SAL_DED_MONTH S ON (EP.LINK = S.LINK_DGH AND YEAR(DATE_DED) = @varKSnYear and Month(DATE_DED) <= @nMonth AND S.[TYPE] = 1)
		INNER JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = EP.pers_link --Было: EP.LINK
		INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION T ON T.LINK = S.REF_DED 
		INNER JOIN dbo.Salary_deductions(@BEGIN_YEAR) DTD on DTD.REF_PAY = S.REF_DED
	where 
		T.NUMBER IN (	1, --Стандартные
						6 --скидки на мат помощь 
						)
		AND			
		EP.DEP_LINK = @DEP_LINK	and S.SUMMA <> 0
	GROUP BY 
		EP.PERS_LINK, T.CODE

	--UPDATE #PAYS3
	--SET
	--	SUMMA = (Select sum(SUM_DED) from dbo.TAX_DEDUCTIONS TD where TD.LINK_DEP = @DEP_LINK AND TD.link_person = #PAYS3.LINK_FACE and TD.LINK_DICTION = #PAYS3.LINK_DED and TD.[YEAR] = @varKSnYear and TD.Month1 <= @nMonth)	
	--where
	--	exists (Select * from dbo.TAX_DEDUCTIONS TD where TD.LINK_DEP = @DEP_LINK AND TD.link_person = #PAYS3.LINK_FACE and TD.LINK_DICTION = #PAYS3.LINK_DED and TD.[YEAR] = @varKSnYear and TD.Month1 <= @nMonth)	

	UPDATE #PAYS3
	SET
		SUMMA = ISNULL(SUMMA_FAKT,0)
	where
		ISNULL(SUMMA,0) = 0

	--Прочие вычеты (имущественные, добровольное пенс страхование и пр.)
	INSERT INTO #PAYS3 (LINK_FACE, LINK_DED, CODE_DED, SUMMA, SUMMA_FAKT)
	SELECT 	
		EP.PERS_LINK, min(S.REF_DED), T.CODE, SUM(S.SUMMA), SUM(S.SUMMA) 
	FROM 
		dbo.EMPL EP 
		INNER JOIN SAL_DED_MONTH S ON (EP.LINK = S.LINK_EMPL AND YEAR(DATE_DED) = @varKSnYear and Month(DATE_DED) <= @nMonth AND TYPE = 1)
		INNER JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = EP.pers_link --Было: EP.LINK
		INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION T ON T.LINK = S.REF_DED 
	where 
		T.NUMBER NOT IN (	1, --Стандартные
							6 --скидки на мат помощь 
							)
		AND			
		EP.DEP_LINK = @DEP_LINK	and S.SUMMA <> 0
	GROUP BY 
		EP.PERS_LINK, T.CODE

	-- Общая сумма имущ. вычетов
	update #RES0
	Set siv = ISNULL( (Select sum(P3.SUMMA_FAKT) from #PAYS3 P3 where R.LINK_FACE = P3.LINK_FACE and P3.LINK_DED IN (SELECT DISTINCT LINK_DICTION FROM TAX_DEDUCTIONS td WHERE TD.LINK_DEP = @DEP_LINK AND TD.[YEAR] = @varKSnYear and TD.Month1 <= @nMonth)),0),
		ssv = ISNULL( (Select sum(P3.SUMMA_FAKT) from #PAYS3 P3 where R.LINK_FACE = P3.LINK_FACE and P3.LINK_DED NOT IN (SELECT DISTINCT LINK_DICTION FROM TAX_DEDUCTIONS td WHERE TD.LINK_DEP = @DEP_LINK AND TD.[YEAR] = @varKSnYear and TD.Month1 <= @nMonth)),0)		

	from #RES0 R
	--
	DELETE FROM #P0

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV1 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV1 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV2 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV2 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV3 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV3 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R

		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV4 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV4 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R

		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV5 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV5 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R

		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV6 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV6 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R

		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV7 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV7 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R

		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV8 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV8 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV9 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV9 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV10 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV10 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV11 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV11 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV12 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV12 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END


	UPDATE #RES0 SET OSD13 = (SELECT top 1 SM FROM #PAYS_R PR WHERE PR.LINK_FACE = R.LINK_FACE) FROM #RES0 R

	----
	UPDATE #RES0 SET SDO13 = OSD13 - ISNULL(SK.SUM_SK, 0.00)
			- ISNULL(SSV1,0.00) - ISNULL(SSV2,0.00) - ISNULL(SSV3,0.00) - ISNULL(SSV4,0.00)
			- ISNULL(SSV5,0.00) - ISNULL(SSV6,0.00) - ISNULL(SSV7,0.00) - ISNULL(SSV8,0.00)
			- ISNULL(SSV9,0.00) - ISNULL(SSV10,0.00) - ISNULL(SSV11,0.00) - ISNULL(SSV12,0.00)
	from #RES0 R LEFT JOIN (Select LINK_FACE, SUM_SK= SUM(SUMMA_DED) from #PAYS_0 GROUP BY LINK_FACE) SK ON R.LINK_FACE = SK.LINK_FACE

	-----
	UPDATE #RES0 SET SDO13 = 0 WHERE SDO13 < 0


	CREATE TABLE #NDFL_TAX(LINK_TAX INT)
	INSERT INTO #NDFL_TAX
	SELECT LINK FROM PAYS P WHERE P.OBJECT = 2 AND P.WAY_CALC = 4

	Create table #NDLF13_tmp (LINK int, SUMMA numeric(18,2))
	Create table #NDLF13 (LINK int, SUMMA numeric(18,2))

	insert into  #NDLF13_tmp (LINK, SUMMA)
	SELECT B.LINK AS LINK, SUM(SUMMA) AS SUMMA
	FROM 
		#S_J_C_Short SJC 
		INNER JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = SJC.LINK_FACE --Было: EP.LINK
		INNER JOIN #NDFL_TAX T ON SJC.LINK_PAYS = T.LINK_TAX  
	WHERE 
		YEAR(PERIOD_BEGIN) = @varKSnYear 
		and month(PERIOD_BEGIN) <= @nMonth
		and sjc.LINK_DEP = @DEP_LINK	
	GROUP BY 
		B.LINK
	---<< Добавление информации по внештатникам
	union all
	SELECT B.LINK AS LINK, SUM(SUMMA) AS SUMMA
	FROM #S_J_C_Short SJC 
		INNER JOIN #NDFL_TAX T ON SJC.LINK_PAYS = T.LINK_TAX  
		INNER JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = SJC.PERS_LINK --Было: EP.LINK
	WHERE YEAR(PERIOD_BEGIN) = @varKSnYear 
		and month(PERIOD_BEGIN) <= @nMonth
		and ISNULL(SJC.LINK_FACE,0) = 0
		and sjc.LINK_DEP = @DEP_LINK	
	GROUP BY B.LINK

	insert into #NDLF13 (LINK, SUMMA)
	Select LINK, Sum(SUMMA) from #NDLF13_tmp group by LINK
	
	drop table #NDLF13_tmp
	--->>

	UPDATE #RES0 SET NALOGU13 = ISNULL((SELECT SUM(SUMMA) FROM #NDLF13 N WHERE N.LINK = R.LINK_FACE), 0) FROM #RES0 R
	UPDATE #RES0 SET NALOGN13 = SDO13 * (CASE WHEN STATUS = '1' THEN 
		( SELECT  top 1 [PERCENT] / 100 FROM DICTIONARY_RANGE R inner join #NDFL_TAX T on R.LINK_PAYS = T.LINK_TAX WHERE TARIF = 1)
								ELSE 0.30 END)
	--Перечисленная сумма по всем за период
	DECLARE @SUMMA_PLAT_ALL NUMERIC(18,2)
		
	IF @nCHECK_S = 0
		BEGIN
			SET @SUMMA_PLAT_ALL =  @nSumm_For_Check 	
		END
	ELSE
		BEGIN 
			EXEC dbo.SA_NDFL_PLAT @BEGIN_YEAR, @DATE, @DEP_LINK, @SUMMA_PLAT_ALL OUT
		END 
	--Начисленная сумма по всем за период
	DECLARE @SUMMA_NACH_ALL NUMERIC(18,2)
	EXEC dbo.SA_NDFL_NACHISL @BEGIN_YEAR, @DATE, @DEP_LINK, @SUMMA_NACH_ALL OUT
	--Перечисленная за сотрудника	
	UPDATE #RES0 SET NALOG13S = CONVERT(NUMERIC(18,0), ISNULL( @SUMMA_PLAT_ALL * CASE WHEN @SUMMA_NACH_ALL > 0 THEN (NALOGU13	/ @SUMMA_NACH_ALL) ELSE 0 END, 0))
	UPDATE #RES0 SET NALOG13S = CASE WHEN NALOG13S > NALOGU13 THEN NALOGU13 ELSE NALOG13S END

	UPDATE #RES0 SET NOM_SPR = ID + @varKSnFirstNum - 1
	
	---Учет переплаты/недоплаты НДФЛ из остатков с прошлого года
	UPDATE A SET 
		S_5_6 = (CASE WHEN R.NDFL > 0 THEN R.NDFL ELSE 0 END),
		S_5_7 = (CASE WHEN R.NDFL <= 0 THEN - R.NDFL ELSE 0 END)
	FROM
		#RES0 A INNER JOIN 
		(SELECT E.PERS_LINK, NDFL = SUM(SR.NDFL) FROM dbo.SAL_REMAIN SR INNER JOIN dbo.EMPL E ON E.LINK = SR.LINK_EMPL WHERE SR.YEAR_SAL = @varKSnYear GROUP BY E.PERS_LINK) R 
			ON R.PERS_LINK = A.LINK_FACE
	--	
	UPDATE #RES0 SET DOLG_NP = CASE WHEN NALOGN13 - NALOGU13 > 0 THEN NALOGN13 - NALOGU13 ELSE 0 END - ISNULL(S_5_6,0)
	UPDATE #RES0 SET DOLG_NA = CASE WHEN NALOGU13 - NALOGN13 > 0 THEN NALOGU13 - NALOGN13 ELSE 0 END - ISNULL(S_5_7,0)

	--^^^^^^^^^Распределение налога по КБК^^^^^^^^^^
	create table  #PAYS_NDFL (ID INT IDENTITY, LINK_FACE int, LINK_PAYS int, kbk_code varchar(20), SUMMA numeric(18,2))

	INSERT INTO #PAYS_NDFL (LINK_FACE, LINK_PAYS, kbk_code, SUMMA)
	SELECT LINK_FACE, SJC.LINK_PAYS, left(kbk.CODE,20), sum(SJC.SUMMA)
	FROM #S_J_C_SHORT SJC inner join dbo.SAL_SFIN kbk on SJC.LINK_VKR = kbk.LINK
	WHERE 
			YEAR(CASE WHEN SJC.TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN SJC.TYP_PER = 2 THEN SJC.DATE1 END) = @varKSnYear
		and
			month(CASE WHEN SJC.TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN SJC.TYP_PER = 2 THEN SJC.DATE1 END) <= @nMonth
		AND	ISNULL(SJC.PERS_LINK,0) = 0
		AND	SJC.LINK_PAYS IN (Select LINK_TAX from #NDFL_TAX)
	GROUP BY 
		LINK_FACE, LINK_PAYS, kbk.CODE

	union all ---<< Добавление информации по внештатникам	

	SELECT  PERS_LINK, SJC.LINK_PAYS, left(kbk.CODE,20), sum(SJC.SUMMA)
	FROM #S_J_C_SHORT SJC inner join dbo.SAL_SFIN kbk on SJC.LINK_VKR = kbk.LINK
	WHERE 
			YEAR(CASE WHEN SJC.TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN SJC.TYP_PER = 2 THEN SJC.DATE1 END) = @varKSnYear
		and
			month(CASE WHEN SJC.TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN SJC.TYP_PER = 2 THEN SJC.DATE1 END) <= @nMonth
		AND	ISNULL(SJC.LINK_FACE,0) = 0
		AND	SJC.LINK_PAYS IN (Select LINK_TAX from #NDFL_TAX)

	GROUP BY 
		PERS_LINK, LINK_PAYS, kbk.CODE
	ORDER BY 
		1, 2, 3



	DELETE FROM #P0

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS_NDFL GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET kbkcode1 = (SELECT top 1 P00.kbk_code FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET kbksum1 = (SELECT top 1 P00.SUMMA FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS_NDFL WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS_NDFL GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET kbkcode2 = (SELECT top 1 P00.kbk_code FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET kbksum2 = (SELECT top 1 P00.SUMMA FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS_NDFL WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS_NDFL GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET kbkcode3 = (SELECT top 1 P00.kbk_code FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET kbksum3 = (SELECT top 1 P00.SUMMA FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS_NDFL WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS_NDFL GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET kbkcode4 = (SELECT top 1 P00.kbk_code FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET kbksum4 = (SELECT top 1 P00.SUMMA FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS_NDFL WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

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


	DECLARE @varKSCNT INT

	SELECT @varKSCNT  = COUNT(*) FROM #RES0

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


	CREATE TABLE #LOG(
		LINK INT, ERR INT IDENTITY, 
		NUMBER VARCHAR(20), DETAIL VARCHAR(254) )

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

	SELECT 
		@varKScInn = INN, @varKScKPP = KPP,
		@varKSFULL_NAME = FULL_NAME, 
		@varKSNALOG = NALOG, @varKSOKATO = Replace(OKATO,' ',''), @varKSOKTMO = Replace(OKTMO,' ',''),
		@varKSPHONE = PHONE, 
		@varKSGLBUH  = GLBUH
	FROM #DEP
	
	IF LEN(@varKScInn) = 0
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указан ИНН организации')
	ELSE BEGIN
		IF LEN(@varKScInn) <> 10 BEGIN
			INSERT INTO #LOG (LINK, NUMBER, DETAIL)
			VALUES (0, 'Общие ошибки', 'Неверный ИНН организации')
		END
		ELSE BEGIN
			EXEC SD_CHECK_INN @varKScInn, @varKSRESULT OUTPUT, 0
			IF @varKSRESULT = -1
				INSERT INTO #LOG (LINK, NUMBER, DETAIL)
				VALUES (0, 'Общие ошибки', 'Неверный ИНН организации')
		END
	END

	
	IF LEN(@varKScKPP) = 0
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указан КПП организации')
	ELSE BEGIN
		IF LEN(@varKScKPP) <>9  BEGIN
			INSERT INTO #LOG (LINK, NUMBER, DETAIL)
			VALUES (0, 'Общие ошибки', 'КПП организации должен быть 9 знаков')
		END
	END

	IF LEN(@varKSNALOG) = 0 
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указан код ИФНС')
	ELSE BEGIN
		IF LEN(@varKSNALOG) <> 4  
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Код ИФНС должен быть 4 знака')

	END

	IF LEN(@varKSFULL_NAME) = 0 
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указано наименование организации-отправителя')



	IF LEN(@varKSOKATO) = 0  
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)		VALUES (0, 'Общие ошибки', 'Не указан код ОКТМО')	

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT E.PERS_LINK, '', 'Не указан код ОКТМО у обособленного подразделения, в котором находится сотрудник ' + RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.'
	FROM
		#S_OBOSOB SO INNER JOIN #E_SUBDIV ES ON SO.SUBDIV_LINK = ES.SUBDIV_LINK
		INNER JOIN DBO.EMPL E ON E.LINK = ES.EMPL_LINK
		INNER JOIN #FACES F ON F.PERS_LINK = E.PERS_LINK
		INNER JOIN DBO.PERSON P ON P.LINK = E.PERS_LINK
	WHERE
		LEN(O_OKATO) = 0 
		
	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT E.PERS_LINK, '', 'Не указан либо указан неверно код KPP у обособленного подразделения, в котором находится сотрудник ' + RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.'
	FROM
		#S_OBOSOB SO INNER JOIN #E_SUBDIV ES ON SO.SUBDIV_LINK = ES.SUBDIV_LINK
		INNER JOIN DBO.EMPL E ON E.LINK = ES.EMPL_LINK
		INNER JOIN #FACES F ON F.PERS_LINK = E.PERS_LINK
		INNER JOIN DBO.PERSON P ON P.LINK = E.PERS_LINK		
	WHERE
		LEN(O_KPP) <> 9

	IF LEN(@varKSPHONE) = 0 
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указан контактный телефон')

	IF LEN(@varKSGLBUH) = 0 
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указано ответственное лицо')

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT DISTINCT
		0, 'Общие ошибки', 'В настройках по зарплате не указан вычет с кодом ' + LTRIM(RTRIM(ISNULL(D.SNAME,'')))
	FROM
		dbo.TAX_DEDUCTIONS TD INNER JOIN DBO.DICTIONARY_TYP_DEDUCTION D ON D.LINK = TD.LINK_DICTION
	WHERE
		TD.[YEAR] = @varKSnYear and TD.Month1 <= @nMonth
		AND
		TD.LINK_DICTION NOT IN (SELECT REF_PAY FROM dbo.Salary_deductions(@BEGIN_YEAR))

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '', 'Не указана фамилия' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE LEN(ISNULL(FM, '')) = 0 AND OSD13 > 0 

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '', 'Не указано имя' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE LEN(ISNULL(IM, '')) = 0 AND OSD13 > 0 

/*	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указано отчество' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE LEN(ISNULL(Ot, '')) = 0 AND OSD13 > 0 
*/
/*	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT NOM_SPR, NOM_SPR,  'Неверный ИНН сотрудника' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE dbo.IsValidINNFiz(INNFIZ) = 0
*/
	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указан статус работника' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE STATUS = '' AND OSD13 > 0 

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указано гражданство' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE GRAZD IS NULL AND OSD13 > 0 
/*
	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT NOM_SPR, NOM_SPR,  'Не указан ИНН' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE ISNULL(INNFIZ, '') = ''
*/
	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указан ИНН либо документ, удостоверяющий личность' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE ISNULL(INNFIZ, '') = '' and KDVD IS NULL AND OSD13 > 0 

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указан ИНН либо номер документа' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE ISNULL(INNFIZ, '') = '' AND ISNULL(SERNOM, '') = '' AND OSD13 > 0 

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указан ИНН либо дата рождения'  + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE ISNULL(INNFIZ, '') = '' AND BIRTH IS NULL AND OSD13 > 0 

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указан адрес'  + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE ISNULL(INNFIZ, '') = '' AND link_adr IS NULL AND OSD13 > 0 

	SET @varKSCNT = 0
	SELECT @varKSCNT = COUNT(DISTINCT LINK) FROM #LOG WHERE LINK > 0

	UPDATE #RES0
	SET ERR = 1
	WHERE LINK_FACE IN (SELECT LINK_FACE FROM #LOG)

	/*заявленные имущественные вычеты*/
	Select LINK_PERSON, NUM_REF, DATE_REF, IFNS_CODE  into #td  from dbo.TAX_DEDUCTIONS td
	where TD.LINK_DEP = @DEP_LINK AND link = (select min(link) from dbo.TAX_DEDUCTIONS td1 where TD1.LINK_DEP = @DEP_LINK AND td1.LINK_PERSON =  td.LINK_PERSON and td1.[YEAR] = @varKSnYear and td1.Month1 <= @nMonth)

	declare @KBK_DEFAULT varchar(254)
	Set @KBK_DEFAULT = (select Top 1 CODE_KBK from dbo.sd_empl where LINK_KBK > 0)

	UPDATE #RES0 Set kbkcode1 = @KBK_DEFAULT, kbksum1 = 0 where ISNULL(kbksum1,0) = 0

	/*Контроль имущественных вычетов*/
	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Указаны не все данные в уведомлении на имущественный вычет'  + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 inner join  #td on #RES0.LINK_FACE = #td.LINK_PERSON 
	WHERE rtrim(ltrim(ISNULL(NUM_REF,''))) = '' or rtrim(ltrim(ISNULL(IFNS_CODE,''))) = '' or DATE_REF is null AND OSD13 > 0 

	CREATE TABLE #RES_OUT (ID INT,LINK_FACE INT,mes INT,LINK_INC INT,CODE_INC VARCHAR(4),SUMMA_INC NUMERIC(18,2),LINK_DED INT,CODE_DED VARCHAR(3),SUMMA_DED NUMERIC(18,2),ID2 INT)

	INSERT INTO #RES_OUT (ID, LINK_FACE, mes, LINK_INC, CODE_INC, SUMMA_INC, LINK_DED, CODE_DED, SUMMA_DED, ID2)
	SELECT ID, LINK_FACE, mes, LINK_INC, CODE_INC, SUMMA_INC, LINK_DED, CODE_DED, SUMMA_DED, ID2 = 0 
	FROM #PAYS_0 
	ORDER BY LINK_FACE, MES, CODE_INC
	
	---СОРТИРОВКА
	CREATE TABLE #RES_OUT_ORD (NUM_PP INT IDENTITY(1,1), ID INT, LINK_FACE INT)
	INSERT INTO #RES_OUT_ORD (ID, LINK_FACE)
	SELECT ID, LINK_FACE FROM #PAYS_0 ORDER BY LINK_FACE, MES, CODE_INC
	--
	CREATE TABLE #RES_OUT_ORD2 (LINK_FACE INT, MIN_NUM INT)
	INSERT INTO #RES_OUT_ORD2 (LINK_FACE, MIN_NUM)
	SELECT LINK_FACE, MIN(NUM_PP) FROM #RES_OUT_ORD GROUP BY LINK_FACE
	---СОРТИРОВКА ДЛЯ КАЖДОГО ФИЗЛИЦА
	UPDATE R
	SET R.ID2 = O.NUM_PP - O2.MIN_NUM + 1
	FROM 
		#RES_OUT R 
		INNER JOIN #RES_OUT_ORD O ON O.ID = R.ID
		INNER JOIN #RES_OUT_ORD2 O2 ON O2.LINK_FACE = R.LINK_FACE

	CREATE TABLE #ORDERS (ID int)
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = 'ALTER TABLE #ORDERS ADD [NOM_SPR] INT IDENTITY(' + RTRIM(str(ISNULL(@varKSnFirstNum,1))) + ',1)'
	EXEC(@SQL)

	INSERT INTO #ORDERS (ID) 
	SELECT DISTINCT ID 
	FROM #RES0 
	WHERE LINK_FACE IN ( Select DISTINCT LINK_FACE from #RES_OUT where [ID2]%2 = 1 )
			--AND ISNULL(OSD13,0) > 0
	ORDER BY ID

	--UPDATE #ORDERS SET NOM_SPR = NOM_SPR + @varKSnFirstNum - 1

	--- общее количество документов
	UPDATE #DEP SET DOCCOUNT = ISNULL((SELECT MAX(NOM_SPR) FROM #ORDERS),0)

	-------------------
	SELECT 
		R.ID, O.NOM_SPR, R.LINK_FACE, R.SEX, R.INNFIZ, R.NUMB_SERT, R.STATUS, 
		R.FIO, R.FM, R.IM, R.OT, R.KDVD, R.SERNOM, R.BIRTH, R.GRAZD, R.KSTR, 
		R.LINK_ADR, R.IND_ADR, R.REGION, R.RAION, R.GOROD, R.NASEL, R.STREET, 
		R.HOUSE, R.KORP, R.FLAT, R.KSTR_ino, R.Adr_ino, 
		R.ksv1, R.ssv1, R.ksv2, R.ssv2, R.ksv3, R.ssv3, R.ksv4, R.ssv4, R.ksv5, R.ssv5, R.ksv6, R.ssv6, 
		R.ksv7, R.ssv7, R.ksv8, R.ssv8, R.ksv9, R.ssv9, R.ksv10, R.ssv10, R.ksv11, R.ssv11, R.ksv12, R.ssv12, 
		R.ssv, R.siv, R.osd13, R.sdo13, R.nalogn13, R.nalogu13, R.nalog13s, R.err, R.S_5_6, R.S_5_7, R.dolg_np, R.dolg_na, 
		R.kbkcode1, R.kbkcode2, R.kbkcode3, R.kbkcode4, R.kbksum1, R.kbksum2, R.kbksum3, R.kbksum4, 
		R.VIFNSPL, R.ZSummPL, R.UdSumPL, R.VzkIFNS, 
		ndoc_td = NUM_REF,
		ddoc_td = DATE_REF,
		nalog	= @varKSNALOG,
		KPP1 = ISNULL(R.O_KPP,@varKScKPP),
		OKATO1 = replace(ISNULL(R.O_OKATO,@varKSOKATO),' ',''),
		OKATO2 = (Case when ISNULL(kbksum2,0) <> 0 then @varKSOKATO else '' end),
		OKATO3 = (Case when ISNULL(kbksum3,0) <> 0 then @varKSOKATO else '' end),
		OKATO4 = (Case when ISNULL(kbksum4,0) <> 0 then @varKSOKATO else '' end),
		OKTMO1 = replace(ISNULL(R.O_OKATO,@varKSOKTMO),' ',''),
		OKTMO2 = (Case when ISNULL(kbksum2,0) <> 0 then @varKSOKTMO else '' end),
		OKTMO3 = (Case when ISNULL(kbksum3,0) <> 0 then @varKSOKTMO else '' end),
		OKTMO4 = (Case when ISNULL(kbksum4,0) <> 0 then @varKSOKTMO else '' end),
		T.M1, T.CINC1, T.SINC1, T.CDED1, T.SDED1, T.M2, T.CINC2, T.SINC2, T.CDED2, T.SDED2,
		#td.LINK_PERSON, #td.NUM_REF, #td.DATE_REF, #td.IFNS_CODE
	FROM #RES0 R 
		INNER JOIN #ORDERS O ON O.ID = R.ID
		INNER JOIN ( 
			Select	T1.LINK_FACE, M1= T1.MES, CINC1= T1.CODE_INC, SINC1= T1.SUMMA_INC, CDED1= T1.CODE_DED, SDED1= T1.SUMMA_DED, M2= T2.MES, CINC2= T2.CODE_INC, SINC2= T2.SUMMA_INC, CDED2= T2.CODE_DED, SDED2= T2.SUMMA_DED
			from	(Select * from #RES_OUT where [ID2]%2 = 1) T1 left join (Select * from #RES_OUT where [ID2]%2 = 0) T2 on T1.link_FACE = T2.LINK_FACE AND T1.[ID2] = (T2.[ID2]-1)
		) T on R.LINK_FACE = T.LINK_FACE
		left join  #td on R.LINK_FACE = #td.LINK_PERSON
	--where OSD13 > 0 
	ORDER BY O.NOM_SPR, T.M1, T.CINC1, T.M2, T.CINC2

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

	UPDATE L SET
		NUMBER = O.NOM_SPR
	FROM 
		#LOG L
		INNER JOIN #RES0 R ON L.LINK = R.LINK_FACE
		INNER JOIN #ORDERS O ON O.ID = R.ID
	
	SELECT * FROM #LOG ORDER BY LINK, ERR
	---
	EXEC dbo.BufferClear

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



GO


GRANT EXECUTE ON dbo.[SD_REP_2NDFL] TO PUBLIC

GO



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

GO

CREATE PROCEDURE dbo.SS_REP_CARD_NDFL
	@cYear varchar(4),
	@nMonth varchar (2) ,			
	@nFirstNum varchar (10) = '',
	@LINK_EMPL int = NULL,  
	@LINK_PERS int = NULL,
	@nCheck1 INT = 0 , 
	@nSum1 numeric(18,2) = NULL, /*Перечисленная сумма НДФЛ за январь*/
	@nSum2 numeric(18,2) = NULL,/*Перечисленная сумма НДФЛ за февраль*/
	@nSum3 numeric(18,2) = NULL,/*Перечисленная сумма НДФЛ за март*/
	@nSum4 numeric(18,2) = NULL, /*Перечисленная сумма НДФЛ за апрель*/
	@nSum5 numeric(18,2) = NULL,/*Перечисленная сумма НДФЛ за май*/
	@nSum6 numeric(18,2) = NULL,/*Перечисленная сумма НДФЛ за июнь*/
	@nSum7 numeric(18,2) = NULL,/*Перечисленная сумма НДФЛ за июль*/
	@nSum8 numeric(18,2) = NULL,/*Перечисленная сумма НДФЛ за август*/
	@nSum9 numeric(18,2) = NULL,/*Перечисленная сумма НДФЛ за сентябрь*/
	@nSum10 numeric(18,2) = NULL,/*Перечисленная сумма НДФЛ за октябрь*/
	@nSum11 numeric(18,2) = NULL,/*Перечисленная сумма НДФЛ за ноябрь*/
	@nSum12 numeric(18,2) = NULL/*Перечисленная сумма НДФЛ за декабрь*/
AS BEGIN

SET NOCOUNT ON
 
	Set @nMonth = (case when len(@nMonth)<2 then '0'+@nMonth  else @nMonth  end)

	DECLARE @varKSnYear INT
	SET @varKSnYear = CAST(@cYear AS INT)

	DECLARE @BEGIN_YEAR DATETIME
	SET @BEGIN_YEAR = dbo.ConvertDMY2Date(1,1,@varKSnYear)
	---------------------------------
	--определим последний день в месяце
	declare @eDay varchar (2)
	set @eDay = (select day(max(d.date1))  from dbo.days_month(@nMonth,@cYear)d)
/*	print @eDay*/

	
	DECLARE @PRES_DATE DATETIME,
			@PRESENT_DATE varchar (10) 			
	SET @PRES_DATE = dbo.ConvertDMY2Date(@eDay,@nMonth,@varKSnYear)
	SET @PRESENT_DATE = (@cYear + @nMonth + @eDay )

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output

	SELECT * INTO #DICT_TYP_INCOMS FROM dbo.DICTIONARY_TYP_INCOMS
	SELECT * INTO #Salary_deductions FROM dbo.Salary_deductions(@PRESENT_DATE)	

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

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

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

	if isnull(@LINK_EMPL,0) = 0
		set @LINK_EMPL =  (SELECT TOP 1 LINK FROM dbo.SD_EMPL WHERE PERS_LINK = @LINK_PERS AND STATUS_EMPL IN (1,3) AND ISNULL(DATE_END,@BEGIN_YEAR) >= @BEGIN_YEAR AND DEP_LINK = @DEP_LINK )

	if isnull(@LINK_PERS,0)= 0
		set @LINK_PERS =  (SELECT TOP 1 PERS_LINK FROM dbo.EMPL WHERE LINK = @LINK_EMPL)


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

	--Все сотрудники в данной организации с заданным @LINK_PERS
	CREATE TABLE #EMPLS (LINK INT, LINK_PERS INT)

	INSERT INTO #EMPLS(LINK, LINK_PERS)
	SELECT distinct LINK, @LINK_PERS FROM dbo.empl WHERE PERS_LINK = @LINK_PERS AND DEP_LINK = @DEP_LINK

	-----------------------------
	delete from dbo.SAL_DED_MONTH
	where 
	YEAR(DATE_DED) = @varKSnYear
	AND
	Month(DATE_DED) <= @nMonth
	AND
	LINK_EMPL IN (Select EM.LINK from #EMPLS EM)
	AND
	LINK IN 
	(
		select D.LINK 
		from dbo.SAL_DED_MONTH D inner join dbo.empl E on D.link_empl = E.link
		where YEAR(D.DATE_DED) = @varKSnYear AND Month(D.DATE_DED) <= @nMonth
		and not exists (Select * from dbo.CALCULATE_JURNAL JC where YEAR(JC.PERIOD_BEGIN) = @varKSnYear AND Month(JC.PERIOD_BEGIN) <= @nMonth AND JC.LINK_EMPL = E.LINK AND JC.LINK_VKR = D.LINK_VKR)
	)
	-----------------------------	

	EXEC dbo.BufferClear
	EXEC dbo.BufferPushTable '#EMPLS', 'REP2NDFL', 'LINK_PERS'

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

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

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

			)
		AND  
			(	-->>NEW
			E.PERS_LINK = @LINK_PERS
			or
			JC.PERS_LINK = @LINK_PERS
			)	
		AND JC.LINK_DEP = @DEP_LINK 
	union all --Удержания
	Select LINK_FACE, PERS_LINK, link_empl, link_pays, link_vkr, link_ekr, typ_per, typ_oper, summa, link_inc,
			CODE_INC = CONVERT(VARCHAR(5), (SELECT top 1 DA.VALUE FROM DICTION_APP DA WHERE DA.LINK_UP = sjc.LINK_INC AND 
							        da.OBJECT =(SELECT top 1 LINK FROM S_OBJECTS WHERE CODE = 'COLUMN_CODE_T_INC'))),
			 period_begin, period_end, date1, link_dep
	from dbo.S_J_C_SHORT SJC 
		LEFT JOIN #DICT_TYP_INCOMS DTI ON DTI.LINK = SJC.LINK_INC 
	where 
		SJC.LINK_DEP = @DEP_LINK
		and
		(
			SJC.LINK_FACE = @LINK_PERS
			or
			SJC.PERS_LINK = @LINK_PERS
		)
		and YEAR(SJC.PERIOD_BEGIN) = @varKSnYear
		and Month(SJC.PERIOD_BEGIN) <= @nMonth
		and TYP_OPER = 2

--select * from SDOC where link = SJC.link_doc
-----------------------------------------------------------
--Для обособленных подразделений
DECLARE @DATE DATETIME
SET @DATE = DBO.ConvertDMY2Date(1,@nMonth, @varKSnYear)
SET @DATE = DBO.DateEndOfMonth(@DATE)

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

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

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

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

	SELECT 	distinct 
		P.SEX, P.INN, /*P.IFNS,*/ P.INSUR_NUM, 
		CASE 
			WHEN P.RESIDENT  IS NULL THEN ''
			WHEN P.RESIDENT = 1 THEN '1'
			WHEN P.RESIDENT = 0 THEN '2'
		END,
		RTRIM(P.FM) + ',' + RTRIM(P.IM) + ',' + RTRIM(P.OT),
		RTRIM(P.FM), RTRIM(P.IM), RTRIM(P.OT),
		[NMD] = (SELECT TOP 1 NAME FROM FACE_DOCUMENT WHERE LINK = P.DOC_LINK),
		[KDVD] = (SELECT TOP 1 CODE FROM FACE_DOCUMENT WHERE LINK = P.DOC_LINK),
		P.DOC_NUM,
		P.BIRTHDATE,
		GRAZD= (SELECT TOP 1 CODE FROM CITIZENSHIP WHERE LINK = P.CITIZ_LINK),
		KSTR= (case when (SELECT TOP 1 CODE FROM CITIZENSHIP WHERE LINK = P.CITIZ_LINK) = '1' then '643' else '' END),
		ADR.LINK_ADDR,
		ADR.IND_ADR,
		ADR.REGION,
		ADR.RAION,
		ADR.GOROD,
		ADR.NASEL,
		ADR.STREET,
		ADR.HOUSE,
		ADR.KORP,
		ADR.FLAT,
		KSTR_ino = '',
		Adr_ino = '',
		isnull(PO.O_OKATO, '') ,
		isnull(PO.O_OKTMO, ''),
		isnull(PO.O_KPP, '')
	FROM 
		dbo.PERSON P
		LEFT OUTER JOIN dbo.NDFL_GET_ADDRESS() ADR ON P.LINK = ADR.LINK_FACE
		LEFT JOIN #P_OBOSOB PO ON 1=1
	WHERE
		P.LINK = @LINK_PERS		
		
	ORDER BY 
		RTRIM(P.FM) + ',' + RTRIM(P.IM) + ',' + RTRIM(P.OT)
		

			
	UPDATE #PERSON SET NOM_SPR = @nFirstNum 

	select distinct LINK_FACE, Y = year(PERIOD_BEGIN), M = month(PERIOD_BEGIN),  LINK_INC, LINK_VKR  
	into #spr_pays_kbk
	from 	#S_J_C_SHORT where TYP_OPER = 1


	---->>

	SELECT D.LINK_FACE, D.mes, SUM(D.SUMMA) as SUMMA, D.REF_DED 
	INTO #DED 
	FROM 
		dbo.SA_NDFL_MONTH_DED_ALL(@varKSnYear) D 
		inner join #spr_pays_kbk kbk on kbk.LINK_FACE = d.LINK_FACE and kbk.m = d.mes and kbk.link_inc = d.REF_INC and kbk.LINK_VKR = d.LINK_VKR
	where 
		kbk.y = @varKSnYear
		and kbk.m <= @nMonth
	GROUP BY 
		D.LINK_FACE, d.mes, d.REF_DED
		
	

	-- выборка заявленных вычетов по сотрудникам 
	---------------------------------
	CREATE  TABLE  #RES_VICHET (LINK INT, LINK_EMPL INT, LINK_PERS int, LINK_DED INT, CODE_DED VARCHAR(6), NAME_DED VARCHAR(254), SUMMA NUMERIC(10,2), PREDEL NUMERIC(28,2), TYPE NUMERIC(3,0), DATE1 DATETIME, DATE2 DATETIME,M_BEG INT, M_END INT, NUM_ROW int identity(1,1), FIO VARCHAR(60), BIRTHDAY DATETIME, AGE INT)
	INSERT INTO #RES_VICHET
	SELECT ed.LINK, 
		   ed.EMPL_LINK AS LINK_EMPL,
		   @LINK_PERS as  LINK_PERS,
		   ed.DED_LINK AS LINK_DED,
           sd.CODE AS CODE_DED,
           sd.NAME AS NAME_DED,
           sd.SUMMA AS SUMMA,
           /*(SELECT CODE
            FROM   dbo.DICTIONARY_TYP_DEDUCTION AS DTD
            WHERE  (LINK = ED.DED_LINK)) AS CODE_DED,
           (SELECT NAME
            FROM   dbo.DICTIONARY_TYP_DEDUCTION AS DTD
            WHERE  (LINK = ED.DED_LINK)) AS NAME_DED, 
           (SELECT SUMMA
            FROM   dbo.DICTIONARY_TYP_DEDUCTION AS DTD
            WHERE  (LINK = ED.DED_LINK)) AS SUMMA, 
            */sd.predel,
            sd.type,
            ed.DATE1, 
            ed.DATE2,
			0,
            0,
            '',
            '',
            0
	FROM dbo.EMPL_DED AS ED 
			INNER JOIN #EMPLS R  ON  ED.empl_link = R.LINK
			inner join  #Salary_deductions sd on sd.ref_pay = ed.ded_link and sd.type = '1'

	where 
		ed.date1 <= @PRES_DATE 
				AND (ed.date2 IS NULL OR YEAR(ed.date2) = '1900' OR year(ed.date2) >=@varKSnYear)
				and @nMonth >= month(ed.date1) 
				and @varKSnYear = year(ed.date1)
				
	update #RES_VICHET
		set M_BEG =  case when year(DATE1)< @cYear then 1
					      when year(DATE1)= @cYear then Month(DATE1) 
						  end,
			M_END = case when DATE2 is null then null
					      when DATE2 is not null and month(DATE2) <= @nMonth then Month(DATE2)
					      when DATE2 is not null and month(DATE2) > @nMonth then null
						  end 
	from #RES_VICHET


	if exists(select CODE_DED from #RES_VICHET where NAME_DED like ('%ребенка%'))
	begin

		create table #CHILDS (ROW_ID int identity(1,1),FIO varchar (60) , BIRTHDAY DATETIME, AGE INT )
		insert into #CHILDS  ( FIO, BIRTHDAY, AGE )
		SELECT 	
			distinct
			[FIO] = CONVERT(VARCHAR(60),RTRIM(FM) +' '+RTRIM(IM) + ' '+ RTRIM(OT)),
			[BIRTHDAY] = BIRTHDATE,
			[AGE] = DATEDIFF(year,BIRTHDATE,dbo.DateEndOfYear(dbo.SalaryCalcPeriod())) 
		FROM 
			dbo.KU_PERS_FAMILY  
		WHERE 
			PERS_LINK = @LINK_PERS
			AND
			FAMILY_NAME IN ('Сын','Дочь', 'Пасынок', 'Падчерица')
			and datediff(yy, BIRTHDATE, dbo.ConvertDMY2Date(1,1,@cYear)) <18

	
		create table #CHILDS_res (LINK INT, LINK_EMPL INT, LINK_PERS int, LINK_DED INT, CODE_DED VARCHAR(6), NAME_DED VARCHAR(254), SUMMA NUMERIC(10,2), PREDEL NUMERIC(28,2), TYPE NUMERIC(3,0), DATE1 DATETIME, DATE2 DATETIME,M_BEG INT, M_END INT, NUM_ROW int, N_ROW_C int identity(1,1), FIO VARCHAR(60), BIRTHDAY DATETIME, AGE INT)
		insert into #CHILDS_res 
		select  r.*
		from #RES_VICHET r where r.NAME_DED like ('%ребенка%')

		update #CHILDS_res
		Set	[FIO] = c.FIO,
			[BIRTHDAY] = c.BIRTHDAY,
			[AGE] = c.AGE
		FROM 
			#CHILDS_res v ,#CHILDS c 
		WHERE 
			v.N_ROW_C = c.ROW_ID

		update #RES_VICHET
		Set	[FIO] = v.FIO,
			[BIRTHDAY] = v.BIRTHDAY,
			[AGE] = v.AGE
		FROM 
			#RES_VICHET r , #CHILDS_res v 
		WHERE 
			r.link = v.link
			
		drop table #CHILDS_res
		drop table  #CHILDS
	end	
	else 
	begin
		


		insert into #RES_VICHET 
		select distinct	
		   0, 
		   0, 
		   0,
		   0,
           '',
           '', 
           0, 
           0,
           0,
           '',
           '',
           0, 
           0,
		   CONVERT(VARCHAR(60),RTRIM(F.FM) +' '+RTRIM(F.IM) + ' '+ RTRIM(F.OT)),
		   isnull(F.BIRTHDATE,''),
		   DATEDIFF(year,F.BIRTHDATE,dbo.DateEndOfYear(dbo.SalaryCalcPeriod()))
		FROM 
			dbo.KU_PERS_FAMILY F
		WHERE 
			F.PERS_LINK = @LINK_PERS
			AND
			F.FAMILY_NAME IN ('Сын','Дочь', 'Пасынок', 'Падчерица')
			--and datediff(yy, BIRTHDATE, dbo.ConvertDMY2Date(1,1,@cYear)) <18
	end 	


	--- если в таблице нет кода с вычетом 103, то добавляем пустую строку и код 103 - для вывода в excel
	if not exists(select * from #RES_VICHET where code_ded = '103')
	begin
		insert into #RES_VICHET 
		select distinct	
		   null, 
		   null, 
		   null,
		   null,
           '103',
           ' ', 
           null, 
           null,
           null,
           null,
           null,
           null, 
           null,
           null,
		   null,
		   null
	end
	
	if not exists(select * from #RES_VICHET where code_ded <> '103' and name_ded not like '%на налогоплательщика%')
		begin
		insert into #RES_VICHET 
		select distinct	
		   0, 
		   0, 
		   0,
		   0,
           ' ',
		   '', 
           0, 
           0,
           0,
           '',
           '',
           0, 
           0,
           null,
		   null,
		   null
	   
	end
	--- 

	--- выборка детей работников 
		CREATE  TABLE  #RES_CHILD_VICHET(PERS_LINK INT, FIO VARCHAR(60), BIRTHDAY DATETIME, AGE INT)
		INSERT INTO #RES_CHILD_VICHET
		SELECT F.PERS_LINK,
			[FIO] = CONVERT(VARCHAR(60),RTRIM(F.FM) +' '+RTRIM(F.IM) + ' '+ RTRIM(F.OT)),
			[BIRTHDAY] = F.BIRTHDATE,
			[AGE] = DATEDIFF(year,F.BIRTHDATE,dbo.DateEndOfYear(dbo.SalaryCalcPeriod()))
		FROM 
			dbo.KU_PERS_FAMILY F
		WHERE 
			F.PERS_LINK = @LINK_PERS
			AND
			F.FAMILY_NAME IN ('Сын','Дочь', 'Пасынок', 'Падчерица')
		

	DECLARE @varKSStatus VARCHAR(1)
	Set @varKSStatus = COALESCE((SELECT TOP 1 STATUS FROM #PERSON),1) /*резидент, не резидент*/	
	--- выборка имущественных вычетов	
	CREATE  TABLE  #RES_IM_VICHET (LINK INT, LINK_EMPL INT, LINK_DED INT, YEAR INT, MONTH1 TINYINT, CODE_DED VARCHAR(6), NAME_DED VARCHAR(254), F_NAME VARCHAR(254), 
		SUM_DED NUMERIC(10,2),NUM_REF VARCHAR(15), IFNS_CODE VARCHAR(20), PREDEL NUMERIC(28,2), TYPE NUMERIC(3,0), DATE_ref DATETIME)
	INSERT INTO #RES_IM_VICHET
	SELECT distinct TD.LINK, 
		   TD.LINK_PERSON AS LINK_EMPL, 
		   TD.LINK_DICTION AS LINK_DED,
		   TD.YEAR,
		   TD.MONTH1,
		   CODE_DED = SPR.CODE,
           NAME_DED = SPR.NAME,
           F_NAME = case when SPR.CODE = '311' or SPR.CODE = '313' then 'Прямые расходы на  новое строительство и (или) приобретение'
						 when SPR.CODE = '312' then 'Погашение процентов по кредитам'
						 when SPR.CODE = '318' then 'Погашение процентов по кредитам на рефинансирование ипотечных займов'
						 else  SPR.NAME end ,
            TD.SUM_DED,
            TD.NUM_REF,
            TD.IFNS_CODE, 
            PREDEL = ISNULL(sd.SUMMA,SPR.SUMMA),
            sd.type,
            TD.DATE_REF
	FROM dbo.TAX_DEDUCTIONS AS TD 
			INNER JOIN #EMPLS R  ON  TD.link_person = R.LINK_PERS
			INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = td.LINK_DICTION AND SPR.NUMBER = 4
			LEFT JOIN #Salary_deductions sd on sd.ref_pay = td.LINK_DICTION and sd.type = '4'
	where 
		YEAR(td.date_ref) = @cYear 
		AND
		TD.LINK_DEP = @DEP_LINK
	group by td.LINK, TD.LINK_PERSON, TD.LINK_DICTION, SPR.CODE, SPR.NAME,	TD.YEAR,TD.MONTH1,  TD.SUM_DED, TD.NUM_REF, TD.IFNS_CODE, sd.SUMMA,SPR.SUMMA, sd.type, TD.DATE_REF

	---------	 Необлагаемые доходы	
	CREATE  TABLE  #RES_NE_VICHET (CODE_DED VARCHAR(6), NAME_DED VARCHAR(254), PREDEL NUMERIC(10,2), CODE_INC varchar(5), NAME_INC VARCHAR(254),  
				SUMMA_M1 NUMERIC(10,2),SUMMA_M2 NUMERIC(10,2),SUMMA_M3 NUMERIC(10,2),SUMMA_M4 NUMERIC(10,2),
				SUMMA_M5 NUMERIC(10,2),SUMMA_M6 NUMERIC(10,2),SUMMA_M7 NUMERIC(10,2),SUMMA_M8 NUMERIC(10,2),
				SUMMA_M9 NUMERIC(10,2),SUMMA_M10 NUMERIC(10,2),SUMMA_M11 NUMERIC(10,2),SUMMA_M12 NUMERIC(10,2))

	INSERT INTO #RES_NE_VICHET
	SELECT DISTINCT
		   CODE_DED = isnull(SPR.CODE,' '),
           NAME_DED = SPR.NAME,
           PREDEL = ISNULL(sd.SUMMA,SPR.SUMMA),
           CODE_INC = DT.SNAME,
           NAME_INC = DT.NAME,
           SUMMA_M1 = 0,
           SUMMA_M2 = 0,
           SUMMA_M3 = 0,
           SUMMA_M4 = 0,
           SUMMA_M5 = 0,
           SUMMA_M6 = 0,
           SUMMA_M7 = 0,
           SUMMA_M8 = 0,
           SUMMA_M9 = 0,
           SUMMA_M10 = 0,
           SUMMA_M11 = 0,
           SUMMA_M12 = 0
	FROM
		dbo.SAL_DED_MONTH AS SDM
		INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
		INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
		inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
		LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
	where 
		YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth


	update #RES_NE_VICHET	
	set    
		   SUMMA_M1 = isnull((select sum(SDM.SUMMA) 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 1 ),0) ,
           SUMMA_M2 = isnull((select SUM(SDM.SUMMA)
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 2 ),0),
           SUMMA_M3 = isnull((select SUM(SDM.SUMMA) 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 3 ),0),           
           SUMMA_M4 = isnull((select SUM(SDM.SUMMA) 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 4 ),0),           
           SUMMA_M5 = isnull((select SUM(SDM.SUMMA) 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 5 ),0),           
           SUMMA_M6 = isnull((select SUM(SDM.SUMMA) 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 6 ),0),          
           SUMMA_M7 = isnull((select SUM(SDM.SUMMA) 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 7 ),0),           
          SUMMA_M8 = isnull((select SUM(SDM.SUMMA) 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 8 ),0),           
           SUMMA_M9 = isnull((select SUM(SDM.SUMMA) 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 9 ),0),           
           SUMMA_M10 = isnull((select SUM(SDM.SUMMA) 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 10 ),0),           
           SUMMA_M11 = isnull((select SUM(SDM.SUMMA)
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 11 ),0),           
           SUMMA_M12 = isnull((select SUM(SDM.SUMMA) 
					   FROM
						dbo.SAL_DED_MONTH AS SDM
						INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION SPR ON SPR.LINK = SDM.REF_DED
						INNER JOIN #EMPLS R  ON  SDM.link_empl = R.LINK
						inner join  #Salary_deductions sd on sd.ref_pay = sdm.ref_ded  and sd.type = '6'
						LEFT join  #DICT_TYP_INCOMS DT on dt.cod_ded = sd.code and dt.ref_deduct is not null
						where 
						YEAR(sdm.date_ded) = @cYear  and month(sdm.date_ded) <= @nMonth	 and MONTH(sdm.DATE_ded) = 12 ),0)

	FROM #RES_NE_VICHET		
	
------*************************


	--CREATE  TABLE  #RES_NonNDFL_VICHET (LINK_EMPL INT,LINK INT, link_vkr INT, link_ekr INT, TYP_PER varchar (8), object varchar (8), SUMMA NUMERIC(10,2), period_begin datetime , period_end datetime,DATE_BEGIN datetime , DATE_END datetime, CODE_DED VARCHAR(3), Ref_ded varchar (8), CODE_INC varchar(5), link_inc int, NAME_DED VARCHAR(254) ,PREDEL NUMERIC(10,2), TYPE_ded NUMERIC(3,0))
	--INSERT INTO #RES_NonNdfl_VICHET
	--Select 
	--	JC.LINK_EMPL, P.LINK, link_vkr, ISNULL(JC.LINK_EKR,P.LINK_EKR), P.TYP_PER, P.OBJECT, jc.summa, 
	--	period_begin =  JC.period_begin ,
	--	period_end = JC.period_end,
	--	JC.DATE_BEGIN,
	--	JC.DATE_END,
	--	dt.cod_ded, 
	--	dt.ref_deduct, 
	--	dt.sname  ,
	--	dt.link , 
	--	dt.name as name_ded,
	--	sd.summa as summa_neoblag,
	--	sd.type 
	
	--from 
	--	dbo.CALCULATE_JURNAL JC 
	--	INNER JOIN #EMPLS R  ON  JC.link_empl = R.LINK_PERS
	--	/*INNER JOIN dbo.EMPL E ON C.LINK_EMPL = E.LINK  /*and e.link = 17114*/*/
	--	INNER JOIN dbo.PAYS P ON   JC.LINK_PAYS = P.LINK 
	--	inner join DICTIONARY_TYP_INCOMS DT on dt.link = p.link_inc and dt.ref_deduct is not null
	--	LEFT JOIN (Select d.link, o.code from sdoc d inner join dbo.s_objects o on d.object = o.link) d on jc.LINK_DOC = d.link
	--	inner join  dbo.Salary_deductions(@cYear + @nMonth + @eDay ) sd on sd.ref_pay = dt.ref_deduct and sd.type = '6'
	--where
	--	P.OBJECT = 1
	--	AND P.LINK in (Select LINK_PAYS from  dbo.NDFL_GroupTax() )   /*  dbo.NDFL_GroupTax() */ 
	--	AND  month(JC.PERIOD_BEGIN) <=@nMonth and  year(JC.PERIOD_BEGIN) = @cYear
	--	/*AND (	@Status <> 1 AND JC.LINK_EMPL = @LINK_EMPL /*Если не основной сотрудник, то доход по своему табельному номеру*/
	--			or
	--	@Status = 1     and  R.PERS_LINK = 17024*/ /*Если основной сотрудник, то доход по всем табельным номерам
	--	)*/	
	--AND JC.LINK_DEP = @DEP_LINK 
	
	----------------------------------
	-- 5. Налоговые ставки 
	----------------------------------
	-- таблица 5.1 Статус налогоплательщика
	declare @varKSSumDed numeric(15,2), @varKSRange  numeric(15,2), @varKSResid int, @varKSStrCom varchar(1000)

	declare @FACE int

	if @link_empl is null
		begin 
			set  @FACE = @link_PERS
		end 
	else
		begin 
			set	@FACE = @link_PERS	
		end


	CREATE  TABLE  #RES_EMP_STATUS (DATE_begin DATETIME,DATE_END DATETIME, NDFL_Range numeric (3), resident int, KSTR VARCHAR(3), month_d int,year_d varchar(4), link_inc int, link_dep int, sname varchar(4), name  varchar (254), flag int, perc_stav varchar(2) )
	INSERT INTO #RES_EMP_STATUS
	SELECT 
		   cast( (@cYear + '01' + '01') as datetime) ,
		   cast( (@cYear + @nMonth + @eDay) as datetime) ,
		   dbo.SalaryGetNDFLRange (@FACE,(@cYear + @nMonth + @eDay) ) as NDFL_Range ,
		   (case when dbo.GetEmplResident(@FACE) = 0 then 1
				 when dbo.GetEmplResident(@FACE) = 1 then 2
				 else 3 end) as resident, 
		   (case when (SELECT TOP 1 CODE FROM CITIZENSHIP WHERE LINK = (select  top 1 CITIZ_LINK from person where link = @LINK_PERS)) = '1' then '643' else '' END) as KSTR,
		   null,
		   '',
		   null,
		   null,
		   '',
		   '', 
		   null,
		   ''
	--Таблица 5.2 Виды доходов (доходы не по ставке 13%)
	--по сотрудникам

	CREATE  TABLE  #vid_dohod_not13 (month_d int,year_d varchar(4), link_inc int, link_dep int, sname varchar(4), name  varchar (254), flag int, perc_stav varchar(2) )
	insert into #vid_dohod_not13	
	select DISTINCT
		   month(s.period_end),
		   year(s.period_end),
		   s.link_inc,
		   s.link_dep,
		   d.sname,
		   d.name,
		   d.flag,
		   perc_stav = case when d.flag = 1 then '0' 
							   when d.flag = 2 then '13'
							   when d.flag = 3 then '30'
							   else '35'
							   end
	from 
		#EMPLS E
		INNER JOIN #S_J_C_SHORT  S ON S.link_empl = E.LINK
		INNER JOIN #DICT_TYP_INCOMS D ON  S.LINK_INC = D.LINK  AND D.FLAG not in (2) 
	where YEAR(S.DATE1) = @cYear 
		 and	
		  Month(s.date1)<= @nMonth 
		 AND S.LINK_DEP = @DEP_LINK 
		 and S.link_inc is not null

	--по договорникам
	insert into #vid_dohod_not13	
	select DISTINCT
		   month(s.period_end),
		   year(s.period_end),
		   s.link_inc,
		   s.link_dep,
		   d.sname,
		   d.name,
		   d.flag,
		   perc_stav = case when d.flag = 1 then '0' 
							   when d.flag = 2 then '13'
							   when d.flag = 3 then '30'
							   else '35'
							   end
	from 
		#S_J_C_SHORT  S
		INNER JOIN #DICT_TYP_INCOMS D ON  S.LINK_INC = D.LINK  AND D.FLAG not in (2) 
	where YEAR(S.DATE1) = @cYear 
		 and	
		  Month(s.date1)<= @nMonth 
		  AND S.PERS_LINK = @LINK_PERS
		 AND S.LINK_DEP = @DEP_LINK 
		 and S.link_inc is not null
	-----------------------------------------------------
	
	DECLARE @varKSCNT INT

	SELECT @varKSCNT  = COUNT(*) FROM #PERSON

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


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

	SELECT 
		@varKScInn = INN, @varKScKPP = KPP,
		@varKSFULL_NAME = FULL_NAME, 
		@varKSNALOG = NALOG, @varKSOKATO = Replace(OKATO,' ','') ,  @varKSOKTMO = Replace(OKTMO,' ',''), 
		@varKSPHONE = PHONE, 
		@varKSGLBUH  = GLBUH
	FROM #DEP
	------------------------------------
	--- 6.  Сведения о вычетах, предоставленных по предыдущему мету работы 
	------------------------------------
	
		---Сумма доходов, облагаемых по ставке 13%
	SELECT  * 
	INTO #Prev_dohod
	FROM SD_EMPL_PREV_DOHOD 
	WHERE LINK_EMPL =  @LINK_EMPL ORDER BY COD_TYP_INCOMS 


	--- Сумма доходов не облагаемых по ставке 13%
	SELECT  SD.LINK_EMPL,
			SD.REF_TYP_INCOMS ,
			SD.COD_TYP_INCOMS AS COD_INC,
			SD.NAME_TYP_INCOMS AS NAME_INC,
			(CASE WHEN SD.SUMMA_TYP_INCOMS > DT.SUMMA_DED THEN DT.SUMMA_DED 
				  WHEN SD.SUMMA_TYP_INCOMS <= DT.SUMMA_DED THEN SD.SUMMA_TYP_INCOMS END )AS SUMM_INC,
			@cYear as PER_YEAR	  				 
	INTO #Prev_dohod_NO
	FROM SD_EMPL_PREV_DOHOD sd
	inner join dbo.#DICT_TYP_INCOMS DT ON DT.LINK = SD.REF_TYP_INCOMS AND DT.NUMBER_DED = 6
	WHERE LINK_EMPL =  @LINK_EMPL ORDER BY COD_TYP_INCOMS

	declare @SUM_doh13  numeric(10,2),
			@sum_doh_no13 numeric(10,2)
		
	set @SUM_doh13 = isnull((select sum(SUMMA_TYP_INCOMS) from #Prev_dohod),0) 
	set @sum_doh_no13 = isnull((select sum(SUMM_INC) from #Prev_dohod_NO),0) 

	
	
	CREATE  TABLE  #DEP_Prev (link_dep int,NALOG varchar(10), INN varchar(12), KPP varchar(9), OKATO varchar(14), OKTMO varchar(11), FULL_NAME  varchar (254), ADDRES  varchar (254), SUMMA_13 NUMERIC(10,2))
	insert into #DEP_Prev
	SELECT 
		null AS link_dep,
		' ' AS NALOG,
		' ' AS INN,
		' ' AS KPP,
		' ' AS OKATO, 
		' ' AS OKTMO, 
		/*
		ISNULL(dd.link,null) AS link_dep,
		ISNULL(dd.IMNS, ' ') AS NALOG,
		ISNULL(dd.INN, ' ') AS INN,
		ISNULL(dd.KPP, ' ') AS KPP,
		ISNULL(dd.OKATO, ' ')AS OKATO,
		*/
		ISNULL(A.DEP, ' ') AS FULL_NAME,
		ISNULL(A.place, ' ') AS ADDRES,
		ISNULL((@SUM_doh13 - @sum_doh_no13),0) AS SUMMA_13
	FROM /*DICTIONARY_DEPARTMENT DD 
	inner join */KU_EMPL_OLDWORK A /*on  (dd.full_name = a.dep or dd.name = a.dep)*/
	inner join KJ_EMPL_OLDWORK_GROUP b  on a.EMPL_LINK = b.EMPL_LINK 
									and b.EMPL_LINK =  @LINK_EMPL
									and b.link > -1 
									and  year(b.date_end) = @cYear 
									and month(b.date_end) <=  @nMonth 
									and b.date_end = (select max(date_end) 
													  from KJ_EMPL_OLDWORK_GROUP   
													  WHERE EMPL_LINK = @LINK_EMPL 
															and  year(date_end) = @cYear  
															and month(date_end) <= @nMonth 
													  ) 

	where a.date_end = (select max(date_end)  from KJ_EMPL_OLDWORK_GROUP   
											  WHERE EMPL_LINK = @LINK_EMPL 
											and  year(date_end) = @cYear  
													and month(date_end) <= @nMonth 
													 ) 
	---- налоговые вычеты с предыдущего места работы по типам

	SELECT  dd.link_empl,dd.link_ded,dd.code_ded,dd.name_ded,dd.summa_ded as summ_ded, sd.type,  @cYear as PER_YEAR
	INTO #Prev_ded
	FROM SD_EMPL_PREV_DED dd
	inner join #Salary_deductions sd on sd.code = dd.code_ded  
	WHERE dd.LINK_EMPL =  @LINK_EMPL ORDER BY dd.CODE_DED
	
	------------------------------------------------
	-- 7. Доходы облагаемые по ставке 13%

	select 
		SJC.link_empl, 
		SJC.pers_link, 
		   d.name  , 
		   D.sname, 
		   SJC.period_begin, 
		   SJC.period_end, 
		   sum(SJC.summa) as summa , 
		   SJC.link_inc
		   
	into #Dohod_13	   		
	from   #S_J_C_SHORT SJC 
			--inner join pays  p on  p.link = SJC.link_pays and  p.link_inc is not null 
			inner join #DICT_TYP_INCOMS d on d.link = SJC.link_inc 
	WHERE
		(
			SJC.LINK_FACE = @FACE
			or
			SJC.PERS_LINK = @FACE
		)
		AND YEAR(CASE WHEN SJC.TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN SJC.TYP_PER = 2 THEN SJC.DATE1 END) = @cYear
		AND MONTH(CASE WHEN SJC.TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN SJC.TYP_PER = 2 THEN SJC.DATE1 END) <= @nMonth
		AND SJC.CODE_INC IS NOT NULL
		AND SJC.CODE_INC <> '0000'
		AND SJC.link_dep  = @DEP_LINK  
	group by SJC.pers_link, SJC.link_empl, D.sname ,d.name  , SJC.period_begin, SJC.period_end, SJC.link_inc

	create TABLE #Dohod_13_1 (link_empl int, name varchar(256),  sname varchar(4) ,link_inc int,  p_b1 datetime, p_e1 datetime, s1 numeric (10,2),  
						 p_b2 datetime, p_e2 datetime, s2 numeric (10,2),p_b3 datetime, p_e3 datetime, s3 numeric (10,2), 
						 p_b4 datetime, p_e4 datetime, s4 numeric (10,2),p_b5 datetime, p_e5 datetime, s5 numeric (10,2), 
						 p_b6 datetime, p_e6 datetime, s6 numeric (10,2),p_b7 datetime, p_e7 datetime, s7 numeric (10,2), 
						 p_b8 datetime, p_e8 datetime, s8 numeric (10,2),p_b9 datetime, p_e9 datetime, s9 numeric (10,2),
						 p_b10 datetime, p_e10 datetime, s10 numeric (10,2),p_b11 datetime, p_e11 datetime, s11 numeric (10,2),
						 p_b12 datetime, p_e12 datetime, s12 numeric (10,2))
	INSERT INTO #Dohod_13_1
	SELECT distinct
		D.link_empl ,
		D.name , 
		D.sname , 
 		D.link_inc,
		[p_b1] =(SELECT top 1 period_begin FROM #Dohod_13 WHERE month(period_begin) = '01' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[p_e1] =(SELECT top 1 period_end FROM #Dohod_13 WHERE month(period_end) = '01' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[s1] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '01' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)),
		[p_b2] =(SELECT top 1 period_begin FROM #Dohod_13 WHERE month(period_begin) = '02' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[p_e2] =(SELECT top 1 period_end FROM #Dohod_13 WHERE month(period_end) = '02' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[s2] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '02' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)),
		[p_b3] =(SELECT top 1 period_begin FROM #Dohod_13 WHERE month(period_begin) = '03' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[p_e3] =(SELECT top 1 period_end FROM #Dohod_13 WHERE month(period_end) = '03' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[s3] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '03' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)),
		[p_b4] =(SELECT top 1 period_begin FROM #Dohod_13 WHERE month(period_begin) = '04' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[p_e4] =(SELECT top 1 period_end FROM #Dohod_13 WHERE month(period_end) = '04' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[s4] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '04' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)),
		[p_b5] =(SELECT top 1 period_begin FROM #Dohod_13 WHERE month(period_begin) = '05' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[p_e5] =(SELECT top 1 period_end FROM #Dohod_13 WHERE month(period_end) = '05' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[s5] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '05' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)),
		[p_b6] =(SELECT top 1 period_begin FROM #Dohod_13 WHERE month(period_begin) = '06' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[p_e6] =(SELECT top 1 period_end FROM #Dohod_13 WHERE month(period_end) = '06' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[s6] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '06' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)),
		[p_b7] =(SELECT top 1 period_begin FROM #Dohod_13 WHERE month(period_begin) = '07' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[p_e7] =(SELECT top 1 period_end FROM #Dohod_13 WHERE month(period_end) = '07' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[s7] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '07' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)),
		[p_b8] =(SELECT top 1 period_begin FROM #Dohod_13 WHERE month(period_begin) = '08' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[p_e8] =(SELECT top 1 period_end FROM #Dohod_13 WHERE month(period_end) = '08' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[s8] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '08' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)),
		[p_b9] =(SELECT top 1 period_begin FROM #Dohod_13 WHERE month(period_begin) = '09' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[p_e9] =(SELECT top 1 period_end FROM #Dohod_13 WHERE month(period_end) = '09' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[s9] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '09' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)),
		[p_b10] =(SELECT top 1 period_begin FROM #Dohod_13 WHERE month(period_begin) = '10' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[p_e10] =(SELECT top 1 period_end FROM #Dohod_13 WHERE month(period_end) = '10' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[s10] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '10' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)),
		[p_b11] =(SELECT top 1 period_begin FROM #Dohod_13 WHERE month(period_begin) = '11' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[p_e11] =(SELECT top 1 period_end FROM #Dohod_13 WHERE month(period_end) = '11' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[s11] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '11' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)),
		[p_b12] =(SELECT top 1 period_begin FROM #Dohod_13 WHERE month(period_begin) = '12' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[p_e12] =(SELECT  top 1 period_end FROM #Dohod_13 WHERE month(period_end) = '12' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0)), 
		[s12] = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '12' AND LINK_INC = D.LINK_INC and ISNULL(link_empl,0) = ISNULL(d.link_empl,0))
	FROM #Dohod_13 D
	GROUP BY D.link_empl ,D.name , D.sname ,D.link_inc

	--- всего за месяц 
	CREATE  TABLE #Dohod_13_i (MODE int, S_JAN NUMERIC(10,2), S_FEB NUMERIC(10,2), S_MART NUMERIC(10,2), S_APR NUMERIC(10,2), S_MAY NUMERIC(10,2), S_JUN NUMERIC(10,2),S_JUL NUMERIC(10,2),S_AUG NUMERIC(10,2), S_SEN NUMERIC(10,2),S_OKT NUMERIC(10,2), S_NOV NUMERIC(10,2), S_DEC NUMERIC(10,2))
	INSERT INTO #Dohod_13_i
	SELECT
		MODE = 1,
		S_JAN = 0 , 
		S_FEB = 0 , 
		S_MART = 0, 
		S_APR = 0, 
		S_MAY = 0, 
		S_JUN = 0,
		S_JUL = 0,
		S_AUG = 0, 
		S_SEN = 0,
		S_OKT = 0, 
		S_NOV = 0, 
		S_DEC = 0
		 
	UPDATE #Dohod_13_i
	SET	S_JAN = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '01' ),
		S_FEB = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '02' ),
		S_MART= (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '03' ),
		S_APR = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '04' ), 
		S_MAY = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '05' ),
		S_JUN = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '06' ),
		S_JUL = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '07' ),
		S_AUG = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '08' ),
		S_SEN = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '09' ),
		S_OKT = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '10' ),
		S_NOV = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '11' ),
		S_DEC = (SELECT isnull(sum(summa),0) FROM #Dohod_13 WHERE month(period_end) = '12' ) 
	FROM #Dohod_13_i where MODE = 1	
	
	--- всего с нарастающим итогом с начала года за месяц
	INSERT INTO  #Dohod_13_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 2,
		S_JAN = isnull(S_JAN,0),
		S_FEB = isnull(S_JAN,0) + isnull(S_FEB,0),
		S_MART= isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) ,
		S_APR = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0),
		S_MAY = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0),
		S_JUN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0),
		S_JUL = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0),
		S_AUG = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0),
		S_SEN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0), 
		S_OKT = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0),
		S_NOV = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0),
		S_DEC = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0) + isnull(S_DEC,0)
	FROM #Dohod_13_i 
		 where MODE = 1	

	------------------------------------------------
	--8. Необлагаемые суммы доходов
	
	Select distinct 
			code_ded, 
			code_inc, 
			name_ded, 
			predel,
			SUMMA_M1,
            SUMMA_M2,          
            SUMMA_M3,         
            SUMMA_M4,        
            SUMMA_M5,          
            SUMMA_M6,          
            SUMMA_M7,        
            SUMMA_M8,      
            SUMMA_M9,         
            SUMMA_M10,         
            SUMMA_M11,          
            SUMMA_M12
				 
	into #Dohod_13_predel
	from #RES_NE_VICHET R

	--- всего за месяц 

	CREATE  TABLE #Dohod_13_predel_i (MODE int null, S_JAN NUMERIC(10,2) , S_FEB NUMERIC(10,2), S_MART NUMERIC(10,2), S_APR NUMERIC(10,2), S_MAY NUMERIC(10,2), S_JUN NUMERIC(10,2),S_JUL NUMERIC(10,2),S_AUG NUMERIC(10,2), S_SEN NUMERIC(10,2),S_OKT NUMERIC(10,2), S_NOV NUMERIC(10,2), S_DEC NUMERIC(10,2))
	
	INSERT INTO #Dohod_13_predel_i
	
	SELECT
		MODE = 1,
		S_JAN = 0, 
		S_FEB = 0, 
		S_MART = 0, 
		S_APR = 0, 
		S_MAY = 0, 
		S_JUN = 0,
		S_JUL = 0,
		S_AUG = 0, 
		S_SEN = 0,
		S_OKT = 0, 
		S_NOV = 0, 
		S_DEC = 0
	 
	UPDATE #Dohod_13_predel_i
	SET MODE = 1,
		S_JAN = (SELECT isnull(SUMMA_M1,0) FROM #Dohod_13_predel),
		S_FEB = (SELECT isnull(SUMMA_M2,0) FROM #Dohod_13_predel),
		S_MART =(SELECT isnull(SUMMA_M3,0) FROM #Dohod_13_predel),
		S_APR = (SELECT isnull(SUMMA_M4,0) FROM #Dohod_13_predel),	
		S_MAY = (SELECT isnull(SUMMA_M5,0) FROM #Dohod_13_predel),
		S_JUN = (SELECT isnull(SUMMA_M6,0) FROM #Dohod_13_predel),	
		S_JUL = (SELECT isnull(SUMMA_M7,0) FROM #Dohod_13_predel),
		S_AUG = (SELECT isnull(SUMMA_M8,0) FROM #Dohod_13_predel),	
		S_SEN = (SELECT isnull(SUMMA_M9,0) FROM #Dohod_13_predel),
		S_OKT = (SELECT isnull(SUMMA_M10,0) FROM #Dohod_13_predel),	
		S_NOV = (SELECT isnull(SUMMA_M11,0) FROM #Dohod_13_predel),
		S_DEC = (SELECT isnull(SUMMA_M12,0) FROM #Dohod_13_predel) 
	FROM #Dohod_13_predel_i	 where mode = 1 
	
	--- всего с нарастающим итогом с начала года за месяц
	INSERT INTO #Dohod_13_predel_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 2,
	    S_JAN = isnull(S_JAN,0), 
		S_FEB = isnull(S_JAN,0) + isnull(S_FEB,0), 
		S_MART =isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0),
		S_APR = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0),
		S_MAY = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0),
		S_JUN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0),
		S_JUL = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0),
		S_AUG = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0),
		S_SEN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0), 
		S_OKT = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0),
		S_NOV = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0), 
		S_DEC = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0) + isnull(S_DEC,0)
	FROM #Dohod_13_predel_i where mode = 1 
		
	------------------------------------------------
	--- 9. Сумма облагаемых доходов
	------------------------------------------------
	
	--- всего за месяц 

	CREATE  TABLE #Obl_Dohod_i (MODE INT , S_JAN NUMERIC(10,2), S_FEB NUMERIC(10,2), S_MART NUMERIC(10,2), S_APR NUMERIC(10,2), S_MAY NUMERIC(10,2), S_JUN NUMERIC(10,2),S_JUL NUMERIC(10,2),S_AUG NUMERIC(10,2), S_SEN NUMERIC(10,2),S_OKT NUMERIC(10,2), S_NOV NUMERIC(10,2), S_DEC NUMERIC(10,2))
	
	INSERT INTO #Obl_Dohod_i
	SELECT  mode = 1 ,S_JAN = 0 ,S_FEB = 0 ,S_MART = 0,	S_APR = 0,S_MAY = 0,S_JUN = 0,S_JUL = 0,S_AUG = 0,S_SEN = 0,S_OKT = 0,S_NOV = 0,S_DEC = 0
	
	UPDATE #Obl_Dohod_i
	SET S_JAN = (SELECT isnull(d.S_JAN,0) - isnull(dp.S_JAN,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),
		S_FEB = (SELECT isnull(d.S_FEB,0) - isnull(dp.S_FEB,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),
		S_MART =(SELECT isnull(d.S_MART,0) - isnull(dp.S_MART,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),
		S_APR = (SELECT isnull(d.S_APR,0) - isnull(dp.S_APR,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),	
		S_MAY = (SELECT isnull(d.S_MAY,0) - isnull(dp.S_MAY,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),
		S_JUN = (SELECT isnull(d.S_JUN,0) - isnull(dp.S_JUN,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),	
		S_JUL = (SELECT isnull(d.S_JUL,0) - isnull(dp.S_JUL,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),
		S_AUG = (SELECT isnull(d.S_AUG,0) - isnull(dp.S_AUG,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),	
		S_SEN = (SELECT isnull(d.S_SEN,0) - isnull(dp.S_SEN,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),
		S_OKT = (SELECT isnull(d.S_OKT,0) - isnull(dp.S_OKT,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),	
		S_NOV = (SELECT isnull(d.S_NOV,0) - isnull(dp.S_NOV,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1),
		S_DEC = (SELECT isnull(d.S_DEC,0) - isnull(dp.S_DEC,0) FROM #Dohod_13_i d, #Dohod_13_predel_i dp where d.mode = 1 and dp.mode = 1) 
	FROM #Obl_Dohod_i where mode = 1 
	
	--- всего с нарастающим итогом с начала года за месяц
	INSERT INTO #Obl_Dohod_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 2,
		S_JAN = isnull(S_JAN,0), 
		S_FEB = isnull(S_JAN,0) + isnull(S_FEB,0), 
		S_MART =isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0), 
		S_APR = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0),
		S_MAY = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0),
		S_JUN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0),
		S_JUL = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0),
		S_AUG = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0),
		S_SEN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0), 
		S_OKT = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0),
		S_NOV = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0), 
		S_DEC = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0) + isnull(S_DEC,0)
	FROM #Obl_Dohod_i where mode = 1 
	
	-----------------------------------------------
	--- 10. Вычеты фактически предоставленные , стандартные, имущестевнные, проффессиональные
	-----------------------------------------------
	CREATE  TABLE #DED_FACT( /* LINK_VKR int, NAME_VKR varchar(20) ,*/ LINK_EMPL int , name_ded varchar(254) , code_ded varchar(6),ref_ded int,
							type tinyint,type_ded tinyint, type_name varchar(100),NUM1 int,summa_1 NUMERIC(10,2), countd1 int,NUM2 int, summa_2 NUMERIC(10,2), countd2 int,
							NUM3 int,summa_3 NUMERIC(10,2), countd3 int,NUM4 int, summa_4 NUMERIC(10,2), countd4 int,NUM5 int, summa_5 NUMERIC(10,2), countd5 int,
							NUM6 int,summa_6 NUMERIC(10,2), countd6 int,NUM7 int, summa_7 NUMERIC(10,2), countd7 int,NUM8 int, summa_8 NUMERIC(10,2), countd8 int,
							NUM9 int,summa_9 NUMERIC(10,2), countd9 int,NUM10 int, summa_10 NUMERIC(10,2), countd10 int,NUM11 int, summa_11 NUMERIC(10,2), countd11 int,
							NUM12 int,summa_12 NUMERIC(10,2), countd12 int)
	INSERT INTO #DED_FACT

	SELECT 	
	--LINK_VKR,
	--[NAME_VKR]= FIN.CODE,
	LINK_EMPL, 
	[name_ded] = T.[name],
	[code_ded] =T.[CODE],
	[ref_ded] = REF_DED,
	[type] = type,
	[type_ded] = t.number,
	[type_name] =(case when type=1 and t.number <> 4 and t.code not in (101,102,106,107,108,109,110,111,112,113)  then 'стандартный налоговый вычет'
					   when type=1 and t.number <> 4 and t.code in (101,102,106,107,108,109,110,111,112,113)  then 'Стандартный налоговый вычет на обеспечение ребенка'
					   when type=1 and  t.number = 10 then 'Социальный налоговый вычет в части расходов по уплате взносов на ДПС (НГПС)' 
					   when type=1 and t.number = 4  then 'Имущественный налоговый вычет'
						 else 'освобождаемые от налогообложения' 
					end),
	[NUM1] = 1,
	[summa_1] = 0,
	countd1 = 0,
	[num2] = 2,
	[summa_2] = 0,
	[countd2] = 0  ,
	[num3] = 3,
	[summa_3] = 0 ,
	[countd3] = 0 ,
	[num4] = 4,
	[summa_4] = 0 ,
	[countd4] = 0 ,	
	[num5]= 5,
	[summa_5] = 0 ,
	[countd5] = 0 ,
	[num6]= 6,
	[summa_6] = 0 ,
	[countd6] = 0 ,
	[num7]= 7,
	[summa_7]  = 0,
	[countd7] = 0 ,
	[num8]= 8,
	[summa_8]  = 0,
	[countd8]  = 0,		
	[num9]= 9,
	[summa_9] = 0 ,
	[countd9] = 0 ,
	[num10]= 10,
	[summa_10] = 0 ,
	[countd10] = 0 ,
	[num11]= 11,
	[summa_11] = 0 ,
	[countd11] = 0 ,
	[num12]= 12,
	[summa_12] = 0 ,
	[countd12] = 0 
	from 
		sal_ded_month D inner join months m on m.num =  month(DATE_DED)
		left join dbo.SAL_SFIN FIN ON FIN.LINK = D.LINK_VKR
		left join DICTIONARY_TYP_DEDUCTION  T on T.link = D.REF_DED
	where  
		month(DATE_DED)<=@nMonth and YEAR(DATE_DED)=@cYear and link_empl = @LINK_EMPL and (TYPE=1 /*or TYPE=2*/)

	group by /*m.num,*/ LINK_EMPL, REF_DED, T.[code],T.[name],  type , /*LINK_VKR, FIN.CODE ,*/ t.number
	order by 1,3
	
	update #DED_FACT
	set 	[summa_1] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= d.NUM1 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = d.ref_ded   and s1.link_empl = d.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd1 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= d.NUM1  and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = d.ref_ded   and s1.link_empl = d.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d

	update #DED_FACT 
	set 	[summa_2] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM2  and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = d.ref_ded   and s1.link_empl = d.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd2 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM2  and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = d.ref_ded   and s1.link_empl = d.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d

	update #DED_FACT
	set 	[summa_3] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM3 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd3 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM3 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d


	update #DED_FACT
	set 	[summa_4] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM4 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd4 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM4 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d

	update #DED_FACT
	set 	[summa_5] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM5 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd5 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM5 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d

	update #DED_FACT
	set 	[summa_6] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM6 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd6 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM6 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d
			
	update #DED_FACT
	set 	[summa_7] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM7 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd7 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM7 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d
	
	update #DED_FACT
	set 	[summa_8] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM8 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd8 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM8 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d
		
	update #DED_FACT
	set 	[summa_9] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM9 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd9 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM9 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d
		
	update #DED_FACT
	set 	[summa_10] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM10 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd10 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM10 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d
		
	update #DED_FACT
	set 	[summa_11] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM11 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd11 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM11 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d
		
	update #DED_FACT
	set 	[summa_12] = isnull((select sum(s1.summa) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM12 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2)),0),
			countd12 = (select count(s1.ref_ded) from sal_ded_month s1 
				where  month(s1.DATE_DED)= D.NUM12 and YEAR(s1.DATE_DED)=@cYear and s1.ref_ded = D.ref_ded   and s1.link_empl = D.link_empl and (s1.TYPE=1 or s1.TYPE=2))
	from #DED_FACT d

	--- всего за месяц 

	CREATE  TABLE #NDFL_13_i ( MODE int, S_JAN NUMERIC(18,2), d1 datetime, num1 varchar(10), S_FEB NUMERIC(18,2), d2 datetime, num2 varchar(10), S_MART NUMERIC(18,2), d3 datetime, num3 varchar(10), S_APR NUMERIC(18,2), d4 datetime, num4 varchar(10), 
							   S_MAY NUMERIC(18,2), d5 datetime, num5 varchar(10), S_JUN NUMERIC(18,2),d6 datetime, num6 varchar(10),S_JUL NUMERIC(18,2), d7 datetime, num7 varchar(10),S_AUG NUMERIC(18,2), d8 datetime, num8 varchar(10), 
							   S_SEN NUMERIC(18,2), d9 datetime, num9 varchar(10), S_OKT NUMERIC(18,2),d10 datetime, num10 varchar(10), S_NOV NUMERIC(18,2), d11 datetime, num11 varchar(10), S_DEC NUMERIC(18,2), d12 datetime, num12 varchar(10))
	
	INSERT INTO #NDFL_13_i
	
	SELECT 
		MODE = 1,
		S_JAN = 0 , 
		null,
		null,
		S_FEB = 0 , 
		null,
		null,
		S_MART = 0, 
		null,
		null,
		S_APR = 0, 
		null,
		null,
		S_MAY = 0, 
		null,
		null,
		S_JUN = 0,
		null,
		null,
		S_JUL = 0,
		null,
		null,
		S_AUG = 0, 
		null,
		null,
		S_SEN = 0,
		null,
		null,
		S_OKT = 0, 
		null,
		null,
		S_NOV = 0, 
		null,
		null,
		S_DEC = 0,
		null,
		null
		
	UPDATE #NDFL_13_i
	SET S_JAN = (SELECT sum(isnull(summa_1,0)) FROM #DED_FACT ),
		S_FEB = (SELECT sum(isnull(summa_2,0)) FROM #DED_FACT ),
		S_MART =(SELECT sum(isnull(summa_3,0)) FROM #DED_FACT ),
		S_APR = (SELECT sum(isnull(summa_4,0)) FROM #DED_FACT ),	
		S_MAY = (SELECT sum(isnull(summa_5,0)) FROM #DED_FACT ),
		S_JUN = (SELECT sum(isnull(summa_6,0)) FROM #DED_FACT ),	
		S_JUL = (SELECT sum(isnull(summa_7,0)) FROM #DED_FACT ),
		S_AUG = (SELECT sum(isnull(summa_8,0)) FROM #DED_FACT ),	
		S_SEN = (SELECT sum(isnull(summa_9,0)) FROM #DED_FACT ),
		S_OKT = (SELECT sum(isnull(summa_10,0)) FROM #DED_FACT ),	
		S_NOV = (SELECT sum(isnull(summa_11,0)) FROM #DED_FACT ),
		S_DEC = (SELECT sum(isnull(summa_12,0)) FROM #DED_FACT ) 
	FROM #NDFL_13_i where mode = 1

	--- всего с нарастающим итогом с начала года за месяц
	INSERT INTO #NDFL_13_i (MODE, S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6, S_JUL, D7, S_AUG, D8, S_SEN, D9, S_OKT, D10, S_NOV, D11, S_DEC, D12)
	SELECT 
		MODE = 2,
		S_JAN = isnull(S_JAN,0), 
		null,
		S_FEB = isnull(S_JAN,0) + isnull(S_FEB,0), 
		null,
		S_MART =isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0),
		null,
		S_APR = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0),
		null,
		S_MAY = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0),
		null,
		S_JUN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0),
		null,
		S_JUL = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0),
		null,
		S_AUG = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) ,
		null,
		S_SEN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) , 
		null,
		S_OKT = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0),
		null,
		S_NOV = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0), 
		null,
		S_DEC = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0) + isnull(S_DEC,0),
		null 
	FROM #NDFL_13_i where mode = 1
	---------------------------------------------
	---- 11. Облагаемая база ставка 13% 
	---------------------------------------------
	--- всего за месяц 

	INSERT INTO #NDFL_13_i (MODE, S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6, S_JUL, D7, S_AUG, D8, S_SEN, D9, S_OKT, D10, S_NOV, D11, S_DEC, D12)
	
	SELECT
		MODE = 3,
		S_JAN = 0 ,
		null,
		S_FEB = 0 ,
		null,
		S_MART = 0,
		null,
		S_APR = 0, 
		null,
		S_MAY = 0,
		null,
		S_JUN = 0,
		null,
		S_JUL = 0,
		null,
		S_AUG = 0,
		null, 
		S_SEN = 0,
		null,
		S_OKT = 0,
		null, 
		S_NOV = 0,
		null, 
		S_DEC = 0,
		null
	 
	UPDATE #NDFL_13_i
	SET S_JAN = (SELECT isnull(O.S_JAN,0) - isnull(D.S_JAN,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),
		S_FEB = (SELECT isnull(O.S_FEB,0) - isnull(D.S_FEB,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),
		S_MART =(SELECT isnull(O.S_MART,0) - isnull(D.S_MART,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),
		S_APR = (SELECT isnull(O.S_APR,0) - isnull(D.S_APR,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),	
		S_MAY = (SELECT isnull(O.S_MAY,0) - isnull(D.S_MAY,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),
		S_JUN = (SELECT isnull(O.S_JUN,0) - isnull(D.S_JUN,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),	
		S_JUL = (SELECT isnull(O.S_JUL,0) - isnull(D.S_JUL,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),
		S_AUG = (SELECT isnull(O.S_AUG,0) - isnull(D.S_AUG,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),	
		S_SEN = (SELECT isnull(O.S_SEN,0) - isnull(D.S_SEN,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),
		S_OKT = (SELECT isnull(O.S_OKT,0) - isnull(D.S_OKT,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),	
		S_NOV = (SELECT isnull(O.S_NOV,0) - isnull(D.S_NOV,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1),
		S_DEC = (SELECT isnull(O.S_DEC,0) - isnull(D.S_DEC,0) FROM #Obl_Dohod_i O, #NDFL_13_i d where d.mode = 1 and o.mode = 1) 
	FROM #NDFL_13_i where mode = 3

	--- всего с нарастающим итогом с начала года за месяц

	
	INSERT INTO #NDFL_13_i (MODE, S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6, S_JUL, D7, S_AUG, D8, S_SEN, D9, S_OKT, D10, S_NOV, D11, S_DEC, D12)
	SELECT 
		MODE = 4,
		S_JAN = 0 ,
		null, 
		S_FEB = 0 ,
		null, 
		S_MART = 0,
		null, 
		S_APR = 0, 
		null,
		S_MAY = 0,
		null, 
		S_JUN = 0,
		null,
		S_JUL = 0,
		null,
		S_AUG = 0,
		null, 
		S_SEN = 0,
		null,
		S_OKT = 0,
		null, 
		S_NOV = 0,
		null, 
		S_DEC = 0,
		null
		
	UPDATE #NDFL_13_i
	set   
		S_JAN = (SELECT isnull(o.S_JAN,0) - isnull(D.S_JAN,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2), 
		S_FEB = (SELECT isnull(o.S_FEB,0) - isnull(D.S_FEB,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2), 
		S_MART =(SELECT isnull(o.S_MART,0) - isnull(D.S_MART,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2),
		S_APR = (SELECT isnull(o.S_APR,0) - isnull(D.S_APR,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2),
		S_MAY = (SELECT isnull(o.S_MAY,0) - isnull(D.S_MAY,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2),
		S_JUN = (SELECT isnull(o.S_JUN,0) - isnull(D.S_JUN,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2),
		S_JUL = (SELECT isnull(o.S_JUL,0) - isnull(D.S_JUL,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2),
		S_AUG = (SELECT isnull(o.S_AUG,0) - isnull(D.S_AUG,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2),
		S_SEN = (SELECT isnull(o.S_SEN,0) - isnull(D.S_SEN,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2), 
		S_OKT = (SELECT isnull(o.S_OKT,0) - isnull(D.S_OKT,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2),
		S_NOV = (SELECT isnull(o.S_NOV,0) - isnull(D.S_NOV,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2), 
		S_DEC = (SELECT isnull(o.S_DEC,0) - isnull(D.S_DEC,0) FROM #NDFL_13_i D, #Obl_Dohod_i O where d.mode = 2 and o.mode=2)
	FROM #NDFL_13_i where mode = 4
	
	------------------------------------------------
	--- 12. НДФЛ по ставке 13%
	------------------------------------------------ 
	--сумма начисленного налого С НАЧАЛА ГОДА
	INSERT INTO #NDFL_13_i  (MODE, S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6, S_JUL, D7, S_AUG, D8, S_SEN, D9, S_OKT, D10, S_NOV, D11, S_DEC, D12)
	SELECT
		MODE = 5,
		S_JAN = 0 ,
		null, 
		S_FEB = 0 , 
		null, 
		S_MART = 0, 
		null, 
		S_APR = 0, 
		null,
		S_MAY = 0, 
		null, 
		S_JUN = 0,
		null,
		S_JUL = 0,
		null,
		S_AUG = 0, 
		null,
		S_SEN = 0,
		null,
		S_OKT = 0, 
		null,
		S_NOV = 0, 
		null,
		S_DEC = 0,
		null

	DECLARE @varKSCOEFF NUMERIC(20,2)
	SELECT @varKSCOEFF = CASE WHEN @varKSStatus = 1 THEN 0.13 ELSE 0.30 END

 
	UPDATE #NDFL_13_i 
	SET S_JAN = round((SELECT isnull(S_JAN,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0), 
		S_FEB = round((SELECT isnull(S_FEB,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0), 
		S_MART =round((SELECT isnull(S_MART,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0),
		S_APR = round((SELECT isnull(S_APR,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0),
		S_MAY = round((SELECT isnull(S_MAY,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0),
		S_JUN = round((SELECT isnull(S_JUN,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0),
		S_JUL = round((SELECT isnull(S_JUL,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0),
		S_AUG = round((SELECT isnull(S_AUG,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0),
		S_SEN = round((SELECT isnull(S_SEN,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0), 
		S_OKT = round((SELECT isnull(S_OKT,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0),
		S_NOV = round((SELECT isnull(S_NOV,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0), 
		S_DEC = round((SELECT isnull(S_DEC,0)* @varKSCOEFF FROM #NDFL_13_i where mode = 4 ),0)
	FROM #NDFL_13_i where mode =5
	

	
	
	--сумма начисленного налога за месяц 
	INSERT INTO #NDFL_13_i (MODE, S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6, S_JUL, D7, S_AUG, D8, S_SEN, D9, S_OKT, D10, S_NOV, D11, S_DEC, D12)
	SELECT
		MODE = 6,
		S_JAN = case ((SELECT SUM(C.SUMMA) FROM (select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '1'	
					     union all
					     select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '1') AS C ) 
						  - (round(isnull(S_JAN,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_JAN,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_JAN,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_JAN,0)* @varKSCOEFF,0) end,
		d1 = case when isnull(S_JAN,0) <>0 then (select max(d.date1) from dbo.days_month(1,@cYear)d) else null end,
		
		
		S_FEB =  case ((SELECT SUM(C.SUMMA) FROM(select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '2'	
					     union all
					     select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '2') AS C ) 
						  - (round(isnull(S_FEB,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_FEB,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_FEB,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_FEB,0)* @varKSCOEFF,0) end, 
		d2 = case when isnull(S_FEB,0) <>0 then (select max(d.date1) from dbo.days_month(2,@cYear)d) else null end,
		S_MART = case ((SELECT SUM(C.SUMMA) FROM(select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '3'	
					     union all
					     select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '3') AS C ) 
						  - (round(isnull(S_MART,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_MART,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_MART,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_MART,0)* @varKSCOEFF,0) end, 
		d3 = case when isnull(S_MART,0) <>0 then (select max(d.date1) from dbo.days_month(3,@cYear)d) else null end,
		S_APR = case ((SELECT SUM(C.SUMMA) FROM(select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '4'	
					     union all
					     select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '4') AS C ) 
						  - (round(isnull(S_APR,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_APR,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_APR,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_APR,0)* @varKSCOEFF,0) end,
		d4 = case when isnull(S_APR,0) <>0 then (select max(d.date1) from dbo.days_month(4,@cYear)d) else null end,
		S_MAY = case ((SELECT SUM(C.SUMMA) FROM(select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '5'	
					     union all
					     select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '5') AS C ) 
						  - (round(isnull(S_MAY,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_MAY,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_MAY,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_MAY,0)* @varKSCOEFF,0) end,
		d5 = case when isnull(S_MAY,0) <>0 then (select max(d.date1) from dbo.days_month(5,@cYear)d) else null end,
		S_JUN = case ((SELECT SUM(C.SUMMA) FROM(select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '6'	
					     union all
					     select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '6') AS C ) 
						  - (round(isnull(S_JUN,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_JUN,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_JUN,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_JUN,0)* @varKSCOEFF,0) end,
		d6 = case when isnull(S_JUN,0) <>0 then (select max(d.date1) from dbo.days_month(6,@cYear)d) else null end,
		S_JUL = case ((SELECT SUM(C.SUMMA) FROM(select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '7'	
					     union all
					     select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '7') AS C ) 
						  - (round(isnull(S_JUL,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_JUL,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_JUL,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_JUL,0)* @varKSCOEFF,0) end,
		d7 = case when isnull(S_JUL,0) <>0 then (select max(d.date1) from dbo.days_month(7,@cYear)d) else null end,
		S_AUG = case ((SELECT SUM(C.SUMMA) FROM(select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '8'	
					     union all
					     select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '8') AS C ) 
						  - (round(isnull(S_AUG,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_AUG,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_AUG,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_AUG,0)* @varKSCOEFF,0) end,
		d8 = case when isnull(S_AUG,0) <>0 then (select max(d.date1) from dbo.days_month(8,@cYear)d) else null end,
		S_SEN = case ((SELECT SUM(C.SUMMA) FROM(select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '9'	
					     union all
					     select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '9') AS C ) 
						  - (round(isnull(S_SEN,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_SEN,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_SEN,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_SEN,0)* @varKSCOEFF,0) end, 
		d9 = case when isnull(S_SEN,0) <>0 then (select max(d.date1) from dbo.days_month(9,@cYear)d) else null end,
		S_OKT = case ((SELECT SUM(C.SUMMA) FROM(select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '10'	
					     union all
					     select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '10') AS C ) 
						  - (round(isnull(S_OKT,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_OKT,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_OKT,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_OKT,0)* @varKSCOEFF,0) end, 
		d10 = case when isnull(S_OKT,0) <>0 then (select max(d.date1) from dbo.days_month(10,@cYear)d) else null end,
		S_NOV = case ((SELECT SUM(C.SUMMA) FROM(select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '11'	
					     union all
					     select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '11') AS C ) 
						  - (round(isnull(S_NOV,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_NOV,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_NOV,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_NOV,0)* @varKSCOEFF,0) end, 
		d11 = case when isnull(S_NOV,0) <>0 then (select max(d.date1) from dbo.days_month(11,@cYear)d) else null end,
		S_DEC =	case ((SELECT SUM(C.SUMMA) FROM(select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  E.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '12'	
					     union all
					     select sum(summa) as summa from #S_J_C_SHORT sjc 
							INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
							where  SJC.PERS_LINK = @LINK_PERS AND SJC.LINK_DEP = @DEP_LINK   and year(sjc.date1) = @varKSnYear and month(sjc.date1) = '12') AS C ) 
						  - (round(isnull(S_DEC,0)* @varKSCOEFF,0))
						)		
				    when 1	
					then (round(isnull(S_DEC,0)* @varKSCOEFF,0)+1)	
					when -1 
					then (round(isnull(S_DEC,0)* @varKSCOEFF,0)-1)	
					else round(isnull(S_DEC,0)* @varKSCOEFF,0) end, 
		d12 = case when isnull(S_DEC,0) <>0 then (select max(d.date1) from dbo.days_month(12,@cYear)d) else null end
	FROM #NDFL_13_i  where mode = 3

	
	--сумма удержанного налого С НАЧАЛА ГОДА
	CREATE TABLE #MONTHES ([MONTH] INT, SUMMA NUMERIC(18,2), CODE_DED VARCHAR(10) )
	INSERT INTO #MONTHES
	SELECT MONTH(DATE1), CAST( (SUM(CAST(round(SUMMA,0) as int) )) AS NUMERIC(8,0) ), ''
	FROM #S_J_C_SHORT SJC 
	INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
	INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
	WHERE 
 		YEAR(DATE1) = @varKSnYear
 		and 
		MONTH(DATE1)<= @nMonth
		AND 
		SJC.LINK_DEP = @DEP_LINK 
		AND 
		E.PERS_LINK = @LINK_PERS 
	GROUP BY MONTH(DATE1)
	UNION ALL
	SELECT MONTH(DATE1), CAST( (SUM(CAST(round(SUMMA,0) as int) )) AS NUMERIC(8,0) ), ''
	FROM #S_J_C_SHORT SJC 
	INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 4)
	WHERE 
 		YEAR(DATE1) = @varKSnYear 
 		and
 		MONTH(DATE1)<= @nMonth 
 		AND 
		SJC.LINK_DEP = @DEP_LINK 
		AND
		SJC.PERS_LINK = @LINK_PERS 
	GROUP BY MONTH(DATE1)	

	--сумма удержанного налога за месяц 
	INSERT INTO #NDFL_13_i (MODE,  S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6,S_JUL, D7,S_AUG, D8, S_SEN, D9,S_OKT, D10, S_NOV, D11, S_DEC, D12)
	select 
		MODE = 8,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null,
		0,
		null
	update	#NDFL_13_i	
	set 
		S_JAN = round(isnull((SELECT SUM(summa) FROM #MONTHES where [month]= 1 ),0),0), 
		S_FEB = round(isnull((SELECT SUM(summa) FROM #MONTHES where [month]= 2 ),0),0), 
		S_MART =round(isnull((SELECT SUM(summa) FROM #MONTHES where [month]= 3 ),0),0),
		S_APR = round(isnull((SELECT SUM(summa) FROM #MONTHES where [month]= 4 ),0),0),
		S_MAY = round(isnull((SELECT SUM(summa) FROM #MONTHES where [month]= 5 ),0),0),
		S_JUN = round(isnull((SELECT SUM(summa) FROM #MONTHES where [month]= 6 ),0),0),
		S_JUL = round(isnull((SELECT SUM(summa) FROM #MONTHES where [month]= 7 ),0),0),
		S_AUG = round(isnull((SELECT SUM(summa) FROM #MONTHES where [month]= 8 ),0),0),
		S_SEN = round(isnull((SELECT SUM(summa) FROM #MONTHES where [month]= 9 ),0),0), 
		S_OKT = round(isnull((SELECT SUM(summa) FROM #MONTHES where [month]= 10 ),0),0),
		S_NOV = round(isnull((SELECT SUM(summa) FROM #MONTHES where [month]= 11 ),0),0), 
		S_DEC = round(isnull((SELECT SUM(summa) FROM #MONTHES where [month]= 12 ),0),0)
	FROM #NDFL_13_i where mode = 8
	
	update	#NDFL_13_i	
	set 
		d1 = case when isnull(S_JAN,0) <>0 then (select max(d.date1)  from dbo.days_month(1,@cYear)d) else null end,
		d2 = case when isnull(S_FEB,0) <>0 then (select max(d.date1)  from dbo.days_month(2,@cYear)d) else null end,
		d3 = case when isnull(S_MART,0) <>0 then (select max(d.date1)  from dbo.days_month(3,@cYear)d) else null end,
		d4 = case when isnull(S_APR,0) <>0 then (select max(d.date1)  from dbo.days_month(4,@cYear)d) else null end,
		d5 = case when isnull(S_MAY,0) <>0 then (select max(d.date1)  from dbo.days_month(5,@cYear)d) else null end,
		d6 = case when isnull(S_JUN,0) <>0 then (select max(d.date1)  from dbo.days_month(6,@cYear)d) else null end,
		d7 = case when isnull(S_JUL,0) <>0 then (select max(d.date1)  from dbo.days_month(7,@cYear)d) else null end,
		d8 = case when isnull(S_AUG,0) <>0 then (select max(d.date1)  from dbo.days_month(8,@cYear)d) else null end,
		d9 = case when isnull(S_SEN,0) <>0 then (select max(d.date1)  from dbo.days_month(9,@cYear)d) else null end,
		d10 = case when isnull(S_OKT,0) <>0 then (select max(d.date1)  from dbo.days_month(10,@cYear)d) else null end,
		d11 = case when isnull(S_NOV,0) <>0 then (select max(d.date1)  from dbo.days_month(11,@cYear)d) else null end,
		d12 = case when isnull(S_DEC,0) <>0 then (select max(d.date1)  from dbo.days_month(12,@cYear)d) else null end
	FROM #NDFL_13_i where mode = 8	
	
 	
	INSERT INTO #NDFL_13_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 7,
		S_JAN = isnull(S_JAN,0), 
		S_FEB = isnull(S_JAN,0) + isnull(S_FEB,0), 
		S_MART =isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0),
		S_APR = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0),
		S_MAY = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0),
		S_JUN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0),
		S_JUL = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0),
		S_AUG = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0),
		S_SEN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0), 
		S_OKT = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0),
		S_NOV = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0), 
		S_DEC = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0) + isnull(S_DEC,0)
	FROM #NDFL_13_i where mode = 8
 	
	-- перечисления	НДФЛ по ставке 13%
	INSERT INTO #NDFL_13_i (MODE,  S_JAN, D1,NUM1, S_FEB, D2,NUM2, S_MART, D3,NUM3, S_APR, D4,NUM4, S_MAY, D5,NUM5, S_JUN, D6,NUM6,S_JUL, D7,NUM7,S_AUG, D8,NUM8, S_SEN, D9,NUM9,S_OKT, D10,NUM10, S_NOV, D11,NUM11, S_DEC, D12,NUM12)
	select 
		MODE = 10,
		0,
		null,
		null,
		0,
		null,
		null,
		0,
		null,
		null,
		0,
		null,
		null,
		0,
		null,
		null,
		0,
		null,
		null,
		0,
		null,
		null,
		0,
		null,
		null,
		0,
		null,
		null,
		0,
		null,
		null,
		0,
		null,
		null,
		0,
		null,
		null



	DECLARE @SUMMA_PLAT_ALL NUMERIC(18,2)
	DECLARE @SUMMA_NACH_ALL NUMERIC(18,2)


	update	#NDFL_13_i	
	set 
		d1 = (select max(d.date1)  from dbo.days_month(1,@cYear)d),
		d2 = (select max(d.date1)  from dbo.days_month(2,@cYear)d),
		d3 = (select max(d.date1)  from dbo.days_month(3,@cYear)d),
		d4 = (select max(d.date1)  from dbo.days_month(4,@cYear)d),
		d5 = (select max(d.date1)  from dbo.days_month(5,@cYear)d),
		d6 = (select max(d.date1)  from dbo.days_month(6,@cYear)d),
		d7 = (select max(d.date1)  from dbo.days_month(7,@cYear)d),
		d8 = (select max(d.date1)  from dbo.days_month(8,@cYear)d),
		d9 = (select max(d.date1)  from dbo.days_month(9,@cYear)d),
		d10 =(select max(d.date1)  from dbo.days_month(10,@cYear)d),
		d11 =(select max(d.date1)  from dbo.days_month(11,@cYear)d),
		d12 =(select max(d.date1)  from dbo.days_month(12,@cYear)d)
	FROM #NDFL_13_i where mode = 10	




	declare @db datetime ,
		@de datetime, 
		@SUMMA_PLAT_ALL1 NUMERIC(18,2),
		@SUMMA_NACH_ALL1 NUMERIC(18,2),
		@SUMMA_PLAT_ALL2 NUMERIC(18,2),
		@SUMMA_NACH_ALL2 NUMERIC(18,2),
		@SUMMA_PLAT_ALL3 NUMERIC(18,2),
		@SUMMA_NACH_ALL3 NUMERIC(18,2),
		@SUMMA_PLAT_ALL4 NUMERIC(18,2),
		@SUMMA_NACH_ALL4 NUMERIC(18,2),
		@SUMMA_PLAT_ALL5 NUMERIC(18,2),
		@SUMMA_NACH_ALL5 NUMERIC(18,2),
		@SUMMA_PLAT_ALL6 NUMERIC(18,2),
		@SUMMA_NACH_ALL6 NUMERIC(18,2),
		@SUMMA_PLAT_ALL7 NUMERIC(18,2),
		@SUMMA_NACH_ALL7 NUMERIC(18,2),
		@SUMMA_PLAT_ALL8 NUMERIC(18,2),
		@SUMMA_NACH_ALL8 NUMERIC(18,2),
		@SUMMA_PLAT_ALL9 NUMERIC(18,2),
		@SUMMA_NACH_ALL9 NUMERIC(18,2),
		@SUMMA_PLAT_ALL10 NUMERIC(18,2),
		@SUMMA_NACH_ALL10 NUMERIC(18,2),
		@SUMMA_PLAT_ALL11 NUMERIC(18,2),
		@SUMMA_NACH_ALL11 NUMERIC(18,2),
		@SUMMA_PLAT_ALL12 NUMERIC(18,2),
		@SUMMA_NACH_ALL12 NUMERIC(18,2)				
		
	set @db = @BEGIN_YEAR
	set @de = (select top 1  d1  FROM #NDFL_13_i where mode = 10)

	IF @nCHECK1 = 0
		BEGIN
			SET @SUMMA_PLAT_ALL1 =  @nSum1
		END
	ELSE
		BEGIN 
			EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL1 OUT
			SET @SUMMA_PLAT_ALL1 = ISNULL(@SUMMA_PLAT_ALL1,0)
		END 
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL1 OUT

	set @de = (select top 1 d2  FROM #NDFL_13_i where mode = 10)
	IF @nCHECK1 = 0
		BEGIN
			SET @SUMMA_PLAT_ALL2 =  @nSum2
		END
	ELSE
		BEGIN 
			EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL2 OUT
			SET @SUMMA_PLAT_ALL2 = ISNULL(@SUMMA_PLAT_ALL2,0)
		END 
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL2 OUT

	set @de = (select top 1 d3  FROM #NDFL_13_i where mode = 10)
	IF @nCHECK1 = 0
		BEGIN
			SET @SUMMA_PLAT_ALL3 =  @nSum3
		END
	ELSE
		BEGIN 
			EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL3 OUT
			SET @SUMMA_PLAT_ALL3 = ISNULL(@SUMMA_PLAT_ALL3,0)
		END 
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL3 OUT

	set @de = (select top 1 d4 FROM #NDFL_13_i where mode = 10)
	IF @nCHECK1 = 0
		BEGIN
			SET @SUMMA_PLAT_ALL4 =  @nSum4
		END
	ELSE
		BEGIN 
			EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL4 OUT
			SET @SUMMA_PLAT_ALL4 = ISNULL(@SUMMA_PLAT_ALL4,0)
		END 
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL4 OUT

	set @de = (select top 1 d5 FROM #NDFL_13_i where mode = 10)
	IF @nCHECK1 = 0
		BEGIN
			SET @SUMMA_PLAT_ALL5 =  @nSum5
		END
	ELSE
		BEGIN 
			EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL5 OUT
			SET @SUMMA_PLAT_ALL5 = ISNULL(@SUMMA_PLAT_ALL5,0)
		END 
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL5 OUT

	set @de = (select top 1 d6 FROM #NDFL_13_i where mode = 10)
	IF @nCHECK1 = 0
		BEGIN
			SET @SUMMA_PLAT_ALL6 =  @nSum6
		END
	ELSE
		BEGIN 
			EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL6 OUT
			SET @SUMMA_PLAT_ALL6 = ISNULL(@SUMMA_PLAT_ALL6,0)
		END 
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL6 OUT

	set @de = (select top 1 d7 FROM #NDFL_13_i where mode = 10)
	IF @nCHECK1 = 0
		BEGIN
			SET @SUMMA_PLAT_ALL7 =  @nSum7
		END
	ELSE
		BEGIN 
			EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL7 OUT
			SET @SUMMA_PLAT_ALL7 = ISNULL(@SUMMA_PLAT_ALL7,0)
		END 
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL7 OUT

	set @de = (select top 1 d8 FROM #NDFL_13_i where mode = 10)
	IF @nCHECK1 = 0
		BEGIN
			SET @SUMMA_PLAT_ALL8 =  @nSum8
		END
	ELSE
		BEGIN 
			EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL8 OUT
			SET @SUMMA_PLAT_ALL8 = ISNULL(@SUMMA_PLAT_ALL8,0)
		END 
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL8 OUT

	set @de = (select top 1 d9 FROM #NDFL_13_i where mode = 10)
	IF @nCHECK1 = 0
		BEGIN
			SET @SUMMA_PLAT_ALL9 =  @nSum9
		END
	ELSE
		BEGIN 
			EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL9 OUT
			SET @SUMMA_PLAT_ALL9 = ISNULL(@SUMMA_PLAT_ALL9,0)
		END 
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL9 OUT

	set @de = (select top 1 d10 FROM #NDFL_13_i where mode = 10)
	IF @nCHECK1 = 0
		BEGIN
			SET @SUMMA_PLAT_ALL10 =  @nSum10
		END
	ELSE
		BEGIN 
				EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL10 OUT
				SET @SUMMA_PLAT_ALL10 = ISNULL(@SUMMA_PLAT_ALL10,0)
		END 
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL10 OUT

	set @de = (select top 1 d11 FROM #NDFL_13_i where mode = 10)
	IF @nCHECK1 = 0
		BEGIN
			SET @SUMMA_PLAT_ALL11 =  @nSum11
		END
	ELSE
		BEGIN 
			EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL11 OUT
			SET @SUMMA_PLAT_ALL11 = ISNULL(@SUMMA_PLAT_ALL11,0)
		END 
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL11 OUT

	set @de = (select top 1 d12 FROM #NDFL_13_i where mode = 10)
	IF @nCHECK1 = 0
		BEGIN
			SET @SUMMA_PLAT_ALL12 =  @nSum12
		END
	ELSE
		BEGIN 
			EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL12 OUT
			SET @SUMMA_PLAT_ALL12 = ISNULL(@SUMMA_PLAT_ALL12,0)
		END 
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL12 OUT


	
IF @nCHECK1 != 0
begin	
	exec dbo.BufferClear 'DT'
	exec dbo.BufferClear 'KT'

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

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


		SELECT max(g.number) as number, max(g.date) as [date] ,CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.')) as PERIOD /*, SUM(P.SUMMA)*/
				into #GPROV_PP
				from 
					dbo.AProvByBufferConditionsShortDate('19900101', '20991231','DT', 'KT') P
					inner join dbo.DOCUMENTS_PAY_ADD PA on P.link = PA.link
					inner join dbo.g_prov G on G.link = PA.link
				WHERE
					P.DEP_LINK = @DEP_LINK
					AND
					G.DEP = @DEP_LINK
					AND
					CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.')) BETWEEN MONTH(@BEGIN_YEAR) AND MONTH(@PRES_DATE)
					AND
					CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')) = YEAR(@BEGIN_YEAR)					
						
		group by PERIOD


	update	#NDFL_13_i	
	set 
		d1 = (select [date] from #GPROV_PP where PERIOD = 1),
		NUM1 = (select number from #GPROV_PP where PERIOD = 1),
		d2 = (select [date] from #GPROV_PP where PERIOD = 2),
		NUM2 = (select number from #GPROV_PP where PERIOD = 2),
		d3 = (select [date] from #GPROV_PP where PERIOD = 3),
		NUM3 = (select number from #GPROV_PP where PERIOD = 3),
		d4 = (select [date] from #GPROV_PP where PERIOD = 4),
		NUM4 = (select number from #GPROV_PP where PERIOD = 4),
		d5 = (select [date] from #GPROV_PP where PERIOD = 5),
		NUM5 = (select number from #GPROV_PP where PERIOD = 5),
		d6 = (select [date] from #GPROV_PP where PERIOD = 6),
		NUM6 = (select number from #GPROV_PP where PERIOD = 6),
		d7 = (select [date] from #GPROV_PP where PERIOD = 7),
		NUM7 = (select number from #GPROV_PP where PERIOD = 7),
		d8 = (select [date] from #GPROV_PP where PERIOD = 8),
		NUM8 = (select number from #GPROV_PP where PERIOD = 8),
		d9 = (select [date] from #GPROV_PP where PERIOD = 9),
		NUM9 = (select number from #GPROV_PP where PERIOD = 9),
		d10 =(select [date] from #GPROV_PP where PERIOD = 10),
		NUM10 = (select number from #GPROV_PP where PERIOD = 10),
		d11 =(select [date] from #GPROV_PP where PERIOD = 11),
		NUM11 = (select number from #GPROV_PP where PERIOD = 11),
		d12 =(select [date] from #GPROV_PP where PERIOD = 12),
		NUM12 = (select number from #GPROV_PP where PERIOD = 12)
	FROM #NDFL_13_i where mode = 10			
						
	exec dbo.BufferClear 'DT'
	exec dbo.BufferClear 'KT'	
end	

	--- расчет перечисленных сумм расчитывается в зависимости от удержанных сум, 
	---  если получившаяся перечисленная сумма больше начисленной , то перечисленную сумму обрезаем до начисленной
	UPDATE #NDFL_13_i
	 SET
		 S_JAN = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL1 * (CASE WHEN @SUMMA_NACH_ALL1 > 0 THEN ((select top 1 S_JAN from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL1) ELSE 0 END), 0)),													
		 S_FEB = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL2 * (CASE WHEN @SUMMA_NACH_ALL2 > 0 THEN ((select top 1 S_FEB from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL2) ELSE 0 END), 0)),
		 S_MART= CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL3 * (CASE WHEN @SUMMA_NACH_ALL3 > 0 THEN ((select top 1 S_MART from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL3) ELSE 0 END), 0)), 
		 S_APR = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL4 * (CASE WHEN @SUMMA_NACH_ALL4 > 0 THEN ((select top 1 S_APR from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL4) ELSE 0 END), 0)),
		 S_MAY = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL5 * (CASE WHEN @SUMMA_NACH_ALL5 > 0 THEN ((select top 1 S_MAY from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL5) ELSE 0 END), 0)),
		 S_JUN = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL6 * (CASE WHEN @SUMMA_NACH_ALL6 > 0 THEN ((select top 1 S_JUN from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL6) ELSE 0 END), 0)),
		 S_JUL = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL7 * (CASE WHEN @SUMMA_NACH_ALL7 > 0 THEN ((select top 1 S_JUL from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL7) ELSE 0 END), 0)),
		 S_AUG = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL8 * (CASE WHEN @SUMMA_NACH_ALL8 > 0 THEN ((select top 1 S_AUG from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL8) ELSE 0 END), 0)),
		 S_SEN = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL9 * (CASE WHEN @SUMMA_NACH_ALL9 > 0 THEN ((select top 1 S_SEN from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL9) ELSE 0 END), 0)),
		 S_OKT = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL10 * (CASE WHEN @SUMMA_NACH_ALL10 > 0 THEN ((select top 1 S_OKT from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL10) ELSE 0 END), 0)),
		 S_NOV = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL11 * (CASE WHEN @SUMMA_NACH_ALL11 > 0 THEN ((select top 1 S_NOV from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL11) ELSE 0 END), 0)),
		 S_DEC = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL12 * (CASE WHEN @SUMMA_NACH_ALL12 > 0 THEN ((select top 1 S_DEC from #NDFL_13_i where mode = 7)/ @SUMMA_NACH_ALL12) ELSE 0 END), 0))
	from #NDFL_13_i where mode = 10

			
	UPDATE #NDFL_13_i
	 SET S_JAN = CASE WHEN S_JAN > ISNULL((select top 1 S_JAN from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select top 1 S_JAN from #NDFL_13_i where mode = 5),0))
					  ELSE S_JAN END,													
		
		 S_FEB = CASE WHEN S_FEB > ISNULL((select top 1 S_FEB from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select top 1 S_FEB from #NDFL_13_i where mode = 5),0))
					  ELSE S_FEB END,
		
		 S_MART= CASE WHEN S_MART > ISNULL((select S_MART from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select S_MART from #NDFL_13_i where mode = 5),0))
					  ELSE S_MART END, 
		
		 S_APR = CASE WHEN S_APR > ISNULL((select top 1 S_APR from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select top 1 S_APR from #NDFL_13_i where mode = 5),0))
					  ELSE S_APR END,
		
		 S_MAY = CASE WHEN S_MAY > ISNULL((select top 1 S_MAY from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select top 1 S_MAY from #NDFL_13_i where mode = 5),0))
					  ELSE S_MAY END,
		
		 S_JUN = CASE WHEN S_JUN > ISNULL((select top 1 S_JUN from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select top 1 S_JUN from #NDFL_13_i where mode = 5),0))
					  ELSE S_JUN END,
		
		 S_JUL = CASE WHEN S_JUL> ISNULL((select top 1 S_JUL from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select top 1 S_JUL from #NDFL_13_i where mode = 5),0))
					  ELSE S_JUL END,
		
		 S_AUG = CASE WHEN S_AUG > ISNULL((select top 1 S_AUG from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select top 1 S_AUG from #NDFL_13_i where mode = 5),0))
					  ELSE S_AUG END,
		
		 S_SEN = CASE WHEN S_SEN > ISNULL((select top 1 S_SEN from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select top 1 S_SEN from #NDFL_13_i where mode = 5),0))
					  ELSE S_SEN END,
		
		 S_OKT = CASE WHEN S_OKT > ISNULL((select top 1 S_OKT from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select top 1 S_OKT from #NDFL_13_i where mode = 5),0))
					  ELSE S_OKT END,
		
		 S_NOV = CASE WHEN S_NOV > ISNULL((select top 1 S_NOV from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select top 1 S_NOV from #NDFL_13_i where mode = 5),0))
					  ELSE S_NOV END,
		
		 S_DEC = CASE WHEN S_DEC > ISNULL((select top 1 S_DEC from #NDFL_13_i where mode = 5),0)
					  THEN (ISNULL((select top 1 S_DEC from #NDFL_13_i where mode = 5),0))
					  ELSE S_DEC END
	from #NDFL_13_i where mode = 10		



	update	#NDFL_13_i	
	set 
		d1 = case when isnull(S_JAN,0) <> 0 then d1 else null end,
		d2 = case when isnull(S_FEB,0) <> 0 then d2 else null end,
		d3 = case when isnull(S_MART,0) <> 0 then d3 else null end,
		d4 = case when isnull(S_APR,0) <> 0 then d4 else null end,
		d5 = case when isnull(S_MAY,0) <> 0 then d5 else null end,
		d6 = case when isnull(S_JUN,0) <> 0 then d6 else null end,
		d7 = case when isnull(S_JUL,0) <> 0 then d7 else null end,
		d8 = case when isnull(S_AUG,0) <> 0 then d8 else null end,
		d9 = case when isnull(S_SEN,0) <> 0 then d9 else null end,
		d10 = case when isnull(S_OKT,0) <> 0 then d10 else null end,
		d11 = case when isnull(S_NOV,0) <> 0 then d11 else null end,
		d12 = case when isnull(S_DEC,0) <> 0 then d12 else null end
	FROM #NDFL_13_i where mode = 10	


--	--Перечисленная сумма по всем за период
----	EXEC dbo.SA_NDFL_PLAT @BEGIN_YEAR, @DATE, @DEP_LINK, @SUMMA_PLAT_ALL OUT
--	EXEC dbo.SA_NDFL_PLAT @BEGIN_YEAR, @DATE, @DEP_LINK, @SUMMA_PLAT_ALL OUT
--	--Начисленная сумма по всем за период
--	EXEC dbo.SA_NDFL_NACHISL @BEGIN_YEAR, @DATE, @DEP_LINK, @SUMMA_NACH_ALL OUT
--	--select @BEGIN_YEAR, @DATE, @DEP_LINK,	@SUMMA_PLAT_ALL, @SUMMA_NACH_ALL
--	--Перечисленная за сотрудника	
--	--UPDATE #RES0 SET NALOG13S = CONVERT(NUMERIC(18,0), ISNULL( @SUMMA_PLAT_ALL * CASE WHEN @SUMMA_NACH_ALL > 0 THEN (NALOGU13	/ @SUMMA_NACH_ALL) ELSE 0 END, 0))
	INSERT INTO #NDFL_13_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 9,
		S_JAN = isnull(S_JAN,0), 
		S_FEB = isnull(S_FEB,0) - isnull(S_JAN,0) , 
		S_MART =isnull(S_MART,0) - isnull(S_FEB,0) ,
		S_APR = isnull(S_APR,0) - isnull(S_MART,0),
		S_MAY = isnull(S_MAY,0) - isnull(S_APR,0),
		S_JUN = isnull(S_JUN,0) - isnull(S_MAY,0),
		S_JUL = isnull(S_JUL,0) - isnull(S_JUN,0),
		S_AUG = isnull(S_AUG,0) - isnull(S_JUL,0),
		S_SEN = isnull(S_SEN,0) - isnull(S_AUG,0), 
		S_OKT = isnull(S_OKT,0) - isnull(S_SEN,0),
		S_NOV = isnull(S_NOV,0) - isnull(S_OKT,0), 
		S_DEC = isnull(S_DEC,0) - isnull(S_NOV,0)
	FROM #NDFL_13_i where mode = 10	
	
	update	#NDFL_13_i	
	set 
		d1 = case when isnull(S_JAN,0) <> 0 then (select d1 from #NDFL_13_i where mode = 10) else null end,
		num1 = case when isnull(S_FEB,0) <> 0 then (select num1 from #NDFL_13_i where mode = 10) else null end,
		d2 = case when isnull(S_FEB,0) <> 0 then (select d2 from #NDFL_13_i where mode = 10) else null end,
		num2 = case when isnull(S_FEB,0) <> 0 then (select num2 from #NDFL_13_i where mode = 10) else null end,
		d3 = case when isnull(S_MART,0) <> 0 then (select d3 from #NDFL_13_i where mode = 10) else null end,
		num3 = case when isnull(S_FEB,0) <> 0 then (select num3 from #NDFL_13_i where mode = 10) else null end,
		d4 = case when isnull(S_APR,0) <> 0 then (select d4 from #NDFL_13_i where mode = 10)  else null end,
		num4 = case when isnull(S_FEB,0) <> 0 then (select num4 from #NDFL_13_i where mode = 10) else null end,
		d5 = case when isnull(S_MAY,0) <> 0 then (select d5 from #NDFL_13_i where mode = 10) else null end,
		num5 = case when isnull(S_FEB,0) <> 0 then (select num5 from #NDFL_13_i where mode = 10) else null end,
		d6 = case when isnull(S_JUN,0) <> 0 then (select d6 from #NDFL_13_i where mode = 10) else null end,
		num6 = case when isnull(S_FEB,0) <> 0 then (select num6 from #NDFL_13_i where mode = 10) else null end,
		d7 = case when isnull(S_JUL,0) <> 0 then (select d7 from #NDFL_13_i where mode = 10) else null end,
		num7 = case when isnull(S_FEB,0) <> 0 then (select num7 from #NDFL_13_i where mode = 10) else null end,
		d8 = case when isnull(S_AUG,0) <> 0 then (select d8 from #NDFL_13_i where mode = 10) else null end,
		num8 = case when isnull(S_FEB,0) <> 0 then (select num8 from #NDFL_13_i where mode = 10) else null end,
		d9 = case when isnull(S_SEN,0) <> 0 then (select d9 from #NDFL_13_i where mode = 10) else null end,
		num9 = case when isnull(S_FEB,0) <> 0 then (select num9 from #NDFL_13_i where mode = 10) else null end,
		d10 = case when isnull(S_OKT,0) <> 0 then (select d10 from #NDFL_13_i where mode = 10) else null end,
		num10 = case when isnull(S_FEB,0) <> 0 then (select num10 from #NDFL_13_i where mode = 10) else null end,
		d11 = case when isnull(S_NOV,0) <> 0 then (select d11 from #NDFL_13_i where mode = 10) else null end,
		num11 = case when isnull(S_FEB,0) <> 0 then (select num11 from #NDFL_13_i where mode = 10) else null end,
		d12 = case when isnull(S_DEC,0) <> 0 then (select d12 from #NDFL_13_i where mode = 10) else null end,
		num12 = case when isnull(S_FEB,0) <> 0 then (select num12 from #NDFL_13_i where mode = 10) else null end
	FROM #NDFL_13_i where mode = 9		
	
	
	------------------------------------------------
	--- 15.Доходы , облагаемая база  - ставка 35%
	-------------------------------------------------
	/*	CREATE  TABLE  #vid_dohod_not13 (LINK_empl INT, LINK_face INT, month_d int,year_d varchar(4), link_inc int, link_dep int, sname varchar(4), name  varchar (254), flag int, percent_stav varchar(2) )
	insert into #vid_dohod_not13	
	select s.link_empl, 
		   s.link_face,
		   s.month_end,
		   s.year_end,
		   s.link_inc,
		   s.link_dep,
		   d.sname,
		   d.name,
		   d.flag,
		   percent_stav = case when d.flag = 1 then '0' 
							   when d.flag = 2 then '13'
							   when d.flag = 3 then '30'
							   else '35'
							   end
	from S_J_C_SHORT  S
		INNER JOIN DICTIONARY_TYP_INCOMS D ON  S.LINK_INC = D.LINK  AND D.FLAG not in (2) 
	where YEAR(S.DATE1) = @cYear 
		 AND S.LINK_DEP = @DEP_LINK 
		 AND S.link_empl = @LINK_EMPL 
		 and S.link_inc is not null
	group by s.link_empl, s.link_face , s.month_end, s.year_end,s.link_inc,s.link_dep, d.sname, d.name, d.flag
	*/

	select j.link_empl,  
		   d.name  , 
		   d.sname , 
		   j.period_begin, 
		   j.period_end, 
		   sum(j.summa) as summa , 
		   p.link_inc

	into #Dohod_35  	
	from   CALCULATE_JURNAL j
		INNER JOIN #EMPLS R  ON  J.link_empl = R.LINK
		inner join pays  p on  p.link = j.link_pays and  p.link_inc is not null 
		inner join #DICT_TYP_INCOMS d on d.link = p.link_inc  and  D.FLAG = 4  	
	where 
 		P.OBJECT = 1
		AND P.LINK in (Select LINK_PAYS from  dbo.NDFL_GroupTax() )   /*  dbo.NDFL_GroupTax() */ 
		AND  month(J.PERIOD_BEGIN) <=@nMonth and  year(J.PERIOD_BEGIN) = @cYear
		/*AND (	@Status <> 1 AND J.LINK_EMPL = @LINK_EMPL /*Если не основной сотрудник, то доход по своему табельному номеру*/
				or
		@Status = 1     and  R.LINK_FACE = @LINK_PERS /*Если основной сотрудник, то доход по всем табельным номерам*/
		)*/
		AND J.LINK_DEP = @DEP_LINK 
	group by j.link_empl, d.sname ,d.name  , j.period_begin, j.period_end, p.link_inc  

	--- Суммы доходов сгруппированнные по коду дохода по месяцам
	CREATE  TABLE #Dohod_35_m( LINK_EMPL int, name varchar(254), sname varchar(3),link_inc int, NUM1 int,summa_1 NUMERIC(10,2), d1 datetime,NUM2 int, summa_2 NUMERIC(10,2), d2 datetime,
							NUM3 int,summa_3 NUMERIC(10,2), d3 datetime,NUM4 int, summa_4 NUMERIC(10,2), d4 datetime,NUM5 int, summa_5 NUMERIC(10,2), d5 datetime,
							NUM6 int,summa_6 NUMERIC(10,2), d6 datetime,NUM7 int, summa_7 NUMERIC(10,2), d7 datetime,NUM8 int, summa_8 NUMERIC(10,2), d8 datetime,
							NUM9 int,summa_9 NUMERIC(10,2), d9 datetime,NUM10 int, summa_10 NUMERIC(10,2), d10 datetime,NUM11 int, summa_11 NUMERIC(10,2), d11 datetime,
							NUM12 int,summa_12 NUMERIC(10,2), d12 datetime)
	INSERT INTO #Dohod_35_m	

	select  d.link_empl,  
		    d.name  , 
		    d.sname , 
		    d.link_inc,
		    [NUM1] = 1,
			[summa_1] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '01' AND LINK_INC = D.LINK_INC),
			[d1] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '01' AND LINK_INC = D.LINK_INC),
			[num2] = 2,
			[summa_2] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '02' AND LINK_INC = D.LINK_INC),
			[d2] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '02' AND LINK_INC = D.LINK_INC),  
			[num3] = 3,
			[summa_3] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '03' AND LINK_INC = D.LINK_INC) ,
			[d3] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '03' AND LINK_INC = D.LINK_INC), 
			[num4] = 4,
			[summa_4] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '04' AND LINK_INC = D.LINK_INC) ,
			[d4] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '04' AND LINK_INC = D.LINK_INC),	
			[num5]= 5,
			[summa_5] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '05' AND LINK_INC = D.LINK_INC) ,
			[d5] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '05' AND LINK_INC = D.LINK_INC),
			[num6]= 6,
			[summa_6] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '06' AND LINK_INC = D.LINK_INC) ,
			[d6] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '06' AND LINK_INC = D.LINK_INC),
			[num7]= 7,
			[summa_7]  = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '07' AND LINK_INC = D.LINK_INC),
			[d7] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '07' AND LINK_INC = D.LINK_INC),
			[num8]= 8,
			[summa_8] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '08' AND LINK_INC = D.LINK_INC),
			[d8]  = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '08' AND LINK_INC = D.LINK_INC),		
			[num9]= 9,
			[summa_9] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '09' AND LINK_INC = D.LINK_INC) ,
			[d9] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '09' AND LINK_INC = D.LINK_INC), 
			[num10]= 10,
			[summa_10] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '10' AND LINK_INC = D.LINK_INC) ,
			[d10] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '10' AND LINK_INC = D.LINK_INC),
			[num11]= 11,
			[summa_11] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '11' AND LINK_INC = D.LINK_INC) ,
			[d11] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '11' AND LINK_INC = D.LINK_INC),
			[num12]= 12,
			[summa_12] = (SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '12' AND LINK_INC = D.LINK_INC) ,
			[d12] = (SELECT period_end FROM #Dohod_35 WHERE month(period_end) = '12' AND LINK_INC = D.LINK_INC)  

	from #Dohod_35 d 
	group by d.link_empl, d.sname ,d.name,  d.link_inc	
	

	--- всего за месяц 
	CREATE  TABLE #Dohod_35_i (MODE INT, S_JAN NUMERIC(10,2), d1 datetime, S_FEB NUMERIC(10,2), d2 datetime,  S_MART NUMERIC(10,2), d3 datetime,  S_APR NUMERIC(10,2), d4 datetime,
							  S_MAY NUMERIC(10,2), d5 datetime,  S_JUN NUMERIC(10,2), d6 datetime, S_JUL NUMERIC(10,2), d7 datetime, S_AUG NUMERIC(10,2), d8 datetime,
							  S_SEN NUMERIC(10,2), d9 datetime, S_OKT NUMERIC(10,2), d10 datetime,  S_NOV NUMERIC(10,2), d11 datetime, S_DEC NUMERIC(10,2), d12 datetime)
	INSERT INTO #Dohod_35_i
	SELECT
		MODE = 1,
		S_JAN = 0 ,
		null, 
		S_FEB = 0 , 
		null,
		S_MART = 0, 
		null,
		S_APR = 0, 
		null,
		S_MAY = 0, 
		null,
		S_JUN = 0,
		null,
		S_JUL = 0,
		null,
		S_AUG = 0, 
		null,
		S_SEN = 0,
		null,
		S_OKT = 0, 
		null,
		S_NOV = 0, 
		null,
		S_DEC = 0,
		null
		 
	UPDATE #Dohod_35_i
	SET	S_JAN = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '01' ),0),
		D1 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '01'), 
		S_FEB = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '02' ),0),
		D2 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '02'), 
		S_MART= round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '03' ),0),
		D3 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '03'), 
		S_APR = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '04' ),0), 
		D4 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '04'), 
		S_MAY = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '05' ),0),
		D5 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '05'), 
		S_JUN = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '06' ),0),
		D6 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '06'), 
		S_JUL = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '07' ),0),
		D7 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '07'), 
		S_AUG = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '08' ),0),
		D8 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '08'), 
		S_SEN = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '09' ),0),
		D9 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '09'), 
		S_OKT = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '10' ),0),
		D10 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '10'), 
		S_NOV = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '11' ),0),
		D11 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '11'), 
		S_DEC = round((SELECT isnull(sum(summa),0) FROM #Dohod_35 WHERE month(period_end) = '12' ),0), 
		D12 = (SELECT isnull(period_end,null) FROM #Dohod_35 WHERE month(period_end) = '12') 
	FROM #Dohod_35_i where mode = 1	
	
	--- всего с нарастающим итогом с начала года 
	INSERT INTO #Dohod_35_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 2,
		S_JAN = isnull(S_JAN,0),
		S_FEB = isnull(S_JAN,0) + isnull(S_FEB,0),
		S_MART= isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0),
		S_APR = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0),
		S_MAY = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0),
		S_JUN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0),
		S_JUL = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0),
		S_AUG = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0),
		S_SEN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0), 
		S_OKT = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0),
		S_NOV = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0),
		S_DEC = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0) + isnull(S_DEC,0)
	FROM #Dohod_35_i where mode = 1
		

	------------------------------------------------
	--- 16. НДФЛ по ставке 35%
	------------------------------------------------
	--сумма начисленного налога С НАЧАЛА ГОДА
	INSERT INTO #Dohod_35_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 3,
		S_JAN = round(isnull(S_JAN,0)*0.35,0),
		S_FEB = round(isnull(S_FEB,0)*0.35,0), 
		S_MART = round(isnull(S_MART,0)*0.35,0),
		S_APR = round(isnull(S_APR,0)*0.35,0),
		S_MAY = round(isnull(S_MAY,0)*0.35,0),
		S_JUN = round(isnull(S_JUN,0)*0.35,0),
		S_JUL = round(isnull(S_JUL,0)*0.35,0),
		S_AUG = round(isnull(S_AUG,0)*0.35,0),
		S_SEN = round(isnull(S_SEN,0)*0.35,0), 
		S_OKT = round(isnull(S_OKT,0)*0.35,0),
		S_NOV = round(isnull(S_NOV,0)*0.35,0), 
		S_DEC = round(isnull(S_DEC,0)*0.35,0)
	FROM #Dohod_35_i where mode = 2
	


	--сумма начисленного налога за месяц 
	INSERT INTO #Dohod_35_i (MODE, S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6,S_JUL, D7,S_AUG, D8, S_SEN, D9,S_OKT, D10, S_NOV, D11, S_DEC, D12)
	SELECT
		MODE = 4,
		S_JAN = round(isnull(S_JAN,0)*0.35,0),
		D1,  
		S_FEB = round(isnull(S_FEB,0)*0.35,0), 
		D2,
		S_MART =round(isnull(S_MART,0)*0.35,0),
		D3,
		S_APR = round(isnull(S_APR,0)*0.35,0),
		D4,
		S_MAY = round(isnull(S_MAY,0)*0.35,0),
		D5,
		S_JUN = round(isnull(S_JUN,0)*0.35,0),
		D6,
		S_JUL = round(isnull(S_JUL,0)*0.35,0),
		D7,
		S_AUG = round(isnull(S_AUG,0)*0.35,0),
		D8,
		S_SEN = round(isnull(S_SEN,0)*0.35,0), 
		D9,
		S_OKT = round(isnull(S_OKT,0)*0.35,0),
		D10,
		S_NOV = round(isnull(S_NOV,0)*0.35,0), 
		D11,
		S_DEC = round(isnull(S_DEC,0)*0.35,0),
		D12
	FROM #Dohod_35_i  where mode = 1
	
	--сумма удержанного налого С НАЧАЛА ГОДА
	delete from #MONTHES
	
	--CREATE TABLE #MONTHES ([MONTH] INT, SUMMA NUMERIC(18,2), CODE_DED VARCHAR(10) )
	INSERT INTO #MONTHES
	SELECT MONTH(DATE1), CAST( (SUM(CAST(round(SUMMA,0) as int) )) AS NUMERIC(8,0) ), ''
	FROM #S_J_C_SHORT SJC 
	INNER JOIN EMPL E ON (E.LINK = SJC.LINK_EMPL)
	INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 5)
	WHERE 
 		YEAR(DATE1) = @varKSnYear 
 		and
 		MONTH(DATE1)<= @nMonth
		AND 
		SJC.LINK_DEP = @DEP_LINK 
		AND 
		E.PERS_LINK = @LINK_PERS 
	GROUP BY MONTH(DATE1)
	UNION ALL
	SELECT MONTH(DATE1), CAST( (SUM(CAST(round(SUMMA,0) as int) )) AS NUMERIC(8,0) ), ''
	FROM #S_J_C_SHORT SJC INNER JOIN PAYS P ON (SJC.LINK_PAYS = P.LINK AND P.OBJECT = 2 AND P.WAY_CALC  = 5)
	WHERE 
 		YEAR(DATE1) = @varKSnYear 
		and 
		MONTH(DATE1)<= @nMonth
		AND 
		SJC.LINK_DEP = @DEP_LINK 
		AND
		SJC.PERS_LINK = @LINK_PERS 
	GROUP BY MONTH(DATE1)		
		
	--сумма удержанного налога за месяц 
	INSERT INTO #Dohod_35_i (MODE, S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6, S_JUL, D7, S_AUG, D8, S_SEN, D9, S_OKT, D10, S_NOV, D11, S_DEC, D12)
	select 5, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL
	
	UPDATE 	#Dohod_35_i
	Set
		MODE = 5,
		S_JAN = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 1 ),0),0), 
		D1 = case when isnull(S_JAN,0) <>0 then (select max(d.date1)  from dbo.days_month(1,@cYear)d) else null end,
		S_FEB = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 2 ),0),0), 
		D2 = case when isnull(S_FEB,0) <>0 then (select max(d.date1)  from dbo.days_month(2,@cYear)d) else null end,
		S_MART =isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 3 ),0),0),
		D3 = case when isnull(S_MART,0) <>0 then (select max(d.date1)  from dbo.days_month(3,@cYear)d) else null end,
		S_APR = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 4 ),0),0),
		D4 = case when isnull(S_APR,0) <>0 then (select max(d.date1)  from dbo.days_month(4,@cYear)d) else null end,
		S_MAY = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 5 ),0),0),
		D5 = case when isnull(S_MAY,0) <>0 then (select max(d.date1)  from dbo.days_month(5,@cYear)d) else null end,
		S_JUN = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 6 ),0),0),
		D6 = case when isnull(S_JUN,0) <>0 then (select max(d.date1)  from dbo.days_month(6,@cYear)d) else null end,
		S_JUL = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 7 ),0),0),
		D7 = case when isnull(S_JUL,0) <>0 then (select max(d.date1)  from dbo.days_month(7,@cYear)d) else null end,
		S_AUG = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 8 ),0),0),
		D8 = case when isnull(S_AUG,0) <>0 then (select max(d.date1)  from dbo.days_month(8,@cYear)d) else null end,
		S_SEN = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 9 ),0),0), 
		D9 = case when isnull(S_SEN,0) <>0 then (select max(d.date1)  from dbo.days_month(9,@cYear)d) else null end,
		S_OKT = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 10 ),0),0),
		D10 = case when isnull(S_OKT,0) <>0 then (select max(d.date1)  from dbo.days_month(10,@cYear)d) else null end,
		S_NOV = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 11 ),0),0), 
		D11 = case when isnull(S_NOV,0) <>0 then (select max(d.date1)  from dbo.days_month(11,@cYear)d) else null end,
		S_DEC = isnull(round((SELECT isnull(summa,0) FROM #MONTHES where [month]= 12 ),0),0),
		D12 = case when isnull(S_DEC,0) <>0 then (select max(d.date1)  from dbo.days_month(12,@cYear)d) else null end
	FROM #Dohod_35_i  where mode = 5
	
	
	--сумма удержанного за год по месяцам
	INSERT INTO #Dohod_35_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 6,
		S_JAN = isnull(S_JAN,0), 
		S_FEB = isnull(S_JAN,0) + isnull(S_FEB,0), 
		S_MART =isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0),
		S_APR = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0),
		S_MAY = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0),
		S_JUN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0),
		S_JUL = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0),
		S_AUG = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0),
		S_SEN = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0), 
		S_OKT = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0),
		S_NOV = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0), 
		S_DEC = isnull(S_JAN,0) + isnull(S_FEB,0) + isnull(S_MART,0) + isnull(S_APR,0) + isnull(S_MAY,0) + isnull(S_JUN,0) + isnull(S_JUL,0) + isnull(S_AUG,0) + isnull(S_SEN,0) + isnull(S_OKT,0) + isnull(S_NOV,0) + isnull(S_DEC,0)
	FROM #Dohod_35_i  where mode = 5 
	

	------------------------------------------------
	-- 17. Перечисление НДФЛ по ставке 35%
	------------------------------------------------
	--месяц 
	INSERT INTO #Dohod_35_i (MODE, S_JAN, D1, S_FEB, D2, S_MART, D3, S_APR, D4, S_MAY, D5, S_JUN, D6, S_JUL, D7, S_AUG, D8, S_SEN, D9, S_OKT, D10, S_NOV, D11, S_DEC, D12)
	select 8, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL
	update	#Dohod_35_i	
	set 
		d1 = (select max(d.date1)  from dbo.days_month(1,@cYear)d),
		d2 = (select max(d.date1)  from dbo.days_month(2,@cYear)d),
		d3 = (select max(d.date1)  from dbo.days_month(3,@cYear)d),
		d4 = (select max(d.date1)  from dbo.days_month(4,@cYear)d),
		d5 = (select max(d.date1)  from dbo.days_month(5,@cYear)d),
		d6 = (select max(d.date1)  from dbo.days_month(6,@cYear)d),
		d7 = (select max(d.date1)  from dbo.days_month(7,@cYear)d),
		d8 = (select max(d.date1)  from dbo.days_month(8,@cYear)d),
		d9 = (select max(d.date1)  from dbo.days_month(9,@cYear)d),
		d10 =(select max(d.date1)  from dbo.days_month(10,@cYear)d),
		d11 =(select max(d.date1)  from dbo.days_month(11,@cYear)d),
		d12 =(select max(d.date1)  from dbo.days_month(12,@cYear)d)
	FROM #Dohod_35_i where mode = 8	
	
	set @db = @BEGIN_YEAR
	set @de = (select top 1 d1  FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL1 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL1 OUT

	set @de = (select top 1 d2  FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL2 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL2 OUT

	set @de = (select top 1 d3  FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL3 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL3 OUT

	set @de = (select top 1 d4 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL4 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL4 OUT

	set @de = (select top 1 d5 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL5 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL5 OUT

	set @de = (select top 1 d6 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL6 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL6 OUT

	set @de = (select top 1 d7 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL7 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL7 OUT

	set @de = (select top 1 d8 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL8 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL8 OUT

	set @de = (select top 1 d9 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL9 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL9 OUT

	set @de = (select top 1 d10 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL10 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL10 OUT

	set @de = (select top 1 d11 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL11 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL11 OUT

	set @de = (select top 1 d12 FROM #Dohod_35_i where mode = 8)
	EXEC dbo.SA_NDFL_PLAT @db, @de, @DEP_LINK, @SUMMA_PLAT_ALL12 OUT
	EXEC dbo.SA_NDFL_NACHISL @db, @de, @DEP_LINK, @SUMMA_NACH_ALL12 OUT

	--- расчет перечисленных сумм расчитывается в зависимости от удержанных сум, 
	---  если получившаяся перечисленная сумма больше начисленной , то перечисленную сумму обрезаем до начисленной
	UPDATE #Dohod_35_i
	 SET S_JAN = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL1 * (CASE WHEN @SUMMA_NACH_ALL1 > 0 THEN ((select top 1 S_JAN from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL1) ELSE 0 END), 0)),													
		 S_FEB = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL2 * (CASE WHEN @SUMMA_NACH_ALL2 > 0 THEN ((select top 1 S_FEB from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL2) ELSE 0 END), 0)),
		 S_MART= CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL3 * (CASE WHEN @SUMMA_NACH_ALL3 > 0 THEN ((select top 1 S_MART from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL3) ELSE 0 END), 0)), 
		 S_APR = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL4 * (CASE WHEN @SUMMA_NACH_ALL4 > 0 THEN ((select top 1 S_APR from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL4) ELSE 0 END), 0)),
		 S_MAY = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL5 * (CASE WHEN @SUMMA_NACH_ALL5 > 0 THEN ((select top 1 S_MAY from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL5) ELSE 0 END), 0)),
		 S_JUN = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL6 * (CASE WHEN @SUMMA_NACH_ALL6 > 0 THEN ((select top 1 S_JUN from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL6) ELSE 0 END), 0)),
		 S_JUL = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL7 * (CASE WHEN @SUMMA_NACH_ALL7 > 0 THEN ((select top 1 S_JUL from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL7) ELSE 0 END), 0)),
		 S_AUG = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL8 * (CASE WHEN @SUMMA_NACH_ALL8 > 0 THEN ((select top 1 S_AUG from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL8) ELSE 0 END), 0)),
		 S_SEN = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL9 * (CASE WHEN @SUMMA_NACH_ALL9 > 0 THEN ((select top 1 S_SEN from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL9) ELSE 0 END), 0)),
		 S_OKT = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL10 * (CASE WHEN @SUMMA_NACH_ALL10 > 0 THEN ((select top 1 S_OKT from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL10) ELSE 0 END), 0)),
		 S_NOV = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL11 * (CASE WHEN @SUMMA_NACH_ALL11 > 0 THEN ((select top 1 S_NOV from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL11) ELSE 0 END), 0)),
		 S_DEC = CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL12 * (CASE WHEN @SUMMA_NACH_ALL12 > 0 THEN ((select top 1 S_DEC from #Dohod_35_i where mode = 6)/ @SUMMA_NACH_ALL12) ELSE 0 END), 0))
	from #Dohod_35_i where mode = 8
			
	UPDATE #Dohod_35_i
	 SET S_JAN = CASE WHEN S_JAN > ISNULL((select top 1 S_JAN from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select top 1 S_JAN from #Dohod_35_i where mode = 3),0))
					  ELSE S_JAN END,													
		
		 S_FEB = CASE WHEN S_FEB > ISNULL((select top 1 S_FEB from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select top 1 S_FEB from #Dohod_35_i where mode = 3),0))
					  ELSE S_FEB END,
		
		 S_MART= CASE WHEN S_MART > ISNULL((select top 1 S_MART from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select top 1 S_MART from #Dohod_35_i where mode = 3),0))
					  ELSE S_MART END, 
		
		 S_APR = CASE WHEN S_APR > ISNULL((select top 1 S_APR from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select top 1 S_APR from #Dohod_35_i where mode = 3),0))
					  ELSE S_APR END,
		
		 S_MAY = CASE WHEN S_MAY > ISNULL((select top 1 S_MAY from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select top 1 S_MAY from #Dohod_35_i where mode = 3),0))
					  ELSE S_MAY END,
		
		 S_JUN = CASE WHEN S_JUN > ISNULL((select top 1 S_JUN from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select top 1 S_JUN from #Dohod_35_i where mode = 3),0))
					  ELSE S_JUN END,
		
		 S_JUL = CASE WHEN S_JUL> ISNULL((select top 1 S_JUL from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select top 1 S_JUL from #Dohod_35_i where mode = 3),0))
					  ELSE S_JUL END,
		
		 S_AUG = CASE WHEN S_AUG > ISNULL((select top 1 S_AUG from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select top 1 S_AUG from #Dohod_35_i where mode = 3),0))
					  ELSE S_AUG END,
		
		 S_SEN = CASE WHEN S_SEN > ISNULL((select top 1 S_SEN from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select top 1 S_SEN from #Dohod_35_i where mode = 3),0))
					  ELSE S_SEN END,
		
		 S_OKT = CASE WHEN S_OKT > ISNULL((select top 1 S_OKT from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select top 1 S_OKT from #Dohod_35_i where mode = 3),0))
					  ELSE S_OKT END,
		
		 S_NOV = CASE WHEN S_NOV > ISNULL((select top 1 S_NOV from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select top 1 S_NOV from #Dohod_35_i where mode = 3),0))
					  ELSE S_NOV END,
		
		 S_DEC = CASE WHEN S_DEC > ISNULL((select top 1 S_DEC from #Dohod_35_i where mode = 3),0)
					  THEN (ISNULL((select top 1 S_DEC from #Dohod_35_i where mode = 3),0))
					  ELSE S_DEC END
	from #Dohod_35_i where mode = 8	
---CONVERT(NUMERIC(18,0), ISNULL(@SUMMA_PLAT_ALL1 * (CASE WHEN @SUMMA_NACH_ALL1 > 0 THEN ((select S_JAN from #Dohod_35_i where mode = 5)/ @SUMMA_NACH_ALL1) ELSE 0 END),0)),
	
	update	#Dohod_35_i 
	set 
		d1 = case when isnull(S_JAN,0) <> 0 then d1 else null end,
		d2 = case when isnull(S_FEB,0) <> 0 then d2 else null end,
		d3 = case when isnull(S_MART,0) <> 0 then d3 else null end,
		d4 = case when isnull(S_APR,0) <> 0 then d4 else null end,
		d5 = case when isnull(S_MAY,0) <> 0 then d5 else null end,
		d6 = case when isnull(S_JUN,0) <> 0 then d6 else null end,
		d7 = case when isnull(S_JUL,0) <> 0 then d7 else null end,
		d8 = case when isnull(S_AUG,0) <> 0 then d8 else null end,
		d9 = case when isnull(S_SEN,0) <> 0 then d9 else null end,
		d10 = case when isnull(S_OKT,0) <> 0 then d10 else null end,
		d11 = case when isnull(S_NOV,0) <> 0 then d11 else null end,
		d12 = case when isnull(S_DEC,0) <> 0 then d12 else null end
	FROM #Dohod_35_i  where mode = 8	
	

	--год
	INSERT INTO #Dohod_35_i (MODE, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL,S_AUG, S_SEN,S_OKT, S_NOV, S_DEC)
	SELECT
		MODE = 7,
		S_JAN = isnull(S_JAN,0), 
		S_FEB = isnull(S_FEB,0) - isnull(S_JAN,0) , 
		S_MART =isnull(S_MART,0) - isnull(S_FEB,0) ,
		S_APR = isnull(S_APR,0) - isnull(S_MART,0),
		S_MAY = isnull(S_MAY,0) - isnull(S_APR,0),
		S_JUN = isnull(S_JUN,0) - isnull(S_MAY,0),
		S_JUL = isnull(S_JUL,0) - isnull(S_JUN,0),
		S_AUG = isnull(S_AUG,0) - isnull(S_JUL,0),
		S_SEN = isnull(S_SEN,0) - isnull(S_AUG,0), 
		S_OKT = isnull(S_OKT,0) - isnull(S_SEN,0),
		S_NOV = isnull(S_NOV,0) - isnull(S_OKT,0), 
		S_DEC = isnull(S_DEC,0) - isnull(S_NOV,0)
	FROM #Dohod_35_i where mode = 8	
	
	------------------------------------------------
	-- 14. Расчет сумм материальной выгоды на дату погашения
	------------------------------------------------
	
	------------------------------------------------
	-- 18.Взыскание/Возврат НДФЛ
	------------------------------------------------
	
	------------------------------------------------
	-- 19. Расчеты по налогу
	------------------------------------------------
	
	-- задолженность по ндфл на начало месяца
	--------
	
	CREATE  TABLE #NALOG_RASH (Mode int, S_JAN NUMERIC(10,2), S_FEB NUMERIC(10,2), S_MART NUMERIC(10,2), S_APR NUMERIC(10,2), S_MAY NUMERIC(10,2), S_JUN NUMERIC(10,2),S_JUL NUMERIC(10,2),S_AUG NUMERIC(10,2), S_SEN NUMERIC(10,2),S_OKT NUMERIC(10,2), S_NOV NUMERIC(10,2), S_DEC NUMERIC(10,2),SNN NUMERIC(10,2), SNU NUMERIC(10,2), DOLG_NAEND NUMERIC(10,2), DOLG_NPEND NUMERIC(10,2))
	insert into #NALOG_RASH
	SELECT		
		MODE = 1,
		S_JAN = 0 , 
		S_FEB = 0 , 
		S_MART = 0, 
		S_APR = 0, 
		S_MAY = 0, 
		S_JUN = 0,
		S_JUL = 0,
		S_AUG = 0, 
		S_SEN = 0,
		S_OKT = 0, 
		S_NOV = 0, 
		S_DEC = 0,
		snn = 0,
		snu = 0,
		DOLG_NAEND  = 0,
		DOLG_NPEND = 0

	
	-- за налогоплательщиком долг если в плюсе
	-- если в минусе то за налоговым агентом
		
	UPDATE #NALOG_RASH 
	set S_JAN = round(isnull(((n1.s_jan + n2.s_jan) - (U1.s_jan + U2.s_jan)  ),0),0) ,
		S_FEB = round(isnull(((n1.S_FEB + n2.S_FEB) - (U1.S_FEB + U2.S_FEB) ),0),0),
		S_MART= round(isnull(((n1.S_MART + n2.S_MART) - (U1.S_MART + U2.S_MART)),0),0),
		S_APR = round(isnull(((n1.S_APR + n2.S_APR) - (U1.S_APR + U2.S_APR)),0),0),
		S_MAY = round(isnull(((n1.S_MAY + n2.S_MAY) - (U1.S_MAY + U2.S_MAY)),0),0),
		S_JUN = round(isnull(((n1.S_JUN + n2.S_JUN) - (U1.S_JUN + U2.S_JUN)),0),0),
		S_JUL = round(isnull(((n1.S_JUL + n2.S_JUL) - (U1.S_JUL + U2.S_JUL)),0),0),
		S_AUG = round(isnull(((n1.S_AUG + n2.S_AUG) - (U1.S_AUG + U2.S_AUG)),0),0),
		S_SEN = round(isnull(((n1.S_SEN + n2.S_SEN) - (U1.S_SEN + U2.S_SEN)),0),0),
		S_OKT = round(isnull(((n1.S_OKT + n2.S_OKT) - (U1.S_OKT + U2.S_OKT)),0),0),
		S_NOV = round(isnull(((n1.S_NOV + n2.S_NOV) - (U1.S_NOV + U2.S_NOV)),0),0),
		S_DEC = round(isnull(((n1.S_DEC + n2.S_DEC) - (U1.S_DEC + U2.S_DEC)),0),0),
		
	 SNN = (COALESCE(Sn1.S_DEC,0)+COALESCE(Sn2.S_DEC,0)),
							
	 SNU = (COALESCE(SU1.S_DEC,0)+COALESCE(SU2.S_DEC,0))
	
	from #NDFL_13_i N1, #Dohod_35_i  N2 , #NDFL_13_i U1, #Dohod_35_i  U2, #NDFL_13_i SN1, #Dohod_35_i  SN2 ,  #NDFL_13_i SU1, #Dohod_35_i  SU2
		where n1.mode = 6
		  and n2.mode = 5 
		  and U1.MODE = 8
		  AND U2.MODE = 4	
		  AND Sn1.mode = 5
		  and Sn2.mode = 8 
		  and SU1.MODE = 7
		  AND SU2.MODE = 3	
		  
			
	-- долг за налоговым агентом		
	UPDATE #NALOG_RASH  SET DOLG_NPEND = SNN - SNU, DOLG_NAEND = 0
	-- долг за налогоплательщиком
	UPDATE #NALOG_RASH SET DOLG_NAEND = -DOLG_NPEND, DOLG_NPEND = 0 WHERE DOLG_NPEND <0

	insert into #NALOG_RASH
	SELECT		
		MODE = 2,
		S_JAN = 0 , 
		S_FEB = 0 , 
		S_MART = 0, 
		S_APR = 0, 
		S_MAY = 0, 
		S_JUN = 0,
		S_JUL = 0,
		S_AUG = 0, 
		S_SEN = 0,
		S_OKT = 0, 
		S_NOV = 0, 
		S_DEC = 0,
		snn = 0,
		snu = 0,
		DOLG_NAEND  = 0,
		DOLG_NPEND = 0

	
	-- за налогоплательщиком долг если в плюсе
	-- если в минусе то за налоговым агентом
		
	UPDATE #NALOG_RASH 
	set S_JAN = case when isnull((select top 1 s_jan from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select top 1 s_jan from #NALOG_RASH where mode = 1),0) end ,
		S_FEB = case when isnull((select top 1 S_FEB from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select top 1 S_FEB from #NALOG_RASH where mode = 1),0) end ,
		S_MART= case when isnull((select top 1 S_MART from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select top 1 S_MART from #NALOG_RASH where mode = 1),0) end ,
		S_APR = case when isnull((select top 1 S_APR from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select top 1 S_APR from #NALOG_RASH where mode = 1),0) end ,
		S_MAY = case when isnull((select top 1 S_MAY from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select top 1 S_MAY from #NALOG_RASH where mode = 1),0) end ,
		S_JUN = case when isnull((select top 1 S_JUN from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select top 1 S_JUN from #NALOG_RASH where mode = 1),0) end ,
		S_JUL = case when isnull((select top 1 S_JUL from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select top 1 S_JUL from #NALOG_RASH where mode = 1),0) end ,
		S_AUG = case when isnull((select top 1 S_AUG from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select top 1 S_AUG from #NALOG_RASH where mode = 1),0) end ,
		S_SEN = case when isnull((select top 1 S_SEN from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select top 1 S_SEN from #NALOG_RASH where mode = 1),0) end ,
		S_OKT = case when isnull((select top 1 S_OKT from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select top 1 S_OKT from #NALOG_RASH where mode = 1),0) end ,
		S_NOV = case when isnull((select top 1 S_NOV from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select top 1 S_NOV from #NALOG_RASH where mode = 1),0) end ,
		S_DEC = case when isnull((select top 1 S_DEC from #NALOG_RASH where mode = 1),0) > 0 then 0 else isnull((select top 1 S_DEC from #NALOG_RASH where mode = 1),0) end ,
		
	 SNN = SNN,
							
	 SNU = SNU
	
	from #NALOG_RASH
		where mode = 2 
		 
			
	-- долг за налоговым агентом		
	UPDATE #NALOG_RASH  SET DOLG_NPEND = SNN - SNU, DOLG_NAEND = 0
	-- долг за налогоплательщиком
	UPDATE #NALOG_RASH SET DOLG_NAEND = -DOLG_NPEND, DOLG_NPEND = 0 WHERE DOLG_NPEND <0

 ----Начислено НДФЛ всего, в том числе по ставкам
	INSERT INTO #NALOG_RASH (Mode, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL, S_AUG, S_SEN ,S_OKT, S_NOV, S_DEC, SNN, SNU, DOLG_NAEND, DOLG_NPEND)
	SELECT 3, 
		0, 
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0
		 
		
	UPDATE #NALOG_RASH 
	set S_JAN = (select (n1.s_jan + n2.s_jan) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4),
		S_FEB = (select (n1.S_FEB + n2.S_FEB) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_MART =(select (n1.S_MART + n2.S_MART) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_APR = (select (n1.S_APR + n2.S_APR) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_MAY = (select (n1.S_MAY + n2.S_MAY) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_JUN = (select (n1.S_JUN + n2.S_JUN) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_JUL = (select (n1.S_JUL + n2.S_JUL) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_AUG = (select (n1.S_AUG + n2.S_AUG) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_SEN = (select (n1.S_SEN + n2.S_SEN) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_OKT = (select (n1.S_OKT + n2.S_OKT) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_NOV = (select (n1.S_NOV + n2.S_NOV) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 ),
		S_DEC = (select (n1.S_DEC + n2.S_DEC) from #NDFL_13_i N1, #Dohod_35_i  N2 where n1.mode = 6 and n2.mode = 4 )
	FROM #NALOG_RASH
		where Mode = 3
	--- 13%
	
	INSERT INTO #NALOG_RASH (Mode, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL, S_AUG, S_SEN ,S_OKT, S_NOV, S_DEC, SNN, SNU, DOLG_NAEND, DOLG_NPEND)
	SELECT 4, 
		0, 
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0
	
	if @varKSCOEFF = 0.13
	begin	
		UPDATE #NALOG_RASH 
		set S_JAN = (select top 1 s_jan from #NDFL_13_i where mode = 6),
			S_FEB = (select top 1 S_FEB from #NDFL_13_i where mode = 6),
			S_MART =(select top 1 S_MART from #NDFL_13_i where mode = 6),
			S_APR = (select top 1 S_APR from #NDFL_13_i where mode = 6),
			S_MAY = (select top 1 S_MAY from #NDFL_13_i where mode = 6),
			S_JUN = (select top 1 S_JUN from #NDFL_13_i where mode = 6),
			S_JUL = (select top 1 S_JUL from #NDFL_13_i where mode = 6),
			S_AUG = (select top 1 S_AUG from #NDFL_13_i where mode = 6),
			S_SEN = (select top 1 S_SEN from #NDFL_13_i where mode = 6),
			S_OKT = (select top 1 S_OKT from #NDFL_13_i where mode = 6),
			S_NOV = (select top 1 S_NOV from #NDFL_13_i where mode = 6),
			S_DEC = (select top 1 S_DEC from #NDFL_13_i where mode = 6),


		 SNN = (SELECT TOP 1 COALESCE(S_DEC,0) FROM #NDFL_13_i where mode = 5),
								
		 SNU = (SELECT TOP 1 COALESCE(S_DEC,0) FROM #NDFL_13_i where mode = 7)
		from #NALOG_RASH 
			where Mode = 4	

		UPDATE #NALOG_RASH  SET DOLG_NPEND = SNN - SNU, DOLG_NAEND = 0
		from #NALOG_RASH 
			where Mode = 4	
		
		UPDATE #NALOG_RASH 
			SET DOLG_NAEND = -DOLG_NPEND, DOLG_NPEND = 0 
		from #NALOG_RASH 
			where Mode = 4	
			and DOLG_NPEND <0
	end
		
	-- 35%	
	INSERT INTO #NALOG_RASH (Mode, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL, S_AUG, S_SEN ,S_OKT, S_NOV, S_DEC, SNN, SNU, DOLG_NAEND, DOLG_NPEND)
	SELECT 5, 
		0, 
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0
		
	UPDATE #NALOG_RASH 
	set S_JAN = (select top 1 s_jan from #Dohod_35_i  where mode = 4),
		S_FEB = (select top 1 S_FEB from #Dohod_35_i  where mode = 4),
		S_MART =(select top 1 S_MART from #Dohod_35_i  where mode = 4),
		S_APR = (select top 1 S_APR from #Dohod_35_i  where mode = 4),
		S_MAY = (select top 1 S_MAY from #Dohod_35_i  where mode = 4),
		S_JUN = (select top 1 S_JUN from #Dohod_35_i  where mode = 4),
		S_JUL = (select top 1 S_JUL from #Dohod_35_i  where mode = 4),
		S_AUG = (select top 1 S_AUG from #Dohod_35_i  where mode = 4),
		S_SEN = (select top 1 S_SEN from #Dohod_35_i  where mode = 4),
		S_OKT = (select top 1 S_OKT from #Dohod_35_i  where mode = 4),
		S_NOV = (select top 1 S_NOV from #Dohod_35_i  where mode = 4),
		S_DEC = (select top 1 S_DEC from #Dohod_35_i  where mode = 4),
	
	 SNN = (SELECT TOP 1 COALESCE(S_DEC,0) FROM #Dohod_35_i  where mode = 3 ),
							
	 SNU = (SELECT TOP 1 COALESCE(S_DEC,0) FROM #Dohod_35_i  where mode = 8 )
	from #NALOG_RASH 
		where Mode = 5
		
	UPDATE #NALOG_RASH  SET DOLG_NPEND = SNN - SNU, DOLG_NAEND = 0
	from #NALOG_RASH 
		where Mode = 5
	
	UPDATE #NALOG_RASH SET DOLG_NAEND = -DOLG_NPEND, DOLG_NPEND = 0 
	from #NALOG_RASH 
		where Mode = 5	and DOLG_NPEND <0

	-- 30%
	INSERT INTO #NALOG_RASH (Mode, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL, S_AUG, S_SEN ,S_OKT, S_NOV, S_DEC, SNN, SNU, DOLG_NAEND, DOLG_NPEND)
	SELECT 6, 
		0, 
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0
	
	if @varKSCOEFF = 0.30
	begin	
		UPDATE #NALOG_RASH 
		set S_JAN = (select top 1  s_jan from #NDFL_13_i where mode = 6),
			S_FEB = (select top 1  S_FEB from #NDFL_13_i where mode = 6),
			S_MART =(select top 1  S_MART from #NDFL_13_i where mode = 6),
			S_APR = (select top 1  S_APR from #NDFL_13_i where mode = 6),
			S_MAY = (select top 1  S_MAY from #NDFL_13_i where mode = 6),
			S_JUN = (select top 1 S_JUN from #NDFL_13_i where mode = 6),
			S_JUL = (select top 1 S_JUL from #NDFL_13_i where mode = 6),
			S_AUG = (select top 1 S_AUG from #NDFL_13_i where mode = 6),
			S_SEN = (select top 1 S_SEN from #NDFL_13_i where mode = 6),
			S_OKT = (select top 1 S_OKT from #NDFL_13_i where mode = 6),
			S_NOV = (select top 1 S_NOV from #NDFL_13_i where mode = 6),
			S_DEC = (select top 1 S_DEC from #NDFL_13_i where mode = 6),


		 SNN = (SELECT TOP 1 COALESCE(S_DEC,0) FROM #NALOG_RASH where mode = 5),
								
		 SNU = (SELECT TOP 1 COALESCE(S_DEC,0) FROM #NDFL_13_i where mode = 7)
		from #NALOG_RASH 
			where Mode = 4	

		UPDATE #NALOG_RASH  SET DOLG_NPEND = SNN - SNU, DOLG_NAEND = 0
		from #NALOG_RASH 
			where Mode = 4	
		
		UPDATE #NALOG_RASH 
			SET DOLG_NAEND = -DOLG_NPEND, DOLG_NPEND = 0 
		from #NALOG_RASH 
			where Mode = 4	
			and DOLG_NPEND <0
	end

	-- 15%
	INSERT INTO #NALOG_RASH
	SELECT 7, 
		0, 
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0
	-- 9%
	INSERT INTO #NALOG_RASH
	SELECT 8, 
		0, 
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0
	
	-- 6%
	INSERT INTO #NALOG_RASH
	SELECT 9, 
		0, 
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0
	
	-- Удержано НДФЛ	
	INSERT INTO #NALOG_RASH (Mode, S_JAN, S_FEB, S_MART, S_APR, S_MAY, S_JUN,S_JUL, S_AUG, S_SEN ,S_OKT, S_NOV, S_DEC, SNN, SNU, DOLG_NAEND, DOLG_NPEND)
	SELECT 10, 
		0, 
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0

		
	UPDATE #NALOG_RASH 
	set S_JAN = isnull((select U1.s_jan + U2.s_jan  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5 ),0),
		S_FEB = isnull((select U1.S_FEB + U2.S_FEB  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_MART = isnull((select U1.S_MART + U2.S_MART  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_APR = isnull((select U1.S_APR + U2.S_APR  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_MAY = isnull((select U1.S_MAY + U2.S_MAY  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_JUN = isnull((select U1.S_JUN + U2.S_JUN  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_JUL = isnull((select U1.S_JUL + U2.S_JUL  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_AUG = isnull((select U1.S_AUG + U2.S_AUG  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_SEN = isnull((select U1.S_SEN + U2.S_SEN  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_OKT = isnull((select U1.S_OKT + U2.S_OKT  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_NOV = isnull((select U1.S_NOV + U2.S_NOV  from #NDFL_13_i U1, #Dohod_35_i  U2 where u1.mode = 8 and u2.mode = 5),0),
		S_DEC = isnull((select U1.S_DEC + U2.S_DEC  from #NDFL_13_i U1, #Dohod_35_i  U2	where u1.mode = 8 and u2.mode = 5),0)
	from #NALOG_RASH 
		where Mode = 10		

-------------------------------------------------------		
-- 20. Общая сумма налога по итогам налогового периода
-------------------------------------------------------
	CREATE  TABLE #ALL_NALOG_Y (PER_Stav varchar(4), S_NN NUMERIC(10,2), S_NU NUMERIC(10,2), S_PERECH NUMERIC(10,2), S_PERED NUMERIC(10,2), S_VOZV NUMERIC(10,2), S_ZACH NUMERIC(10,2),DOLG_NP NUMERIC(10,2),DOLG_NA NUMERIC(10,2))
	insert into #ALL_NALOG_Y
	SELECT		
		PER_STAV = '6%',
		S_NN = (SELECT TOP 1 SNN FROM #NALOG_RASH where mode = 9),
		S_NU = (SELECT TOP 1 SNU FROM #NALOG_RASH where mode = 9) ,
		S_PERECH =  case when isnull((select top 1  s_jan from #NALOG_RASH where mode = 9),0) > 0 then (SELECT TOP 1 S_DEC FROM #NDFL_13_i where mode = 10) else 0 end ,
		S_PERED = 0,
		S_VOZV = 0,
		S_ZACH = 0,
		DOLG_NP = 0,
		DOLG_NA = 0
		
	UPDATE #ALL_NALOG_Y 
	SET DOLG_NP = S_NN - S_NU,  
		DOLG_NA = 0
	from #ALL_NALOG_Y 
	where PER_STAV = '6%'	
			
	UPDATE #ALL_NALOG_Y 
	SET DOLG_NA = -DOLG_NP,
		DOLG_NP = 0
	from #ALL_NALOG_Y 
	where PER_STAV = '6%'	
		and DOLG_NP <0		
	---
	insert into #ALL_NALOG_Y
	SELECT		
		PER_STAV = '9%',
		S_NN = (SELECT TOP 1 SNN FROM #NALOG_RASH where mode = 8),
		S_NU = (SELECT TOP 1 SNU FROM #NALOG_RASH where mode = 8) ,
		S_PERECH = case when isnull((select top 1  s_jan from #NALOG_RASH where mode = 8),0) > 0 then (SELECT TOP 1 S_DEC FROM #NDFL_13_i where mode = 10) else 0 end ,
		S_PERED = 0, 
		S_VOZV = 0, 
		S_ZACH = 0, 
		DOLG_NP = 0,
		DOLG_NA = 0	
	
	UPDATE #ALL_NALOG_Y 
	SET DOLG_NP = S_NN - S_NU,  
		DOLG_NA = 0
	from #ALL_NALOG_Y 
	where PER_STAV = '9%'	
			
	UPDATE #ALL_NALOG_Y 
	SET DOLG_NA = -DOLG_NP,
		DOLG_NP = 0
	from #ALL_NALOG_Y 
	where PER_STAV = '9%'	
		and DOLG_NP <0	
	
	---
	insert into #ALL_NALOG_Y
	SELECT		
		PER_STAV = '13%',
		S_NN = 0 ,
		S_NU = 0 ,
		S_PERECH = 0 , 
		S_PERED = 0, 
		S_VOZV = 0, 
		S_ZACH = 0, 
		DOLG_NP = 0,
		DOLG_NA = 0	
	
	if @varKSCOEFF = 0.13
	begin	
		UPDATE #ALL_NALOG_Y 
		set S_NN = (SELECT TOP 1 SNN FROM #NALOG_RASH where mode = 4),
			S_NU = (SELECT TOP 1 SNU FROM #NALOG_RASH where mode = 4) ,
			S_PERECH = case when isnull((select top 1  s_jan from #NALOG_RASH where mode = 4),0) > 0 then (SELECT TOP 1 S_DEC FROM #NDFL_13_i where mode = 10) else 0 end ,
			S_PERED = 0,
			S_VOZV = 0,
			S_ZACH = 0
		from #ALL_NALOG_Y 
			where PER_STAV = '13%'	
		
			UPDATE #ALL_NALOG_Y 
			SET DOLG_NP = S_NN - S_NU,  
				DOLG_NA = 0
			from #ALL_NALOG_Y 
				where PER_STAV = '13%'	
			
			UPDATE #ALL_NALOG_Y 
				SET DOLG_NA = -DOLG_NP,
					DOLG_NP = 0
			from #ALL_NALOG_Y 
				where PER_STAV = '13%'	
				and DOLG_NP <0	
	end
	----
	
	insert into #ALL_NALOG_Y
	SELECT		
		PER_STAV = '15%',
		S_NN = (SELECT TOP 1 SNN FROM #NALOG_RASH where mode = 7),
		S_NU = (SELECT TOP 1 SNU FROM #NALOG_RASH where mode = 7) ,
		S_PERECH = case when isnull((select top 1  s_jan from #NALOG_RASH where mode = 7),0) > 0 then (SELECT TOP 1 S_DEC FROM #NDFL_13_i where mode = 10) else 0 end , 
		S_PERED = 0, 
		S_VOZV = 0, 
		S_ZACH = 0, 
		DOLG_NP = 0,
		DOLG_NA = 0	
	
	UPDATE #ALL_NALOG_Y 
	SET DOLG_NP = S_NN - S_NU,  
		DOLG_NA = 0
	from #ALL_NALOG_Y 
	where PER_STAV = '15%'	
			
	UPDATE #ALL_NALOG_Y 
	SET DOLG_NA = -DOLG_NP,
		DOLG_NP = 0
	from #ALL_NALOG_Y 
	where PER_STAV = '15%'	
		and DOLG_NP <0	
	----
	insert into #ALL_NALOG_Y
	SELECT		
		PER_STAV = '30%',
		S_NN = 0 ,
		S_NU = 0 ,
		S_PERECH = 0 , 
		S_PERED = 0, 
		S_VOZV = 0, 
		S_ZACH = 0, 
		DOLG_NP = 0,
		DOLG_NA = 0	

	if @varKSCOEFF = 0.30
	begin	
			
		UPDATE #ALL_NALOG_Y 
		set S_NN = (SELECT TOP 1 SNN FROM #NALOG_RASH where mode = 6),
			S_NU = (SELECT TOP 1 SNU FROM #NALOG_RASH where mode = 6),
			S_PERECH = case when isnull((select top 1  s_jan from #NALOG_RASH where mode = 6),0) > 0 then (SELECT TOP 1 S_DEC FROM #NDFL_13_i where mode = 10) else 0 end ,
			S_PERED = 0,
			S_VOZV = 0,
			S_ZACH = 0
		from #ALL_NALOG_Y 
			where PER_STAV = '30%'	
		
			UPDATE #ALL_NALOG_Y 
			SET DOLG_NP = S_NN - S_NU,  
				DOLG_NA = 0
			from #ALL_NALOG_Y 
				where PER_STAV = '30%'	
			
			UPDATE #ALL_NALOG_Y 
				SET DOLG_NA = -DOLG_NP,
					DOLG_NP = 0
			from #ALL_NALOG_Y 
				where PER_STAV = '30%'	
				and DOLG_NP <0		
	end
	---
		
	insert into #ALL_NALOG_Y
	SELECT		
		PER_STAV = '35%',
		S_NN = 0  ,
		S_NU = 0 ,
		S_PERECH = 0 , 
		S_PERED = 0, 
		S_VOZV = 0, 
		S_ZACH = 0, 
		DOLG_NP = 0,
		DOLG_NA = 0	
	
	UPDATE #ALL_NALOG_Y 
		set	S_NN = (SELECT TOP 1 SNN FROM #NALOG_RASH where mode = 5),
			S_NU = (SELECT TOP 1 SNU FROM #NALOG_RASH where mode = 5),
			S_PERECH = case when isnull((select top 1  s_jan from #NALOG_RASH where mode = 5),0) > 0 then (SELECT TOP 1 S_DEC FROM #Dohod_35_i where mode = 8) else 0 end 
		from #ALL_NALOG_Y 
		where PER_STAV = '35%'
		
	UPDATE #ALL_NALOG_Y 
		SET DOLG_NP = S_NN - S_NU, DOLG_NA = 0
		from #ALL_NALOG_Y where PER_STAV = '35%'	
			
	UPDATE #ALL_NALOG_Y 
		SET DOLG_NA = -DOLG_NP, DOLG_NP = 0
		from #ALL_NALOG_Y where PER_STAV = '35%' and DOLG_NP <0		
	
-------------------------------------------------------	

	
--print '1. Налоговый агент и Налогоплательщик'
	---
	SELECT  d.*, CAST(  (CAST (d.DOCCOUNT AS INT) - @varKSCNT) AS VARCHAR(254) ) AS DOCCOUNT2 , r.* FROM #DEP d , #PERSON R  
	---

--print 'Дети'	
--print '3.  Стандартный налоговый вычет'	
	declare @count1 int,
			@count2 int
	set @count1 = 0			
 
	SELECT * FROM #RES_VICHET

	
--print 'Имущественный налоговый вычет'	
	set @count1 = 0			
	set @count1 = (SELECT count(*)	FROM #RES_IM_VICHET)		
	
	if 	@count1 < 1
	begin 
		insert into #RES_IM_VICHET
		select distinct	
			 null,null,null,' ',null,' ',' ',null,null,null,null,0,null,null
	end 
	select * from #RES_IM_VICHET
		order by code_ded

--print '4. Необлагаемые доходы'
	set @count1 = 0			
	set @count1 = (SELECT count(*)	FROM #RES_NE_VICHET)		
	
	if 	@count1 < 1
	begin 
		insert into #RES_NE_VICHET
		select distinct	
			 '',null,null,null,null,0,0,0,0,0,0,0,0,0,0,0,0 
	end 
	select * from #RES_NE_VICHET
					
	--select * from #RES_NonNDFL_VICHET
--print '5. Налоговые ставки'	
	
--print 'и Таблица 5.2 Виды доходов (доходы не по ставке 13%)'
	--select * from #RES_EMP_STATUS
	
	set @count1 = (select count(*) from #RES_EMP_STATUS )
	set @count2 = (select count(*) from #vid_dohod_not13 ) 

	if @count1 > 0 and @count1 >= @count2 
	begin
		update #RES_EMP_STATUS 
		set month_d = v.month_d, 
	   		year_d = v.year_d,
	   		link_inc = v.link_inc,
	   		link_dep = v.link_dep,
	   		sname = v.sname,
	   		name = v.name,
	   		flag = v.flag,
	   		perc_stav = v.perc_stav
		 from #RES_EMP_STATUS r, #vid_dohod_not13 v 
		 where v.year_d = @cYear	
	end  
	else	
		begin
			insert into #RES_EMP_STATUS 
			select distinct	
			   null, 
			   null,
			   null, 
			   null,
			   NULL,
			   [month_d] = v.month_d, 
	   		   [year_d] = v.year_d,
	   		   [link_inc] = v.link_inc,
	   		   [link_dep] = v.link_dep,
	   		   [sname] = v.sname,
	   		   [name] = v.name,
	   		   [flag] = v.flag,
	   		   [perc_stav] = v.perc_stav
			FROM 
				#vid_dohod_not13 v
	  end	

	select * from #RES_EMP_STATUS 


	--select * from  #vid_dohod_not13
	
--print '6.предыдущее место работы'	
	declare @countPrevInfo int
	set @countPrevInfo = 0
	set @countPrevInfo = (SELECT count(*)	FROM #DEP_Prev)
	
	if 	@countPrevInfo < 1
	begin 
		insert into #DEP_Prev
		select distinct	
			[LINK_DEP] = null,[NALOG] = ' ',[INN] = ' ',[KPP] = ' ',[OKATO] = ' ',[OKTMO] = ' ',[FULL_NAME] = ' ',[ADDRES] = ' ',[SUMMA_13]= 0
	end 
	SELECT * FROM #DEP_Prev
		
	
--print ' Сумма доходов, облагаемых по ставке 13% '	
	--set @count1 = 0
	--set @count1 = (SELECT count(*)	FROM #Prev_dohod)
	
	--if 	@count1 < 1
	--begin 
	--	insert into #Prev_dohod
	--	select distinct	
	--		[LINK_EMPL] = 1,
	--		[REF_TYP_INCOMS] = 0, 
	--		[COD_INC] = '.',
	--		[NAME_INC] = '.',
	--	    [SUMM_INC] = 0
	--end 
	--select * from #Prev_dohod	

--print ' Сумма необлагаемых доходов по ставке 13% '	
	set @count1 = 0
	if	@countPrevInfo < 1
	begin 
		delete from #Prev_dohod_NO
	end	
	
	set @count1 = (SELECT count(*)	FROM #Prev_dohod_NO)

	if 	@count1 < 1 
	begin 
		insert into #Prev_dohod_NO
		select distinct	
			[LINK_EMPL] = 0,[REF_TYP_INCOMS] = ' ',	[COD_INC] = ' ',[NAME_INC] = ' ', [SUMM_INC] = 0, [PER_YEAR] = ' '
	end 
	select * from #Prev_dohod_NO	
	
--print 'Налоговые вычеты с предыдущего места работы по типам'
	set @count1 = 0

	if	@countPrevInfo < 1
	begin 
		delete from #Prev_ded
	end	
	
	set @count1 = (SELECT count(*)	FROM #Prev_ded)
	
	if 	@count1 < 1 or 	@countPrevInfo < 1
	begin 
		insert into #Prev_ded
		select distinct	
			[LINK_EMPL] = 0,[LINK_DED] = 0,[CODE_DED] = ' ',[NAME_DED] = ' ',[SUMM_DED] = 0,[TYPE] = null,[PER_YEAR] = null
	end 	
	select * from #Prev_ded
--print '7. доходы облагаемые по ставке 13%'  	
--	select * from #Dohod_13	
	set @count1 = 0
	set @count1 = (SELECT count(*)	FROM #Dohod_13_1)
	
	if 	@count1 < 1
	begin 
		insert into #Dohod_13_1
		select 
			null,' ',' ',null,null,null,0,null,null,0,null,null,0,null,null,0,null,null,0,null,null,0,
			null,null,0,null,null,0,null,null,0,null,null,0,null,null,0,null,null,0																							
	end 	
	select * from #Dohod_13_1
--print ' Итого 13% месяц и год '
	select * from #Dohod_13_i
--print '8. необлагаемые суммы налогов'  
	set @count1 = 0
	set @count1 = (SELECT count(*)	FROM #Dohod_13_predel)
	if 	@count1 < 1
	begin 
		insert into #Dohod_13_predel
		select
			null, 
			null, 
			null, 
			0,
			0,
            0,          
            0,    
			0,        
            0,          
            0,          
            0,        
            0,      
            0,         
            0,         
            0,          
            0	
    end  
	select * from #Dohod_13_predel
--print ' Итого месяц и год'	
	select * from #Dohod_13_predel_i
--print '9. Сумма облагаемых доходов (месяц и год)'
	select * from #Obl_Dohod_i
--print '10. Вычеты фактически предоставленные , стандартные, имущестевнные, проффессиональные'
	set @count1 = 0
	set @count1 = (SELECT count(*)	FROM #DED_FACT)
	if 	@count1 < 1
	begin 
		insert into #DED_FACT
		select
			null, 
			null, 
			null, 
			null,
			null,
            null,          
            null,         
       null,        
            0,          
            null,          
            null,        
            0,      
            null,         
            null,         
            0,          
            null,	
            null,        
            0,      
            null,         
            null,         
            0,          
            null,
            null,        
            0,      
            null,         
            null,         
            0,          
            null,
            null,        
            0,      
            null,         
            null,         
            0,          
            null,
            null,        
            0,      
            null,         
            null,         
            0,          
            null,
            null,         
            0,       
            null
    end  
	select * from #DED_FACT 
--	select * from #DED_FACT_i
--	select * from #OBL_base_fi
		-- итоги по месяцам и за год 
		--	 mode = 1 и mode = 2
		
--print '11.Облагаемая база ставка 13% ' 	
		-- итоги по месяцам и за год 
		--	 mode = 3 и mode = 4
--print '12.НДФЛ по ставке 13% 	--сумма начисленного налого С НАЧАЛА ГОДА , за месяц'
		-- за месяц и год по начисленным 	 mode = 5 и mode = 6
		-- за месяц и год по удержанным 	 mode = 7 и mode = 8
		select * from #NDFL_13_i  order by mode

--print '13. Перечисление НДФЛ по ставке 13% --сумма перечисленного налога С НАЧАЛА ГОДА , за месяц'



--print '15.ДОходы, облагаемая база со ставкой  35%'
	set @count1 = 0
	set @count1 = (SELECT count(*)	FROM #Dohod_35)
	
	if 	@count1 < 1
	begin 
		insert into #Dohod_35_m
		select 
		   [link_empl] = 1,  
		   [name]  = ' ', 
		   [sname] = ' ', 
		   [link_inc] = null,	
		   [NUM1] = null,
		   [summa_1] = null,
		   [d1] = null,
		   [num2] = null,
		   [summa_2] = null,
		   [d2] = null,
		   [num3] = null,
		   [summa_3] = null,
		   [d3] = null,
		   [num4] = null,
		   [summa_4] = null,
		   [d4] = null,
		   [num5]= null,
		   [summa_5] = null,
		   [d5] = null,
		   [num6]= null,
		   [summa_6] = null,
		   [d6] = null,
		   [num7]= null,
		   [summa_7]  = null,
		   [d7] = null,
		   [num8]= null,
		   [summa_8]  = null,
		   [d8]  = null,
		   [num9]= null,
		   [summa_9] = null,
		   [d9] = null,
		   [num10]= null,
		   [summa_10] = null,
		   [d10] = null,
		   [num11]= null,
		   [summa_11] = null,
		   [d11] = null,
		   [num12]= null,
		   [summa_12] = null ,
		   [d12] = null 
		    
	end		   
---	select * from #Dohod_35
	select * from #Dohod_35_m
--print 'Итого за месяц'	
--print '16.НДФЛ по ставке 13 %'
	select * from #Dohod_35_i
--print '17.Расчеты по налогу  и 20. общая сумма по итогам налогового периода '	
	select * from #NALOG_RASH	
	select * from #ALL_NALOG_Y

	---	

	---
	EXEC dbo.BufferClear

	DROP TABLE #E_SUBDIV
	DROP TABLE #S_OBOSOB
	DROP TABLE #P_OBOSOB	
	DROP TABLE #PERSON
	DROP TABLE #RES_VICHET
--	DROP TABLE #RES_CHILD_VICHET
	DROP TABLE #RES_IM_VICHET
	DROP TABLE #RES_NE_VICHET
	--DROP TABLE #RES_NonNDFL_VICHET
	DROP TABLE #RES_EMP_STATUS
	drop table #vid_dohod_not13
	DROP TABLE #DEP_Prev
	DROP TABLE #Prev_dohod	
	DROP TABLE #Prev_dohod_NO
	DROP TABLE #Prev_ded
	DROP TABLE #Dohod_13
	DROP TABLE #Dohod_13_1
	drop table #Dohod_13_predel
	drop table #Dohod_13_i
	drop table #Dohod_13_predel_i
	drop table #Obl_Dohod_i
	drop table #DED_FACT 
--	drop table #DED_FACT_i
--	drop table #OBL_base_fi

	drop table #NDFL_13_i

	drop table #Dohod_35
	drop table #Dohod_35_m
	drop table #Dohod_35_i

	drop table #MONTHES
	drop table #NALOG_RASH	
	drop table #ALL_NALOG_Y	


END





GO


GRANT EXECUTE ON dbo.[SS_REP_CARD_NDFL] TO PUBLIC

GO




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

CREATE PROCEDURE dbo.BV_AVANSE_SELECT_TABLE
	@intDocLink int
AS
BEGIN
	SELECT *
	FROM dbo.BK_DOC_TABLE_AO_FN (@intDocLink)
END

GO

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

	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)

--Выводить вместо подписи лицевой счёт
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_UP, LINK_EKR, SUM(DISBURS) AS SUMM
	INTO #SUM_EKR
	FROM #SDOC_VEDOM_TABLE1
	GROUP BY LINK_EMPL, LINK_UP, LINK_EKR 

	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
)
	

	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)),
		LEFT(ISNULL(P.DOC_NUM, ''),20),
		LEFT(@ORGNAME,254),
		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
	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
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_WARNINGS OFF
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RT_CALC_0503125G]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RT_CALC_0503125G]
GO

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

CREATE PROCEDURE dbo.RT_CALC_0503125G
@LSF int,
@table int
AS

declare @cAccount varchar(9),  -- девять знаков: [1] - код вида деятельности [2..6] - счёт(синт+ан) [7..9] - СГУ
		@cSource char(1),
		@cSinth char(3),
		@cAnalit char(2),
		@cSGU char(3),
		@iLinkAccount int,
		@dBeginDate datetime,
		@dEndDate datetime,
		@dEndDate_pl datetime,
		@iThisDep int,
		@iCorrDep int,
		@i int,
		@j int,
		@iLink_col int,
		@code_row varchar(50),
		@float_val numeric(20,4),
		@str_val varchar(250),
		@cVidForm varchar(250),
		@cVidFormCode tinyint,
		@nPeriod_Type tinyint,
		@cStrSql varchar(8000),
		@nabor_filter varchar(100)
		
declare @table1 table(key_prov int, kbk int, account int, sgu int, db_kr tinyint, account_korr int, sgu_korr int, kpb_korr int, summa numeric(20,4))
create table #table2(nn int IDENTITY(1,1),Name_bp varchar(254), kod_bp varchar(10), ppp char(3), el_bud char(2), okato char(11), KBK varchar(17), Code_Acc varchar(9), summa_db numeric(20,4), summa_kr numeric(20,4),korr_acc varchar(10), link varchar(254), dnd tinyint, key_prov int)
create table #table3(nn int IDENTITY(1,1),Name_bp varchar(254), kod_bp varchar(10), ppp char(3), el_bud char(2), okato char(11), KBK varchar(17), Code_Acc varchar(9), summa_db numeric(20,4), summa_kr numeric(20,4),korr_acc varchar(10), link varchar(254), dnd tinyint, key_prov int)
declare @filter_kbk table (kbk varchar(20))

-- вытаскиваем данные из сохранённой формы
set @cAccount = ltrim(rtrim(replace(dbo.RN_GET_ATR_VALUE(@LSF,'REPORTS_ATR_ACC_2011'),'.','')))
set @cSource = substring(@cAccount,1,1) -- вид деятельности
set @cSinth = substring(@cAccount,2,3)  -- синтетический счёт
set @cAnalit = substring(@cAccount,5,2) -- аналитическая составляющая
set @cSGU = substring(@cAccount,7,3)    -- СГУ

--set @cVidForm = ltrim(rtrim(dbo.RN_GET_ATR_VALUE(@LSF,'REPORTS_ATR_NAFO')))
--select @cVidFormCode = link from dbo.RT_VIEW_NAFO_125 where [Name] = @cVidForm

-- print '@cAccount = '+@cAccount
-- print '@cSource = '+@cSource
-- print '@cSinth = '+@cSinth
-- print '@cAnalit = '+@cAnalit
-- print '@cSGU = '+@cSGU
-- print '@cVidForm = '+@cVidForm
-- print '@cVidFormCode = '+cast(@cVidFormCode as varchar(3))

-- определяем период (если в январе формируем, то берём весь предыдущий год не включая 31 декабря)
select @dEndDate = Begin_Date, @nPeriod_Type = period_type from dbo.report_saved_forms where link_saved_form = @LSF

select @dBeginDate = dbo.DateBeginOfYear(@dEndDate)

-- set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then (@dBeginDate - (datepart(dd,@dBeginDate))) - 1 else @dBeginDate /*- (datepart(dd,@dBeginDate))*/ end
-- set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')


--if @nPeriod_Type <> 1 
--	set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then @dBeginDate - 1 else @dBeginDate end
--else
--	set @dEndDate = @dBeginDate
--
--	set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')

-- получаем линк указанного счёта
select @iLinkAccount = link from dbo.s_accounts
where cSource = @cSource
and cSinth = @cSinth
and cAnalit = @cAnalit

-- линк организации которая собственно формирует справку
select @iThisDep = Link_Organization from dbo.report_saved_forms where link_saved_form = @LSF

-- print '@dBeginDate = '+cast(@dBeginDate as varchar(100))
-- print '@dEndDate = '+cast(@dEndDate as varchar(100))
-- print '@iLinkAccount = '+cast(@iLinkAccount as varchar(10))
-- теперь надо получить список корресп. счетов
if (((@cSinth = '206' and @cAnalit = '51') or (@cSinth = '205' and @cAnalit = '51') or (@cSinth = '207' and (@cAnalit = '11' or @cAnalit = '12' or @cAnalit = '13'))) and @cSGU = '000') /*and @nPeriod_Type = 1*/ begin
	set @dEndDate_pl = dateadd(d,1,@dEndDate)
	insert into @table1
	select 1,kbk, account, sgu, 1, null, null, dep, /*d_summa - */k_summa - d_summa
	from dbo.ARestTableByDate(@dEndDate_pl, @iLinkAccount)
	where dep_link = @iThisDep
end
else begin
	insert into @table1
	select
	C.link,
	D.kbk,
	D.account,
	D.sgu,
	D.DB_KR,
	E.account,
	E.sgu,
	/* Boch, брать организацию из извещения
	(case
	when D.Dep is not NULL and D.Dep <> A.Dep then
	D.Dep
	else (case when E.Dep is not NULL and E.Dep <> A.Dep then E.Dep else NULL end)
	end) as kpb_korr,*/
	(case
	when D.Dep is not NULL and D.Dep <> A.Dep then D.Dep
	when E.Dep is not NULL and E.Dep <> A.Dep then E.Dep
	when OS.Dep_pass is not NULL and OS.Dep_pass <> A.Dep then OS.Dep_pass
	when OS.Dep_receive is not NULL and OS.Dep_receive <> A.Dep then OS.Dep_receive
	else isnull((SELECT GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA, dbo.S_OBJECTS SO WHERE GPDA.DOC_LINK = A.LINK AND GPDA.OBJECT = SO.LINK and SO.CODE = 'NOTICE_LINK_DEP_RECEIVER'), NULL) end)
	as kpb_korr,
	C.Summa
	from dbo.g_prov as A
	inner join dbo.g_prov1 as B
	on A.link = B.link_up
	and A.date_prov between @dBeginDate and @dEndDate
	and A.Dep = @iThisDep
	inner join dbo.g_prov2 as C
	on B.link = C.link_up
	inner join dbo.g_prov_ap as D
	on C.link = D.link_up
	inner join dbo.g_prov_ap as E
	on D.link_up = E.link_up
	and D.account <> E.account
	and D.account = @iLinkAccount
	and (D.sgu = (select link from dbo.kosgu where code = @cSGU) or '000' = @cSGU)
	left join dbo.G_PROV_OS1 OS on OS.LINK_OS1 = A.LINK
end
--select * from @table1

select @nabor_filter = REPLACE (dbo.rn_get_atr_value(@LSF,'REPORTS_FILTER_KBK'), 'Не отобрано', '')
insert @filter_kbk (kbk)   
Select LINK FROM rn_get_filter(@LSF,'REPORTS_FILTER_KBK')


-- теперь необходимо удалить из всего набора таблицы @table1 строчки с ненужными КБК (в зависимости от того для какой таблицы производится рассчёт)
delete from @table1
where kbk not in (select [LINK] 
					from dbo.kl_kbk K
					LEFT JOIN @filter_kbk F on K.LINK = F.KBK
					where @table = case when [TYPE] in (4,8) then 3 when [TYPE] = 1 then 2 when [TYPE] = 2 then 1 else [TYPE] end
					AND (F.kbk IS NULL OR isnull(@nabor_filter, '') = ''))

-- в таблице #table2
insert into #table2
select
(case
when exists(select [FULL_Name] from dbo.Departments where link = kpb_korr)
then (select [FULL_Name] from dbo.Departments where link = kpb_korr)
else 'корреспондент_не_указан'
end),
(case
when exists(select [CODE] from dbo.Departments where link = kpb_korr)
then (select [CODE] from dbo.Departments where link = kpb_korr)
else '0'
end),
(case
when exists(select [CODE] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr))
then (select [CODE] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr))
else '000'
end),
(case
when exists(select [CODE_EL] from dbo.kl_budg_type where link = (select top 1 [Link_Budg] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr)))
then (select [CODE_EL] from dbo.kl_budg_type where link = (select top 1 [Link_Budg] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr)))
else '00'
end),
--     (select [CODE] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr)),
--     (select [CODE_EL] from dbo.kl_budg_type where link = (select top 1 [Link_Budg] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr))),
(case
--when exists(select [OKATO] from dbo.Departments where link = kpb_korr)
--then (select left(replace([OKATO],' ',''),11) from dbo.Departments where link = kpb_korr)
when exists(select [OKTMO] from dbo.Departments where link = kpb_korr)
then (select left(replace([OKTMO],' ',''),8) from dbo.Departments where link = kpb_korr)
else ' '
end),
(case
when exists(select replace(replace(rtrim(code),'.',''),' ','') from dbo.kl_kbk where link = kbk)
then (select replace(replace(rtrim(code),'.',''),' ','') from dbo.kl_kbk where link = kbk)
else '_не_заполнен_кбк_'
end),
	@cSource+@cSinth+@cAnalit+
(case
when exists(select [code] from dbo.kosgu where link = sgu)
then (select [code] from dbo.kosgu where link = sgu)
else '000'
end),
(case when db_kr = 0 then isnull(SUM(summa),0.0) else 0.0 end),
(case when db_kr = 1 then isnull(SUM(summa),0.0) else 0.0 end),
(select left(replace(code,'.',''),6) from dbo.s_accounts where link = account_korr)+
(case
when exists(select [code] from dbo.kosgu where link = sgu_korr)
then (select [code] from dbo.kosgu where link = sgu_korr)
else '000'
end),
(NULL),
(NULL),
MAX(key_prov)

from @table1
group by kbk, account, sgu, db_kr, account_korr, sgu_korr, kpb_korr

--select * from #table2
-- очищаем зёрна от плевел -----------------------------------------------------------

if  @cSinth = '304' AND @cAnalit = '04' AND @cSGU = '000' begin
	update #table2
	set ppp = '', el_bud = '', okato = ''
end

if  @cSinth = '401' AND @cAnalit = '10' AND (@cSGU = '241' or @cSGU = '180')begin
	update #table2
	set el_bud = '',okato = ''
end

if  (@cSinth = '206' AND @cAnalit = '51' and @cSGU = '000')	or (@cSinth = '205' AND @cAnalit = '51' and @cSGU = '000') or (@cSinth = '207' AND (@cAnalit = '11' or @cAnalit = '12' or @cAnalit = '13') and @cSGU = '000') begin
	update #table2
	set summa_db = -(coalesce(summa_db,0.0) - coalesce(summa_kr,0.0)), summa_kr = 0.0, korr_acc = ''
end

if  @cSinth = '301' AND @cSGU = '000'/*@cVidFormCode = 14*/ begin
	update #table2
	set summa_db = 0.0, korr_acc = ''
end

if  (@cSinth = '211' OR @cSinth = '212') AND @cAnalit = '00' AND (@cSGU = '560' or @cSGU = '660') begin
	update #table2
	set ppp = '', el_bud = '',summa_db = 0.0
end

if  (@cSinth = '308' OR @cSinth = '309') AND @cAnalit = '00' AND (@cSGU = '730' or @cSGU = '830') begin
	update #table2
	set ppp = '', el_bud = '',summa_db = 0.0
end
--устанавливаем признак денежный - неденежный ----------------------------------------
update #table2  
set dnd = 
(case
    when 
        right(left(korr_acc,6),5) in ('21002','30405') or
        right(korr_acc,3) in ('510','610')
    then 1 -- денежные рассчёты
    else 0 -- не денежные рассчёты             
 end)
--------------------------------------------------------------------------------------
if (((@cSinth = '206' and @cAnalit = '51') or (@cSinth = '205' and @cAnalit = '51') or (@cSinth = '207' and (@cAnalit = '11' or @cAnalit = '12' or @cAnalit = '13'))) and @cSGU = '000') begin
	set @cStrSql = '
	insert into #table3 (Name_bp,ppp,el_bud,okato,KBK,summa_db,summa_kr,korr_acc,link,dnd,key_prov)
	select Name_bp,ppp,el_bud,okato,KBK,sum(summa_db),sum(summa_kr),korr_acc,null,dnd,null from #table2
	where Name_bp <> ''корреспондент_не_указан'' 
	group by Name_bp,ppp,el_bud,okato,KBK,korr_acc,dnd
	order by Name_bp,ppp

	insert into #table3 (Name_bp,ppp,el_bud,okato,KBK,summa_db,summa_kr,korr_acc,link,dnd,key_prov)
	select Name_bp,ppp,el_bud,okato,KBK,sum(summa_db),sum(summa_kr),korr_acc,null,dnd,null from #table2
	where Name_bp = ''корреспондент_не_указан'' 
	group by Name_bp,ppp,el_bud,okato,KBK,korr_acc,dnd
	order by KBK'
end
else begin
	set @cStrSql = '
	insert into #table3 (Name_bp,ppp,el_bud,okato,KBK,Code_Acc,summa_db,summa_kr,korr_acc,link,dnd,key_prov)
	select Name_bp,ppp,el_bud,okato,KBK,Code_Acc,summa_db,summa_kr,korr_acc,link,dnd,key_prov from #table2
	where Name_bp <> ''корреспондент_не_указан''
	order by Name_bp,ppp

	insert into #table3 (Name_bp,ppp,el_bud,okato,KBK,Code_Acc,summa_db,summa_kr,korr_acc,link,dnd,key_prov)
	select Name_bp,ppp,el_bud,okato,KBK,Code_Acc,summa_db,summa_kr,korr_acc,link,dnd,key_prov from #table2
	where Name_bp = ''корреспондент_не_указан''
	order by KBK,Code_Acc'
end
execute(@cStrSql)

delete from #table3 where summa_db = 0.0 and summa_kr = 0.0

update #table3
set link = LEFT(RTRIM(ISNULL(ppp,''))+'000',3)+LEFT(RTRIM(isnull(okato,'')) + '           ',11)+LEFT(RTRIM(ISNULL(el_bud,''))+'00',2)+LEFT(substring(rtrim(isnull([KBK],'')),1,17)+'00000000000000000',17)+LEFT(RTRIM(ISNULL(korr_acc,''))+'000000000',9)+RIGHT('00000000' + LTRIM(CAST(ISNULL(nn,0) as VARCHAR(8))),8)
--set link = LEFT(RTRIM(ISNULL(ppp,''))+'   ',3)+LEFT(RTRIM(isnull(okato,'')) + '           ',11)+LEFT(RTRIM(ISNULL(el_bud,''))+'  ',2)+LEFT(substring(rtrim(isnull([KBK],'')),1,17)+'                 ',17)+LEFT(RTRIM(ISNULL(korr_acc,''))+'         ',9)+RIGHT('00000000' + LTRIM(CAST(ISNULL(nn,0) as VARCHAR(8))),8)
--set link = LEFT(RTRIM(ISNULL(ppp,''))+'000',3)+LEFT(RTRIM(isnull(okato,''))+'00000000000',11)+LEFT(RTRIM(ISNULL(el_bud,''))+'00',2)+LEFT(substring(rtrim(isnull([KBK],'')),1,17)+'00000000000000000',17)+LEFT(RTRIM(ISNULL(korr_acc,''))+'000000000',9)+RIGHT('00000000' + LTRIM(CAST(ISNULL(nn,0) as VARCHAR(8))),8)

-- удаляем только строчки, принадлежащие указанной таблице. Остальные, соответственно, не трогаем
delete from dbo.report_dinamics where Link_SF = @LSF and Link_Col in (select link_col from dbo.report_coloumns where link_table = (select link_table from dbo.report_tables where link_form = (select top 1 link_form from dbo.report_saved_forms where link_saved_form = @LSF) and Orders = @table))

if @table in (1,3) begin
SELECT 
[CODE] = [link], -- Код строки.
[COL1] = [Name_bp], -- Наименование контрагента
[COL2] = [ppp], -- ППП
[COL3] = [okato], -- ОКАТО
[COL4] = [el_bud], -- Элемент бюджета
[COL5] = substring(rtrim(isnull([KBK],'')),1,3), -- АДМ
[COL6] = substring(rtrim(isnull([KBK],'')),4,14), -- КБК
[COL7] = [summa_db], -- сумма дебет
[COL8] = [summa_kr], -- сумма кредит
[COL9] = [korr_acc], -- Код корреспондирующего счёта бюджетного учета
[COL10] = cast (isnull([dnd],'') as varchar), -- Признак платежа
[COL11]= [link], -- Код строки.
[COL12]= RIGHT('00000000' + LTRIM(CAST(ISNULL(nn,0) as VARCHAR(8))),8)
FROM #table3
ORDER BY [link]
end
else begin
SELECT 
[CODE] = [link], -- Код строки.
[COL1] = [Name_bp], -- Наименование контрагента
[COL2] = [ppp], -- ППП
[COL3] = [okato], -- ОКАТО
[COL4] = [el_bud], -- Элемент бюджета
[COL5] = substring(rtrim(isnull([KBK],'')),1,3), -- АДМ
[COL6] = substring(rtrim(isnull([KBK],'')),4,4), -- РзПр
[COL7] = substring(rtrim(isnull([KBK],'')),8,7), -- ЦСР
[COL8] = substring(rtrim(isnull([KBK],'')),15,3),-- ВР
[COL9] = [summa_db], -- сумма дебет
[COL10] = [summa_kr], -- сумма кредит
[COL11] = [korr_acc], -- Код корреспондирующего счёта бюджетного учета
[COL12] = cast (isnull([dnd],'') as varchar), -- Признак платежа
[COL13] = [link], -- Код строки.
[COL14] = RIGHT('00000000' + LTRIM(CAST(ISNULL(nn,0) as VARCHAR(8))),8)
FROM #table3
ORDER BY [link]
end

drop table #table2
drop table #table3

GO
GRANT EXECUTE ON dbo.[RT_CALC_0503125G] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET ANSI_WARNINGS ON
GO
SET NOCOUNT OFF
GO

GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

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

GO
CREATE PROCEDURE dbo.BK_UPDATE_OUT_TABLE_ECARDS
	@varKSintLINK_UP	int,
	@varKSintOBJECT		int,
	@varKSintDICTION	int
AS
DECLARE
	@varKSERROR	int,
	@varKSRowCount	int,
	@varKStrancount	int

	SET @varKSintDICTION = (SELECT LINK FROM dbo.PERSON_ECARDS WITH (NOLOCK) WHERE LINK = @varKSintDICTION)

	SET @varKStrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON

	IF @varKSintDICTION is null
		DELETE FROM dbo.OUT_TABLE_ECARD
		WHERE LINK_UP = @varKSintLINK_UP
			AND OBJECT = @varKSintOBJECT
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN 7
		END
	ELSE
	BEGIN
		UPDATE dbo.OUT_TABLE_ECARD
			SET ECARD = @varKSintDICTION
		WHERE LINK_UP = @varKSintLINK_UP
			AND OBJECT = @varKSintOBJECT
	
		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
	
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN 7
		END
	
		IF @varKSRowCount = 0
		BEGIN
			INSERT INTO dbo.OUT_TABLE_ECARD(LINK_UP, OBJECT, ECARD)
			VALUES (@varKSintLINK_UP, @varKSintOBJECT, @varKSintDICTION)
			IF @@ERROR <> 0
			BEGIN
				ROLLBACK TRAN
				RETURN 7
			END
		END
	END

	IF @@TRANCOUNT > @varKStrancount
		COMMIT TRAN

	RETURN 0



GO


GRANT EXECUTE ON dbo.BK_UPDATE_OUT_TABLE_ECARDS TO PUBLIC

GO


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


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_WARNINGS OFF
GO
SET ANSI_NULLS ON 
GO
SET NOCOUNT ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RB_CALC_0503125G_NEW]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RB_CALC_0503125G_NEW]
GO

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

CREATE PROCEDURE dbo.RB_CALC_0503125G_NEW
@iLSF int,
@table int
AS

declare @dBeginDate datetime,
		@dEndDate datetime,
		@dEndDate_pl datetime,
		@dCALC_DATE datetime,
		@iThisDep int,
		@nPeriod_Type tinyint,
		@cStrSql varchar(8000)
----------		
DECLARE @LF	int, 
		@LT	int,
		@LC	int,
		@orderCol int,
		@iLinkCalcForm int,
		@iLinkColDt int,
		@bid varchar(100),
		@nabor_filter varchar(1000)
---------------
				
declare @tTempRes table(DEP_NAME varchar(254),
						PPP varchar(3), 
						OKATO varchar(11), 
						EL_BUDG varchar(2), 
						KBK varchar(17), 
						ACC_CODE varchar(9), 
						summa_db numeric(20,4), 
						summa_kr numeric(20,4), 
						korr_acc varchar(9), 
						D_ND tinyint) 

declare @tTempRes2 table(DEP_NAME varchar(254),
						 PPP varchar(3), 
						 OKATO varchar(11), 
						 EL_BUDG varchar(2), 
						 KBK varchar(17), 
						 ACC_CODE varchar(9), 
						 summa_db numeric(20,4), 
						 summa_kr numeric(20,4), 
						 korr_acc varchar(9), 
						 D_ND tinyint,
						 NUM_PP int IDENTITY(1,1)) 
declare @filter_kbk table (kbk varchar(20))

-- определяем период (если в январе формируем, то берём весь предыдущий год не включая 31 декабря)
select @dEndDate = Begin_Date, @nPeriod_Type = period_type from dbo.report_saved_forms where link_saved_form = @iLSF

select @dBeginDate = dbo.DateBeginOfYear(@dEndDate)

-- set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then (@dBeginDate - (datepart(dd,@dBeginDate))) - 1 else @dBeginDate /*- (datepart(dd,@dBeginDate))*/ end
-- set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')


--if @nPeriod_Type <> 1 
--	set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then @dBeginDate - 1 else @dBeginDate end
--else
--	set @dEndDate = @dBeginDate
--
--	set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')

select @nabor_filter = REPLACE(dbo.rn_get_atr_value(@iLSF,'REPORTS_FILTER_KBK'), 'Не отобрано', '')

insert @filter_kbk (kbk)   
Select RTRIM(code) FROM rn_get_filter(@iLSF,'REPORTS_FILTER_KBK')


---------------------------------------****************************
declare @temp_nastr table (link int, [Link_Col] int NOT NULL, 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL, link_dt int, link_kt int, dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint)
declare @temp_nastr_xor table (	link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_dt int, link_kt int, dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, dt_kt tinyint)
declare @temp_nastr_rest table (	link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000),
	[type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint)
declare @temp_nastr_rest_xor table (link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000),
	[type] tinyint, type_kbk tinyint, dt_kt tinyint)


-------- ЧИТАЕМ ДАННЫЕ ОТЧЕТА
select @LF = RSF.Link_Form, 
		@iThisDep 	= Link_Organization, 
		@dEndDate	= Begin_Date + 1,
		@dCALC_DATE	= Begin_Date, 
		@dBeginDate	= dbo.DateBeginOfYear(Begin_Date),
		@nPeriod_Type = period_type
from report_saved_forms RSF  where RSF.link_saved_form = @iLSF

SET @iLinkCalcForm = dbo.RK_GET_NASTR_CALC_REPORT (@iLSF, 1)
print @iLinkCalcForm
if @iLinkCalcForm is null 
BEGIN
	exec RT_CALC_0503125G @iLSF, @table
	RETURN 0
END

set @iLinkColDt = (select top 1 RC.LINK_COL
					from dbo.REPORT_COLOUMNS RC
					inner join dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.Link_Form = @LF and RT.orders = @table and RT.orders = @table
					where @table = 2 and RC.Export_Order = 9 or @table <> 2 and RC.Export_Order = 7)
---------------------------------------------------------------------
----- ПОЛУЧАЕМ ВЫБОРКУ ИЗ ТАБЛИЦЫ НАСТРОЕК ----
insert @temp_nastr 
select C.link, C.Link_Col, Calc_Order, [Sign], DT.link , KT.link, dt_ekr, kt_ekr, [type], type_kbk, mask_kbk, dt_kt
from dbo.REPORT_CALC C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = @table and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE C.LINK_UP = @iLinkCalcForm
	AND [sign] in (1,2) and CR.[type] = 1 
	AND (rtrim (CR.DT_Mask) = '' OR CR.DT_Mask = '%' OR rtrim (CR.DT_Mask) <> '' AND DT.LINK IS NOT NULL)
	AND (rtrim (CR.KT_Mask) = '' OR CR.KT_Mask = '%' OR rtrim (CR.KT_Mask) <> '' AND KT.LINK IS NOT NULL)


-- проводки, которые мы исключаем --
insert @temp_nastr_xor 
select C.link, C.Link_Col, Calc_Order, [Sign], DT.link , KT.link, dt_ekr, kt_ekr, [type], type_kbk, dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = @table and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
where C.LINK_UP = @iLinkCalcForm
	AND [sign] = 3 and CR.[type] = 1 


--- Выборка счетов для расчета остатков ---
insert @temp_nastr_rest 
select C.link, C.Link_Col, Calc_Order, [Sign],
	case
		when DT.link is NULL then KT.link
		else DT.link
	end,
	case
		when DT.link is NULL then kt_ekr
		else dt_ekr
	end, [type],
	type_kbk,
	mask_kbk,
	dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = @table and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE C.LINK_UP = @iLinkCalcForm 
	AND CR.[type] in (2,3) and [sign] in (1,2) 
	AND (rtrim (CR.DT_Mask) = '' OR rtrim (CR.DT_Mask) <> '' AND DT.LINK IS NOT NULL)
	AND (rtrim (CR.KT_Mask) = '' OR rtrim (CR.KT_Mask) <> '' AND KT.LINK IS NOT NULL)

/*
select S1.CODE, * from @temp_nastr_rest T, S_ACCOUNTS S1 
WHERE S1.LINK = T.LINK_account
*/
--- Счета, которые исключаем для расчета остатков ---
insert @temp_nastr_rest_xor
select C.link, C.Link_Col, Calc_Order, [Sign],
	case
		when DT.link is NULL then KT.link
		else DT.link
	end,
	case
		when DT.link is NULL then kt_ekr
		else dt_ekr
	end,
	[type],
	type_kbk,
	dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = @table and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE  C.LINK_UP = @iLinkCalcForm 
	AND CR.[type] in (2,3) and [sign] = 3 
	AND (DT.LINK IS NOT NULL
		OR KT.LINK IS NOT NULL)
---------------------------------------****************
---- Обороты

	insert into @tTempRes
	select	DEP_NAME = isnull(D.FULL_NAME, 'корреспондент_не_указан'), -- Наименование контрагента
			PPP = case when TMP.Mask_KBK like '%АДМ%' then isnull(VED.CODE, '') else '' end, -- ППП
			--OKATO = case when TMP.Mask_KBK like '%ОКАТО%' then isnull(replace(D.OKATO,' ',''), '') else '' end, -- ОКАТО
			OKATO = case when TMP.Mask_KBK like '%ОКТМО%' then isnull(replace(D.OKTMO,' ',''), '') else '' end, -- ОКАТО
			EL_BUDG = case when TMP.Mask_KBK like '%ЭЛЕМЕНТ%' then isnull(BUDG.CODE_EL, '') else '' end, -- Элемент бюджета
			KBK = isnull(replace(KBK.CODE,'.',''),''), --KBK
			ACC_CODE = case TMP.dt_kt when 0 then isnull(left(replace(SAD.CODE,'.',''),6),'') + isnull(DTS.CODE,'') else isnull(left(replace(SAK.CODE,'.',''),6),'') + isnull(KTS.CODE,'')  end,
			SUMMA_DB = case TMP.LINK_COL when @iLinkColDt then isnull(G2.SUMMA,'') else 0 end, -- сумма дебет
			SUMMA_KR = case TMP.LINK_COL when @iLinkColDt then 0 else isnull(G2.SUMMA,'') end, -- сумма кредит
			korr_acc = case TMP.dt_kt when 0 then isnull(left(replace(SAK.CODE,'.',''),6),'')  + isnull(KTS.CODE,'') else isnull(left(replace(SAD.CODE,'.',''),6),'') + isnull(DTS.CODE,'')  end, -- корреспондирующий счет
			D_ND = case when TMP.Mask_KBK like '%ДЕН%' then 1 else 0 end-- Признак платежа

	FROM dbo.G_PROV G
	INNER JOIN dbo.G_PROV1 G1 ON (G1.LINK_UP = G.LINK)
	INNER JOIN dbo.G_PROV2 G2 ON (G2.LINK_UP = G1.LINK)


	LEFT JOIN dbo.G_PROV_AP DT ON (DT.LINK_UP = G2.LINK AND DT.DB_KR = 0)
	LEFT JOIN dbo.G_PROV_AP KT ON (KT.LINK_UP = G2.LINK AND KT.DB_KR = 1)

	LEFT JOIN dbo.KOSGU DTS ON (DTS.Link = DT.SGU)
	LEFT JOIN dbo.KOSGU KTS ON (KTS.Link = KT.SGU)
	
	INNER JOIN @TEMP_NASTR TMP ON (TMP.LINK_DT = DT.ACCOUNT OR TMP.LINK_DT IS NULL)
			AND (TMP.LINK_KT = KT.ACCOUNT OR TMP.LINK_KT IS NULL)
		AND (dbo.RO_LIKE_LIST(DTS.Code, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '')
		AND (dbo.RO_LIKE_LIST(KTS.Code, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '')

	LEFT JOIN dbo.S_ACCOUNTS SAD ON SAD.LINK = DT.ACCOUNT

	LEFT JOIN dbo.S_ACCOUNTS SAK ON SAK.LINK = KT.ACCOUNT 

	LEFT JOIN dbo.KL_KBK KBK ON (TMP.dt_kt = 0 AND KBK.LINK = DT.KBK OR TMP.DT_KT = 1 AND KBK.LINK = KT.KBK)
	left join dbo.G_PROV_OS1 OS on OS.LINK_OS1 = G.LINK
	LEFT JOIN dbo.DEPARTMENTS D ON D.LINK = (case	when DT.Dep is not NULL and DT.Dep <> G.Dep then DT.Dep
										when KT.Dep is not NULL and KT.Dep <> G.Dep then KT.Dep
										when OS.Dep_pass is not NULL and OS.Dep_pass <> G.Dep then OS.Dep_pass
										when OS.Dep_receive is not NULL and OS.Dep_receive <> G.Dep then OS.Dep_receive
										else isnull((SELECT top 1 GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA, dbo.S_OBJECTS SO WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT = SO.LINK and (SO.CODE = 'NOTICE_LINK_DEP_RECEIVER' or SO.CODE = 'NOTICE_LINK_DEP_SENDER') AND GPDA.DEPARTMENT <> G.Dep), NULL) end)
	left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
	left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
	LEFT JOIN @filter_kbk F on KBK.Code = F.kbk
	WHERE G.DATE_PROV BETWEEN @dBeginDate AND @dCALC_DATE
		AND G.DEP = @iThisDep
		AND (F.kbk IS NOT NULL OR isnull(@nabor_filter, '') = '')
		AND (TMP.TYPE_KBK = 0 OR (TMP.TYPE_KBK & KBK.[TYPE]) / KBK.[TYPE] = 1)
		AND not exists(select top 1 *
				from @temp_nastr_xor xor
				where xor.link = tmp.link
					and xor.link_dt = dt.account and xor.link_kt = kt.account
					and (CHARINDEX(RTRIM(DTS.Code), xor.dt_ekr) > 0
						or RTRIM(isnull(DTS.Code,'')) like RTRIM(xor.dt_ekr) + '%') 
					and (RTRIM(isnull(KTS.Code,'
			')) like RTRIM(xor.kt_ekr) + '%' or CHARINDEX(RTRIM(KTS.Code),xor.kt_ekr) > 0)) -- исключаем
			
----------------- остатки ------------------------------
while exists(select top 1 * from @temp_nastr_rest)
begin
	select top 1 @LC = Link_Col from @temp_nastr_rest

	set @bid = 'calc_col_' + LTRIM(RTRIM(STR(@LC)))

	insert dbo.buffer(ID, Link)
	select @bid, link_account
	from @temp_nastr_rest
	where link_col = @LC

	-- остаток на конец периода
	insert into @tTempRes
	select	DEP_NAME = isnull(D.FULL_NAME, 'корреспондент_не_указан'), -- Наименование контрагента
			PPP = case when R.Mask_KBK like '%АДМ%' then isnull(VED.CODE, '') else '' end, -- ППП
			OKATO = case when R.Mask_KBK like '%ОКТМО%' then isnull(replace(D.OKATO,' ',''), '') else '' end, -- ОКАТО
			EL_BUDG = case when R.Mask_KBK like '%ЭЛЕМЕНТ%' then isnull(BUDG.CODE_EL, '') else '' end, -- Элемент бюджета
			KBK = isnull(replace(K.CODE,'.',''),''), --KBK
			ACC_CODE = isnull(left(replace(SA.CODE,'.',''),6),'') + '000',
			SUMMA_DB = case when R.LINK_COL = @iLinkColDt and (SA.S_PASSIVE = 1 and [sign] = 1 OR SA.S_ACTIVE = 1 and [sign] = 2) then isnull(k_summa - d_summa,'') 
							when R.LINK_COL = @iLinkColDt and (SA.S_PASSIVE = 2 and [sign] = 2 OR SA.S_ACTIVE = 1 and [sign] = 1) then isnull(d_summa - k_summa,'') 
							else 0 end, -- сумма дебет
			
			SUMMA_KR = case when R.LINK_COL <> @iLinkColDt and (SA.S_PASSIVE = 1 and [sign] = 1 OR SA.S_ACTIVE = 1 and [sign] = 2) then isnull(d_summa - k_summa,'') 
							when R.LINK_COL <> @iLinkColDt and (SA.S_PASSIVE = 2 and [sign] = 2 OR SA.S_ACTIVE = 1 and [sign] = 1) then isnull(k_summa - d_summa,'') 
							else 0 end, -- сумма кредит
			korr_acc = '000000000',
			D_ND = case when R.Mask_KBK like '%ДЕН%' then 1 else 0 end-- Признак платежа ,
			--R.Calc_Order
	from dbo.ARestTableByDateAccounts(@dEndDate, @bid) A
	INNER JOIN @temp_nastr_rest R on R.link_account = account and R.Link_Col = @LC and R.[Type] = 3
	LEFT JOIN dbo.KL_KBK K on K.Link = A.KBK and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end) > 0)
	left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	LEFT JOIN dbo.DEPARTMENTS D ON D.LINK = A.DEP
	left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
	left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
	LEFT JOIN @filter_kbk F on K.Code = F.kbk
	where dep_link = @iThisDep
			and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and r1.link = r.link)
		AND (F.kbk IS NOT NULL OR isnull(@nabor_filter, '') = '')
		AND (R.TYPE_KBK = 0 OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		



-- select * from #tTemp
	
	delete @temp_nastr_rest where Link_Col = @LC

	exec dbo.BufferClear @bid	
end


insert into @tTempRes2 (DEP_NAME, PPP, OKATO, EL_BUDG, ACC_CODE, KBK, summa_db, summa_kr, KORR_ACC, D_ND)
select DEP_NAME, PPP, OKATO, EL_BUDG, ACC_CODE, KBK, SUM(summa_db), SUM(summa_kr), KORR_ACC, D_ND
from @tTempRes 
where DEP_NAME <> 'корреспондент_не_указан'
group by DEP_NAME, PPP, OKATO, EL_BUDG, ACC_CODE, KBK, KORR_ACC, D_ND
union
select DEP_NAME, PPP, OKATO, EL_BUDG, ACC_CODE, KBK, SUM(summa_db), SUM(summa_kr), KORR_ACC, D_ND
from @tTempRes 
where DEP_NAME = 'корреспондент_не_указан'
group by DEP_NAME, PPP, OKATO, EL_BUDG, ACC_CODE, KBK, KORR_ACC, D_ND



if @table in (1,3) 
	SELECT 
--	[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'00000000000',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
--	[CODE] = LEFT(RTRIM(PPP)+'   ',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '  ',2) + LEFT(rtrim(KBK) + '                 ',17) + LEFT(RTRIM(KORR_ACC) + '         ',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL1] = DEP_NAME, -- Наименование контрагента
	[COL2] = PPP, -- ППП
	[COL3] = OKATO, -- ОКАТО
	[COL4] = EL_BUDG, -- Элемент бюджета
	[COL5] = substring(rtrim(KBK),1,3), -- АДМ
	[COL6] = substring(rtrim(KBK),4,14), -- КБК
	[COL7] = SUMMA_DB, -- сумма дебет
	[COL8] = SUMMA_KR, -- сумма кредит
	[COL9] = KORR_ACC, -- Код корреспондирующего счёта бюджетного учета
	[COL10] = cast (isnull(d_nd,'') as varchar), -- Признак платежа
	[COL11]= LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL12]= RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8)
	FROM @tTempRes2
	where  summa_db <> 0 or summa_kr <> 0
	ORDER BY NUM_PP

else 
	SELECT 
	--[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'00000000000',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	--[CODE] = LEFT(RTRIM(PPP)+'   ',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '  ',2) + LEFT(rtrim(KBK) + '                 ',17) + LEFT(RTRIM(KORR_ACC) + '         ',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL1] = DEP_NAME, -- Наименование контрагента
	[COL2] = PPP, -- ППП
	[COL3] = OKATO, -- ОКАТО
	[COL4] = EL_BUDG, -- Элемент бюджета
	[COL5] = substring(rtrim(KBK),1,3), -- АДМ
	[COL6] = substring(rtrim(KBK),4,4), -- РзПр
	[COL7] = substring(rtrim(KBK),8,7), -- ЦСР
	[COL8] = substring(rtrim(KBK),15,3),-- ВР
	[COL9] = SUMMA_DB, -- сумма дебет
	[COL10] = SUMMA_KR, -- сумма кредит
	[COL11] = KORR_ACC, -- Код корреспондирующего счёта бюджетного учета
	[COL12] = cast (isnull(d_nd,'') as varchar), -- Признак платежа
	[COL13] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL14] = RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8)
	FROM @tTempRes2
	where  summa_db <> 0 or summa_kr <> 0
	ORDER BY NUM_PP



GO
GRANT EXECUTE ON dbo.[RB_CALC_0503125G_NEW] TO PUBLIC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET ANSI_WARNINGS ON
GO
SET NOCOUNT OFF
GO

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

GO
CREATE PROCEDURE dbo.BK_EXPORT_F1151006_505 (@iLINK_FORM INT)
AS
BEGIN

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

	DECLARE
		@FNAME VARCHAR (254),
		@FNAME_ID VARCHAR (254),

		@PART_NAME_NNN VARCHAR (100),

		@DEP_LINK	INT,
		@INN	VARCHAR (12),
		@KPP VARCHAR (9),
		@IMNS VARCHAR (4),
		@OKVED VARCHAR (8),
		@TLF_GL_BUH	VARCHAR (10),
		@POST_GL_BUH	VARCHAR (254),
		@DEP_NAME VARCHAR (254),

		@SONO VARCHAR (4),

		@DOC_ID		VARCHAR (36),

		@NAME_RUK	VARCHAR (60),
		@FAM_RUK	VARCHAR (60),
		@OT_RUK		VARCHAR (60),

		@NAME_GL_BUH	VARCHAR (60),
		@FAM_GL_BUH	VARCHAR (60),
		@OT_GL_BUH	VARCHAR (60),

		@dDATE_FORM	DATETIME,
		@PERIOD_TYPE	INT,
		@PERIOD_NUM	INT,
		@cPERIOD_NUM	VARCHAR (2),

		@iLINK_TABLE	INT,
		@PROC_NAME	VARCHAR (254),

		--- Раздел 1 ---
		@OKTMO_D VARCHAR (15),
		@OKTMO VARCHAR (15),
		
		@KBK VARCHAR (20),
		@SUMMA1 VARCHAR (100),
		@SUMMA2 VARCHAR (100),
		@NUM_KOR	VARCHAR (3),
		@PLACE_USED	VARCHAR (3),

		--- Лист 02 ---
		@CODE VARCHAR (50),
		@COL1 VARCHAR (50),
		@COL3 NUMERIC (20,4), 	
		@COL4 NUMERIC (20,4), 	

		@strINS_VALUE	VARCHAR (100),

		@strEXEC	VARCHAR (8000)
	--- ---
	SELECT
		@DEP_LINK = LINK_ORGANIZATION,
		@dDATE_FORM	= BEGIN_DATE,
		@PERIOD_TYPE = PERIOD_TYPE,
		@PERIOD_NUM	= PERIOD_NUMBER
	FROM dbo.REPORT_SAVED_FORMS RSF
	WHERE link_saved_form = @iLINK_FORM

	SET @cPERIOD_NUM =
			CASE
				WHEN @PERIOD_TYPE = 1 THEN '34'	-- ПЕРИОД ГОД
				WHEN @PERIOD_TYPE = 2 THEN 	-- ПЕРИОД КВАРТАЛ
					CASE 
						WHEN @PERIOD_NUM = 1 THEN '21'
						WHEN @PERIOD_NUM = 2 THEN '31'
						WHEN @PERIOD_NUM = 3 THEN '33'
					END
				WHEN @PERIOD_TYPE = 4 THEN LTRIM (STR (34 + @PERIOD_NUM ))
			END

	EXEC dbo.GetRandStr 36, @DOC_ID OUTPUT

	SELECT @PART_NAME_NNN = @DOC_ID

	SELECT
		@INN	= CONVERT (VARCHAR (10), INN_LONG),
		@KPP = CONVERT (VARCHAR (9), KPP),
		@IMNS = CONVERT (VARCHAR (4), IMNS),
		@OKVED = CONVERT (VARCHAR (8), OKVED),
		@DEP_NAME = [NAME],
		@OKTMO_D = CONVERT (VARCHAR (11), REPLACE (OKTMO, ' ', '')),
		@SONO = CONVERT (VARCHAR (4), ISNULL (IMNS, ''))
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @DEP_LINK

	SET @DEP_NAME = REPLACE (@DEP_NAME, '"', '&quot;')

	SELECT
		@TLF_GL_BUH = A.PHONE,
		@POST_GL_BUH = B.POST_NAME,

		@NAME_GL_BUH = B.IM,
		@FAM_GL_BUH = B.FM,
		@OT_GL_BUH = B.OT

	FROM dbo.DICTIONARY_OTV_FACE A
	LEFT JOIN dbo.KU_EMPL_PLACING B ON (B.LINK = A.FACE_LINK)
	WHERE A.DEP_LINK = @DEP_LINK
		AND A.[NAME] = 'Главный бухгалтер'
		
	SELECT
		@NAME_RUK = IM,
		@FAM_RUK = FM,
		@OT_RUK = OT
	FROM dbo.KU_EMPL_PLACING 
	WHERE LINK = (SELECT FACE_LINK FROM dbo.DICTIONARY_OTV_FACE
					WHERE DEP_LINK = @DEP_LINK
						AND [NAME] = 'Руководитель')

	--- Данные раздела 1.1 ---
	SELECT
		@iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 1)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TABLE_R1_1
		(
		CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (50),
		COL2 VARCHAR(254),	-- ОКТМО
		FCOL2 VARCHAR (254),
		COL3 VARCHAR (100), 	-- КБК (ФБ)
		FCOL3 VARCHAR (254),
		COL4 VARCHAR(100), 	-- Сумма1 (ФБ)
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Сумма2 (ФБ)
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- КБК (Субъект)
		FCOL6 VARCHAR (254),
		COL7 VARCHAR(100), 	-- Сумма1 (Субъект)
		FCOL7 VARCHAR (254),
		COL8 VARCHAR(100), 	-- Сумма2 (Субъект)
		FCOL8 VARCHAR (254),
		COL9 VARCHAR(100), 	-- Номер корректировки
		FCOL9 VARCHAR (254),
		COL10 VARCHAR(100), 	-- По месту использования
		FCOL10 VARCHAR (254),
		ITOG NUMERIC (20)
		) 	
	
	SET @strEXEC = 'INSERT INTO #TABLE_R1_1 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, FCOL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, COL7, FCOL7,
		COL8, FCOL8, COL9, FCOL9,
		COL10, FCOL10, ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

	--- Данные листа 02 ---
	SELECT
		@iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 2)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TEMP
		(
		CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (50),
		COL2 VARCHAR(254),	-- Показатель
		COL3 NUMERIC (20,4), 	-- Сумма
		FCOL3 VARCHAR (8000),
		COL4 NUMERIC (20,4), 	-- Ставка
		FCOL4 varchar (8000),
		ITOG NUMERIC (20,4)
		) 	
	
	SET @strEXEC = 'INSERT INTO #TEMP (CHECKED, UPD, DEL, LINK_SAVED_FORM, LINK_ROW, ORDERS, 
				CALC_ORDERS, PRINT_NULL, CODE, COL1, COL2, COL3, FCOL3, COL4, FCOL4, 
				ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

	--- Формирование XML ---
	SELECT @FNAME_ID = 'NO_PRIB_' + ISNULL (RTRIM (@IMNS), '0000') + '_' + ISNULL (RTRIM (@IMNS), '0000') + '_'
		+ ISNULL (RTRIM (@INN), '0000000000') + ISNULL (RTRIM (@KPP), '000000000')
		+ '_' + CONVERT (VARCHAR (10), GETDATE (), 112) + '_'
		+ SUBSTRING (@PART_NAME_NNN, LEN (@PART_NAME_NNN) - 36, 36) 

	SELECT @FNAME = RTRIM (@FNAME_ID) + '.XML'

	DECLARE @OUTPUT TABLE (ID int identity(1,1), F_NAME VARCHAR(254) DEFAULT (''),
			OUT_TEXT TEXT DEFAULT (''))

	--Строка заголовка
	CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))

	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

	DECLARE @NAME_PROG VARCHAR(254), @VERS_PROG VARCHAR(254)
	SELECT @NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
		@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
		+ '.' + (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
		+ '.' + (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
	FROM dbo.DICTIONARY_TASK where CODE = 'SMETA'

	SET @NAME_PROG = RTRIM (@NAME_PROG) + ' ' + @VERS_PROG

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'OEM')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<?xml version="1.0" encoding="windows-1251" ?>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Файл xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИдФайл="' + RTRIM (@FNAME_ID) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсПрог="' + RTRIM (LEFT (@NAME_PROG, 40)) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсФорм="5.05">')


	--- Документ ---
	SELECT
		@NUM_KOR = COL9,
		@PLACE_USED = COL10
	FROM #TABLE_R1_1

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Документ КНД="1151006"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ДатаДок="' + CONVERT (VARCHAR (10), GETDATE (), 104) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Период="' + @cPERIOD_NUM + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ОтчетГод="' + LTRIM (STR (YEAR (@dDATE_FORM))) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КодНО="' + @SONO + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НомКорр="' + ISNULL (@NUM_KOR, '0') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ПоМесту="' + ISNULL (@PLACE_USED, '214') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '>')

	

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СвНП')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ОКВЭД="' + ISNULL (@OKVED, '') + '"')
	IF ISNULL (@TLF_GL_BUH, '') <> ''
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Тлф="' + RTRIM (ISNULL (@TLF_GL_BUH, '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НПЮЛ')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НаимОрг="'
			 + RTRIM (ISNULL (REPLACE (@DEP_NAME, '"', '&quot;'), '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИННЮЛ="' + ISNULL (@INN, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КПП="' + ISNULL (@KPP, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '/>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СвНП>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Подписант ПрПодп="1">')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ФИО')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, ' Фамилия="' + RTRIM (ISNULL (@FAM_RUK, '')) 
					+ '" Имя="' + RTRIM (@NAME_RUK) + '"'
					+ CASE WHEN ISNULL (@OT_RUK, '') <> '' THEN ' Отчество="'
											+ RTRIM (ISNULL (@OT_RUK, '')) + '"'
							ELSE '' END
					+ '/>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Подписант>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Прибыль>')
	
	--- Раздел 1 ---
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НалПУ>')
	--- 1.1. для организаций, уплачивающих авансовые платежи и налог на прибыль организаций ---
	--- ОКТМО ---
	SELECT @OKTMO = COL2
	FROM #TABLE_R1_1 

	IF ISNULL (@OKTMO, '') = ''
		SET @OKTMO = ISNULL (@OKTMO_D, '')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НалПУАв ТипНП="1" ОКТМО="'
		+ @OKTMO + '">')

	-- Фед. бюджет --
	SELECT
		@KBK = COL3,
		@SUMMA1 = COL4,
		@SUMMA2 = COL5
	FROM #TABLE_R1_1 

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ФедБдж')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КБК="' + RTRIM (@KBK) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + RTRIM (@SUMMA2) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '/>')	

	-- Бюджет субъекта --
	SELECT
		@KBK = COL6,
		@SUMMA1 = COL7,
		@SUMMA2 = COL8
	FROM #TABLE_R1_1 

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СубБдж')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КБК="' + RTRIM (@KBK) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + RTRIM (@SUMMA2) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '/>')	

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</НалПУАв>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</НалПУ>')

	--- Лист 02 ---
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасчНал')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ТипНП="1"')

	--- Таблица ---
	DECLARE #DATA_CURSOR CURSOR LOCAL STATIC	
		FOR
		SELECT
			CODE,
			COL1,
			COL3,
			COL4
		FROM #TEMP
		ORDER BY ORDERS

	OPEN #DATA_CURSOR

	FETCH FROM #DATA_CURSOR
		INTO @CODE,
			@COL1, 
			@COL3, 
			@COL4 


	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @strINS_VALUE = CASE
					WHEN @CODE = '010' THEN 'ДохРеал="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '020' THEN 'ДохВнереал="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '030' THEN 'РасхУмРеал="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '040' THEN 'РасхВнереал="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '050' THEN 'Убытки="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '060' THEN 'ПрибУб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '070' THEN 'ДохИсклПриб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '080' THEN 'ПрибБРСт0="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '090' THEN 'СумЛьгот="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '100' THEN 'НалБаза="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '110' THEN 'УбытУмНБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '120' THEN 'НалБазаИсч="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '130' THEN 'НалБазаИсчСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '140' THEN 'СтавНалВсего="' + LTRIM (STR (ISNULL (@COL4, 0), 20, 2)) + '"'
					WHEN @CODE = '150' THEN 'СтавНалФБ="' + LTRIM (STR (ISNULL (@COL4, 0), 20, 2)) + '"'
					WHEN @CODE = '160' THEN 'СтавНалСуб="' + LTRIM (STR (ISNULL (@COL4, 0), 20, 2)) + '"'
					WHEN @CODE = '170' THEN 'СтавНалСуб284="' + LTRIM (STR (ISNULL (@COL4, 0), 20, 2)) + '"'
					WHEN @CODE = '180' THEN 'НалИсчисл="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '190' THEN 'НалИсчислФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '200' THEN 'НалИсчислСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '210' THEN 'АвНачисл="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '220' THEN 'АвНачислФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '230' THEN 'АвНачислСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '240' THEN 'НалВыпл311="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '250' THEN 'НалВыпл311ФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '260' THEN 'НалВыпл311Суб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '270' THEN 'НалДоплФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '271' THEN 'НалДоплСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '280' THEN 'НалУменФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '281' THEN 'НалУменСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '290' THEN 'АвПлатМес="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '300' THEN 'АвПлатМесФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '310' THEN 'АвПлатМесСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '320' THEN 'АвПлатУпл1Кв="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '330' THEN 'АвПлатУпл1КвФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '340' THEN 'АвПлатУпл1КвСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					ELSE ''
				END	
				
		IF LEN (@strINS_VALUE) > 0
			INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, @strINS_VALUE)

		FETCH NEXT FROM #DATA_CURSOR
			INTO @CODE,
				@COL1, 
				@COL3, 
				@COL4 
	END	--- WHILE @@FETCH_STATUS = 0

	CLOSE #DATA_CURSOR
	DEALLOCATE #DATA_CURSOR
	------------------------------
	------------------------------
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '/>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Прибыль>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Документ>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Файл>')

	DROP TABLE #TASK_PROP

	DROP TABLE #TEMP
	DROP TABLE #TABLE_R1_1

	SELECT * FROM @OUTPUT ORDER BY [ID]
END 

GO

GRANT EXECUTE ON dbo.[BK_EXPORT_F1151006_505] TO PUBLIC

GO


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


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

GO


CREATE   PROCEDURE [dbo].SA_REP_FUR @LINK_DOC INT
AS

declare @OBJ_CODE varchar(254), @SR_VID INT, @AvgDays NUMERIC(18,2), @PAYMENT INT, @PER INT, @DATE_BEG DATETIME, @LINK_EMPL INT, @LINK_PAYS INT 
Set @OBJ_CODE = (Select top 1 O.CODE from dbo.sdoc D inner join S_OBJECTS O on D.OBJECT = O.LINK and D.LINK = @LINK_DOC)

Select top 1 @SR_VID = [TYPE], @PAYMENT = [PAYMENT], @PER = [TYP_PERIOD], @DATE_BEG = DATE1, @LINK_EMPL = LINK_EMPL, @LINK_PAYS = LINK_PAY
from SDOC_AVAC where LINK_UP = @LINK_DOC
  
--
DECLARE @LINK_DEP INT
select @LINK_DEP = LINK_DEP from SDOC where LINK = @LINK_DOC

SET @AvgDays = COALESCE(dbo.sa_get_option_by_code('FURLOUGH_OPT4'),29,4)

Select  NAME_DOC = 'Расчет отпускных №' + RTRIM(C.[NUMBER]) + ' от ' + convert(varchar(10), C.[DATE], 104),
	NAME_DOC2 = 'Основание: приказ ' + RTRIM(LTRIM(t.[NAME])) + ' №' + RTRIM(O.NUMBER) + ' от ' + convert(varchar(10),O.[DATE],104),
	NAME_EMPL,
	TAB_NUMER,
	DATE1, DATE2, ITOGO_DNI,
	SYST_PAY = CASE WHEN SYST_PAY = 2 THEN 'Почасовая система оплаты' else '' END,
	CODE_PAY, NAME_PAY,
	DATE_PER,
	TYP_PERIOD = CASE TYP_PERIOD WHEN 1 THEN '3 месяца' WHEN 2 THEN '12 месяцев' end,
	PAYMENT = CASE PAYMENT WHEN 1 THEN 'в рабочих днях' WHEN 2 THEN 'в календарных днях' end,
	NAME_TYP = NAME_TYP_ARHE
from dbo.DOCUMENTS_ADD_FUR C 
	INNER JOIN dbo.item_vacation iv ON C.REF_ARHE = IV.LINK
	INNER JOIN dbo.orders O ON IV.ORDER_LINK = O.LINK
	INNER JOIN dbo.order_types T on O.TYPE = T.CODE
where C.LINK = @LINK_DOC
UNION
Select  NAME_DOC = 'Расчет командировочных №' + RTRIM(C.[NUMBER]) + ' от ' + convert(varchar(10), C.[DATE], 104),
	NAME_DOC2 = 'Основание: приказ ' + RTRIM(LTRIM(t.[NAME])) + ' №' + RTRIM(O.NUMBER) + ' от ' + convert(varchar(10),O.[DATE],104),
	NAME_EMPL,
	TAB_NUMER,
	DATE1, DATE2, ITOGO_DNI,
	SYST_PAY = CASE WHEN SYST_PAY = 2 THEN 'Почасовая система оплаты' else '' END,
	CODE_PAY, NAME_PAY,
	DATE_PER,
	TYP_PERIOD = CASE TYP_PERIOD WHEN 1 THEN '3 месяца' WHEN 2 THEN '12 месяцев' end,
	PAYMENT = CASE PAYMENT WHEN 1 THEN 'в рабочих днях' WHEN 2 THEN 'в календарных днях' end,
	NAME_TYP = NAME_TYP_ARHE
from dbo.DOCUMENTS_CALC_TRAVEL C 
	INNER JOIN dbo.item_travel iv ON C.REF_ARHE = IV.LINK
	INNER JOIN dbo.orders O ON IV.ORDER_LINK = O.LINK
	INNER JOIN dbo.order_types T on O.TYPE = T.CODE
where C.LINK = @LINK_DOC
UNION
Select  NAME_DOC = CASE WHEN TYPE = 1 THEN 'Расчет компенсации за неиспользованный отпуск №' else 'Расчет по среднему №' end + RTRIM(C.[NUMBER]) + ' от ' + convert(varchar(10), C.[DATE], 104),
	NAME_DOC2 = '',
	NAME_EMPL,
	TAB_NUMER,
	DATE1, DATE2, ITOGO_DNI,
	SYST_PAY = CASE WHEN SYST_PAY = 2 THEN 'Почасовая система оплаты' else '' END,
	CODE_PAY, NAME_PAY,
	DATE_PER,
	TYP_PERIOD = CASE TYP_PERIOD WHEN 1 THEN '3 месяца' WHEN 2 THEN '12 месяцев' end,
	PAYMENT = CASE PAYMENT WHEN 1 THEN 'в рабочих днях' WHEN 2 THEN 'в календарных днях' end,
	NAME_TYP = NAME_TYP_ARHE
from dbo.DOCUMENTS_CALC_AVG C 
where C.LINK = @LINK_DOC


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

SELECT  @SCRIPT1 = '', @I = 1, @DATE_BEGIN_RP = DATE_PER,
	@RP_SUMMA_PREM = RP_SUMMA_PREM, @RP_SUMMA_MAT = RP_SUMMA_MAT, @RP_SUMMA = RP_SUMMA, 
	@SR_PREM = SR_PREM, @SYST_PAY = SYST_PAY,
	@RP_DAYS = RP_DAYS,	@RP_HOURS = RP_HOURS,
	@RP_DAYS_N = RP_DAYS_N , @RP_HOURS_N = RP_HOURS_N,
	@SUMMA_BASE0 = SUMMA_BASE, @ITOGO_DNI = ITOGO_DNI, @ITOGO_CH = ITOGO_CH,
	@INSTR = INSTR
FROM 	(
	Select DATE_PER, RP_SUMMA_PREM, RP_SUMMA, RP_SUMMA_MAT, SR_PREM, SYST_PAY, RP_DAYS, RP_HOURS, RP_DAYS_N, RP_HOURS_N, SUMMA_BASE, ITOGO_DNI, ITOGO_CH, INSTR from dbo.DOCUMENTS_ADD_FUR where LINK = @LINK_DOC
	UNION 
	Select DATE_PER, RP_SUMMA_PREM, RP_SUMMA, RP_SUMMA_MAT=0, SR_PREM, SYST_PAY, RP_DAYS, RP_HOURS, RP_DAYS_N, RP_HOURS_N, SUMMA_BASE, ITOGO_DNI, ITOGO_CH, INSTR from dbo.DOCUMENTS_CALC_TRAVEL where LINK = @LINK_DOC
	UNION 
	Select DATE_PER, RP_SUMMA_PREM, RP_SUMMA, RP_SUMMA_MAT=0, SR_PREM, SYST_PAY, RP_DAYS, RP_HOURS, RP_DAYS_N, RP_HOURS_N, SUMMA_BASE, ITOGO_DNI, ITOGO_CH, INSTR from dbo.DOCUMENTS_CALC_AVG where LINK = @LINK_DOC
	) DOC


---начисление по видам оплат
DECLARE @COUNT_M INT
SET @COUNT_M = COALESCE((Select COUNT(DISTINCT PERIOD) from SDOC_AVAC_TABLE2 where LINK_UP = @LINK_DOC),0) - (CASE WHEN @INSTR = 2 THEN 1 ELSE 0 END)
SET @COUNT_M = CASE WHEN @COUNT_M <= 0 THEN 1 ELSE @COUNT_M END
SET @COUNT_M = CASE WHEN @COUNT_M > 12 THEN 12 ELSE @COUNT_M END


IF EXISTS (Select LINK_UP from dbo.SDOC_AVAC_TABLE3 T3 where LINK_UP = @LINK_DOC)
BEGIN

	WHILE @I <= @COUNT_M
	BEGIN
		SET @SCRIPT1 = @SCRIPT1 
			+ ', N_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ' = CONVERT(DATETIME,''' + CONVERT(VARCHAR(10),DATEADD(MONTH,@I-1,@DATE_BEGIN_RP),104) + ''',104)'
			+ ', S_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))  + ' = SUMMA' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))
		SET @I = @I + 1
	END

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

	SET @SCRIPT1 = 'Select ORDERS, LINK_PAY, NAME_PAY = P.NAME, LINK_KBK, CODE_KBK = KBK.CODE ' + @SCRIPT1 
			+ ' from dbo.SDOC_AVAC_TABLE3 T3 INNER JOIN dbo.PAYS P ON T3.LINK_PAY = P.LINK '
			+ ' LEFT JOIN dbo.SAL_SFIN KBK ON T3.LINK_KBK = KBK.LINK WHERE LINK_UP = ' 
		+ CONVERT(VARCHAR(20),@LINK_DOC) + ' ORDER BY ORDERS'
END
ELSE
BEGIN --Если вручную заполнили суммы по месяцам, а по видам начислений данных нет

	WHILE @I <= @COUNT_M
	BEGIN
		SET @SCRIPT1 = @SCRIPT1 
			+ ', N_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ' = CONVERT(DATETIME,''' + CONVERT(VARCHAR(10),DATEADD(MONTH,@I-1,@DATE_BEGIN_RP),104) + ''',104)'
			+ ', S_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))  + ' = 0.00'
		SET @I = @I + 1
	END

	SET @I = 1
	SET @SCRIPT1 = @SCRIPT1 + ', SUM_N = 0'
	SET @SCRIPT1 = 'Select ORDERS=0, LINK_PAY=0, NAME_PAY = '''', LINK_KBK=0, CODE_KBK = '''' ' + @SCRIPT1 

END

exec (@SCRIPT1)

--Коэффициенты индексации
IF (	COALESCE((Select COUNT(distinct koef1) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef1,0) > 0 group by link_up having count(koef1) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef2) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef2,0) > 0 group by link_up having count(koef2) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef3) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef3,0) > 0 group by link_up having count(koef3) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef4) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef4,0) > 0 group by link_up having count(koef4) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef5) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef5,0) > 0 group by link_up having count(koef5) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef6) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef6,0) > 0 group by link_up having count(koef6) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef7) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef7,0) > 0 group by link_up having count(koef7) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef8) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef8,0) > 0 group by link_up having count(koef8) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef9) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef9,0) > 0 group by link_up having count(koef9) > 0 ),1)
	*COALESCE((Select COUNT(distinct koef10) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef10,0) > 0 group by link_up having count(koef10) > 0),1)
	*COALESCE((Select COUNT(distinct koef11) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef11,0) > 0 group by link_up having count(koef11) > 0),1)
	*COALESCE((Select COUNT(distinct koef12) from dbo.SDOC_AVAC_TABLE3 where LINK_UP = @LINK_DOC and coalesce(koef12,0) > 0 group by link_up having count(koef12) > 0),1) 
)  = 1 
BEGIN

	SET  @SCRIPT1 = 'Select distinct INSTR = ' + convert(varchar(1),@INSTR) + ', ORDERS = 1, NAME_PAY = ''для всех начислений'', CODE_KBK = ''для всех источников''' 
	SET  @I = 1
	WHILE @I <= @COUNT_M
	BEGIN
		SET @SCRIPT1 = @SCRIPT1 
			+ ', N_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ' = CONVERT(DATETIME,''' + CONVERT(VARCHAR(10),DATEADD(MONTH,@I-1,@DATE_BEGIN_RP),104) + ''',104)'
			+ ', S_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))  + ' = MAX(COALESCE(koef' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ',1))'
		SET @I = @I + 1
	END
	SET  @SCRIPT1 = @SCRIPT1 + ' from dbo.SDOC_AVAC_TABLE3 where LINK_UP = ' + CONVERT(VARCHAR(20),@LINK_DOC)
	exec (@SCRIPT1)

END
ELSE BEGIN

	SET  @SCRIPT1 = ''
	SET  @I = 1
	WHILE @I <= @COUNT_M
	BEGIN
		SET @SCRIPT1 = @SCRIPT1 
			+ ', N_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I))) + ' = CONVERT(DATETIME,''' + CONVERT(VARCHAR(10),DATEADD(MONTH,@I-1,@DATE_BEGIN_RP),104) + ''',104)'
			+ ', S_' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))  + ' = KOEF' + RTRIM(LTRIM(CONVERT(VARCHAR(2),@I)))
		SET @I = @I + 1
	END
	
	SET @SCRIPT1 = 'Select INSTR = ' + convert(varchar(1),@INSTR) + ', ORDERS, LINK_PAY, NAME_PAY = P.NAME, LINK_KBK, CODE_KBK = KBK.CODE ' + @SCRIPT1 
			+ ' from dbo.SDOC_AVAC_TABLE3 T3 INNER JOIN dbo.PAYS P ON T3.LINK_PAY = P.LINK '
			+ ' LEFT JOIN dbo.SAL_SFIN KBK ON T3.LINK_KBK = KBK.LINK WHERE LINK_UP = ' 
		+ CONVERT(VARCHAR(20),@LINK_DOC) + ' ORDER BY ORDERS'
	
	exec (@SCRIPT1)
END

		

DECLARE @DAYS_SZ NUMERIC(18,2)
--- Время за расчетный период
SELECT  [PERIOD],
	[DAYS_N] = MAX(DAYS_N) ,
	[HOURS_N] = MAX(HOURS_N),
	[DAYS] = MAX(DAYS) ,
	[HOURS] = MAX(HOURS),
	[KDAYS] = MAX(KDAYS),
	[KDAYS_N] = MAX(ISNULL(CONVERT(NUMERIC(4,0),DAY(dbo.DateEndOfMonth(PERIOD))),0))
INTO #TMP
FROM dbo.SDOC_AVAC_TABLE2 WHERE LINK_UP = @LINK_DOC
GROUP BY [PERIOD]

SELECT  
	@DAYS_SZ = SUM(
		CASE WHEN @PAYMENT = 1 THEN--В рабочих днях 
			CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
				CASE WHEN COALESCE(DAYS,0) >= COALESCE(DAYS_N,0) THEN COALESCE(DAYS_N,0) else COALESCE(DAYS,0) * 1.2 END
			ELSE DAYS --Рассчитываются не отпускные, а прочие начисления по среднему
			END
		ELSE --В календарных днях
			CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
					CASE WHEN COALESCE(KDAYS,0.00) <> 0 AND COALESCE(KDAYS,0.00) >= COALESCE(KDAYS_N,0.00) THEN @AvgDays else @AvgDays * (CASE WHEN COALESCE(KDAYS_N,0.00) <> 0.00 THEN COALESCE(KDAYS,0.00) / COALESCE(KDAYS_N,0.00) else 0.00 END) END
			ELSE KDAYS --Рассчитываются не отпускные, а прочие начисления по среднему
			END				
		END)
FROM #TMP

---начисление по месяцам
Select ORDERS, PERIOD, SUMMA, PREM, MATER, 
	DAYS = CASE WHEN @SYST_PAY = 2 THEN 0 ELSE DAYS END, 
	HOURS, 
	DAYS_N = CASE WHEN @SYST_PAY = 2 THEN 0 ELSE DAYS_N END, 
	HOURS_N, CODE_KBK = KBK.CODE, 
	RP_S_PREM = @RP_SUMMA_PREM, RP_SUMMA = @RP_SUMMA, RP_S_MAT = @RP_SUMMA_MAT, 
	RP_DAYS = @RP_DAYS,	RP_HOURS = @RP_HOURS,
	RP_DAYS_N = @RP_DAYS_N,	RP_HOURS_N = @RP_HOURS_N,
	SR_PREM = @SR_PREM, DSUM = @SUMMA_BASE0,
	SUM_DSZ = @DAYS_SZ,
	KOEF = 
	CASE WHEN @PAYMENT = 1 THEN--В рабочих днях 
		CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
			CASE WHEN COALESCE(DAYS,0) >= COALESCE(DAYS_N,0) THEN 1 else 1.2 END
		ELSE 1 --Рассчитываются не отпускные, а прочие начисления по среднему
		END
	ELSE --В календарных днях
	CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
			1
		ELSE 1 --Рассчитываются не отпускные, а прочие начисления по среднему
		END				
	END,
	DAYS_SZ = ROUND(
	CASE WHEN @PAYMENT = 1 THEN--В рабочих днях 
		CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
			CASE WHEN COALESCE(DAYS,0) >= COALESCE(DAYS_N,0) THEN COALESCE(DAYS_N,0) else COALESCE(DAYS,0) * 1.2 END
		ELSE DAYS --Рассчитываются не отпускные, а прочие начисления по среднему
		END
	ELSE --В календарных днях
		CASE WHEN (@OBJ_CODE = 'DOCUMENTS_ADD_FURLOUGH' OR @OBJ_CODE = 'DOCUMENTS_CALC_AVG' AND @SR_VID = 1) THEN
					CASE WHEN COALESCE(KDAYS,0.00) <> 0 AND COALESCE(KDAYS,0.00) >= COALESCE(KDAYS_N,0.00) THEN @AvgDays else @AvgDays * (CASE WHEN COALESCE(KDAYS_N,0.00) <> 0.00 THEN COALESCE(KDAYS,0.00) / COALESCE(KDAYS_N,0.00) else 0.00 END) END
		ELSE KDAYS --Рассчитываются не отпускные, а прочие начисления по среднему
		END				
	END,2)
from SDOC_AVAC_TABLE2 T2  LEFT JOIN dbo.SAL_SFIN KBK ON T2.LINK_KBK = KBK.LINK
where link_up = @LINK_DOC
ORDER BY PERIOD

---

DECLARE @FURLOUGH_OPT11 int -- Расчет с учетом районного коэффициента
SET @FURLOUGH_OPT11 = dbo.sa_get_option_by_code('FURLOUGH_OPT11')
---Накручиваем северный коэффициент, если надо
DECLARE @FURLOUGH_GOS_OPT5 int -- Расчет с учетом северного коэффициента
SET @FURLOUGH_GOS_OPT5 = dbo.sa_get_option_by_code('FURLOUGH_GOS_OPT5')

DECLARE @FURLOUGH_GOS_OPT4 varchar(10) --Дата применения районного коэффициента к мат. помощи
SET @FURLOUGH_GOS_OPT4 = COALESCE((SELECT VALUE FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('FURLOUGH_GOS_OPT4'))) AND SID IS NULL),'')
SET @FURLOUGH_GOS_OPT4 = CASE WHEN @FURLOUGH_GOS_OPT4 LIKE '%.  .%' THEN '' ELSE @FURLOUGH_GOS_OPT4 END

SET @FURLOUGH_GOS_OPT4 = CASE WHEN LTRIM(RTRIM(@FURLOUGH_GOS_OPT4)) = '' THEN '01.01.1900' else LTRIM(RTRIM(@FURLOUGH_GOS_OPT4)) END


select INSTR = @INSTR, CODE_PAYS = P.CODE, NAME_PAYS = P.NAME, S.SUMMA,
	RAION_S = S.SUMMA *
	CASE WHEN @FURLOUGH_OPT11 = 1 THEN
		CASE WHEN WAY_CALC = 12
			THEN (CASE WHEN @DATE_BEG >= CONVERT(DATETIME,@FURLOUGH_GOS_OPT4,104) THEN DBO.SA_GET_REGION(@LINK_EMPL,@DATE_BEG,1) / 100  ELSE 1 END) 
			ELSE DBO.SA_GET_REGION(@LINK_EMPL,@DATE_BEG,1) / 100
		END
	ELSE 0
	END,
	NORHT_S = S.SUMMA * CASE WHEN @FURLOUGH_GOS_OPT5 = 1 THEN DBO.SA_GET_REGION(@LINK_EMPL,@DATE_BEG,2) / 100 ELSE 0 END
INTO #TMPA
from 
	dbo.SA_ALL_PAYS_ALL_DATE0(@LINK_EMPL, @DATE_BEG, DEFAULT, @LINK_DEP) S
	inner join dbo.pays P on s.link_pay = p.link
where 
	WAY_CALC not in (6, 7, 12)
	AND
	s.link_pay IN (Select T.PAY_LINK FROM dbo.group_pays(@LINK_PAYS) T)

IF NOT EXISTS (SELECT * FROM #TMPA)
	INSERT INTO #TMPA (INSTR, CODE_PAYS, NAME_PAYS) 
	VALUES (1, '', '')

SELECT * FROM #TMPA

---начисление по расчету
Select ORDERS, DATE1, DATE2, DAYS, HOURS, KOEF_IDX, SR_ZP, SUMMA, 
	CODE_KBK = KBK.CODE, ITOGO_DNI = @ITOGO_DNI, ITOGO_CH = @ITOGO_CH
from SDOC_AVAC_TABLE1 T2  LEFT JOIN dbo.SAL_SFIN KBK ON T2.LINK_KBK = KBK.LINK
where link_up = @LINK_DOC 




GO


GRANT EXECUTE ON dbo.[SA_REP_FUR] TO PUBLIC

GO




GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

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

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

*******************************************************************************/
-- create table #FileExportReport (txt varchar(800), NameFile varchar(100), orders int)
CREATE PROCEDURE dbo.[RA_EXPORT_FORM_171]
	@iLINK_SAVED_FORM INT,	                  -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	         INT=1                   -- Формат: 1-внутренний, 2-минфиновский
AS

SET NOCOUNT ON

DECLARE @iORDER_BEGIN  INT,
        @iORDER_END    INT,
        @iORDER_INTRO  INT,
        @iORDER_EPILOG INT

DECLARE @tabFileExport TABLE ([TXT]	        VARCHAR(800), 
							         [NAMEFILE]    VARCHAR(100), 
                              [NAMEFILEARH] VARCHAR(100),
							         [ORDERS]      INT IDENTITY(1,1))  


EXEC dbo.[RA_EXPORT_FORM_STANDART] @iLINK_SAVED_FORM,
                                   @vcFILE_NAME OUTPUT,
                                   @iMODE                          



IF @iMODE = 2
BEGIN  
   -- Формирование ТБ=01
   SELECT @iORDER_INTRO = [ORDERS] + 2
   FROM #FileExportReport
   WHERE [TXT] = 'ТБ=01'
   
   INSERT @tabFileExport ([TXT], 
							     [NAMEFILE], 
                          [NAMEFILEARH])
   SELECT [TXT], 
          [NAMEFILE], 
          [NAMEFILEARH]
   FROM #FileExportReport
   WHERE [ORDERS] < @iORDER_INTRO
   
   SELECT @iORDER_BEGIN = [ORDERS] + 2
   FROM #FileExportReport
   WHERE [TXT] = 'ТБ=02'

   SELECT @iORDER_END = MIN([ORDERS]) - 1
   FROM #FileExportReport
   WHERE [ORDERS] >= @iORDER_BEGIN AND
         [TXT] = '#'
         
--SELECT    @iORDER_BEGIN, @iORDER_END  
         
   SET @iORDER_EPILOG = @iORDER_END 

   INSERT @tabFileExport ([TXT], 
			                 [NAMEFILE], 
			                 [NAMEFILEARH])
   SELECT [TXT], 
			 [NAMEFILE], 
			 [NAMEFILEARH]
   FROM #FileExportReport
   WHERE [ORDERS] BETWEEN @iORDER_BEGIN AND @iORDER_END AND
         [TXT] NOT LIKE '999|9999|9999999|999|9|99999|999|%'


   INSERT @tabFileExport ([TXT], 
			                 [NAMEFILE], 
			                 [NAMEFILEARH])
   SELECT [TXT] = '***|****|*******|***|' + [A].[CODE1]+'|'+[A].[CODE2]+'|'+[A].[CODE3]+'|***|-|-|'+
          ISNULL(CAST(SUM([VALUE]) AS VARCHAR(50)),'0') + '|-|-|',
          MAX([NAMEFILE]), 
          MAX([NAMEFILEARH])
   FROM (
      SELECT [CODE1] = dbo.[RA_GETWORDNUM]([TXT],5,'|'),
             [CODE2] = dbo.[RA_GETWORDNUM]([TXT],6,'|'),
             [CODE3] = dbo.[RA_GETWORDNUM]([TXT],7,'|'),
             [VALUE] = CAST(dbo.[RA_GETWORDNUM]([TXT],10,'|') AS NUMERIC(19,2)),
             [TXT],
             [NAMEFILE], 
             [NAMEFILEARH] 
      FROM #FileExportReport
      WHERE [ORDERS] BETWEEN @iORDER_BEGIN AND @iORDER_END AND
            [TXT] NOT LIKE '999|9999|9999999|999|9|99999|999|%'
                           
   ) [A]
   GROUP BY [A].[CODE1],[A].[CODE2],[A].[CODE3]
   
   INSERT @tabFileExport ([TXT], 
			                 [NAMEFILE], 
			                 [NAMEFILEARH])
   SELECT '***|****|*******|***|*|*****|***|***|' + SUBSTRING([TXT],38,8000),
			 [NAMEFILE], 
			 [NAMEFILEARH]
   FROM #FileExportReport
   WHERE [ORDERS] BETWEEN @iORDER_BEGIN AND @iORDER_END AND
            [TXT] LIKE '999|9999|9999999|999|9|99999|999|%' 
   
   -- Формирование ТБ=02
   INSERT @tabFileExport ([TXT], 
			                 [NAMEFILE], 
			                 [NAMEFILEARH])
   SELECT [TXT], 
          [NAMEFILE], 
          [NAMEFILEARH]
   FROM #FileExportReport
   WHERE [ORDERS] BETWEEN @iORDER_BEGIN-4 AND @iORDER_BEGIN-1

   SELECT @iORDER_BEGIN = [ORDERS] + 2
   FROM #FileExportReport
   WHERE [TXT] = 'ТБ=01'

   SELECT @iORDER_END = MIN([ORDERS]) - 1
   FROM #FileExportReport
   WHERE [ORDERS] >= @iORDER_BEGIN AND
         [TXT] = '#'

   INSERT @tabFileExport ([TXT], 
			                 [NAMEFILE], 
			                 [NAMEFILEARH])
   SELECT [TXT], 
			 [NAMEFILE], 
			 [NAMEFILEARH]
   FROM #FileExportReport
   WHERE [ORDERS] BETWEEN @iORDER_BEGIN AND @iORDER_END AND
         [TXT] NOT LIKE '888|8888|8888|88|8888|8|88888|888|%' AND
         [TXT] NOT LIKE '777|7777|7777|77|7777|7|77777|777|%' AND
         [TXT] NOT LIKE '000|0000|0000|00|0000|%'

   INSERT @tabFileExport ([TXT], 
			                 [NAMEFILE], 
			                 [NAMEFILEARH])
   SELECT [TXT] = '***|****|****|**|****|' + [A].[CODE1]+'|'+[A].[CODE2]+'|'+[A].[CODE3]+'|***|-|-|'+
          ISNULL(CAST(SUM([VALUE]) AS VARCHAR(50)),'0') + '|-|-|',
          MAX([NAMEFILE]), 
          MAX([NAMEFILEARH])
   FROM (
      SELECT [CODE1] = dbo.[RA_GETWORDNUM]([TXT],6,'|'),
             [CODE2] = dbo.[RA_GETWORDNUM]([TXT],7,'|'),
             [CODE3] = dbo.[RA_GETWORDNUM]([TXT],8,'|'),
             [VALUE] = CAST(dbo.[RA_GETWORDNUM]([TXT],11,'|') AS NUMERIC(19,2)),
             [TXT],
             [NAMEFILE], 
             [NAMEFILEARH] 
      FROM #FileExportReport
      WHERE [ORDERS] BETWEEN @iORDER_BEGIN AND @iORDER_END AND
            [TXT] NOT LIKE '888|8888|8888|88|8888|8|88888|888|%' AND
            [TXT] NOT LIKE '777|7777|7777|77|7777|7|77777|777|%' AND
            [TXT] NOT LIKE '000|0000|0000|00|0000|%'
   ) [A]
   GROUP BY [A].[CODE1],[A].[CODE2],[A].[CODE3]

   INSERT @tabFileExport ([TXT], 
			                 [NAMEFILE], 
			                 [NAMEFILEARH])
   SELECT '***|****|****|**|****|*|*****|***|***|' + SUBSTRING([TXT],39,8000),
			 [NAMEFILE], 
			 [NAMEFILEARH]
   FROM #FileExportReport
   WHERE [ORDERS] BETWEEN @iORDER_BEGIN AND @iORDER_END AND
            [TXT] LIKE '777|7777|7777|77|7777|7|77777|777|%' 

   -- Формирование ТБ=03
   INSERT @tabFileExport ([TXT], 
			                 [NAMEFILE], 
			                 [NAMEFILEARH])
   SELECT REPLACE([TXT],'ТБ=01','ТБ=03'),
          [NAMEFILE], 
          [NAMEFILEARH]
   FROM #FileExportReport
   WHERE [ORDERS] BETWEEN @iORDER_BEGIN-4 AND @iORDER_BEGIN-1

   INSERT @tabFileExport ([TXT], 
			                 [NAMEFILE], 
			                 [NAMEFILEARH])
   SELECT '***|**************|*|*****|***|***|' + SUBSTRING([TXT],39,8000),   
			 [NAMEFILE], 
			 [NAMEFILEARH]
   FROM #FileExportReport
   WHERE [ORDERS] BETWEEN @iORDER_BEGIN AND @iORDER_END AND
            [TXT] LIKE '888|8888|8888|88|8888|8|88888|888|%'

   INSERT @tabFileExport ([TXT], 
			                 [NAMEFILE], 
			                 [NAMEFILEARH])
   SELECT [TXT], 
          [NAMEFILE], 
          [NAMEFILEARH]
   FROM #FileExportReport
   WHERE [ORDERS] > @iORDER_EPILOG
   
   DELETE #FileExportReport
   
   INSERT #FileExportReport ([TXT], [NAMEFILE], [NAMEFILEARH], [ORDERS])
   SELECT [TXT], [NAMEFILE], [NAMEFILEARH], [ORDERS]
   FROM @tabFileExport
  
END


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

/*
exec BUFFERPUSH 9.900000000000000e+003, 'REPORT_ATR_EXPORT'
exec BUFFERPUSH 9.901000000000000e+003, 'REPORT_ATR_EXPORT'
create table #Reps (LSF int)
insert #Reps (LSF) values(      9900)
exec dbo.RO_EXPORT_REPORT '#Reps', 2.000000000000000e+000


exec BUFFERPUSH 9.935000000000000e+003, 'REPORT_ATR_EXPORT'
exec BUFFERPUSH 9.936000000000000e+003, 'REPORT_ATR_EXPORT'
create table #Reps (LSF int)
insert #Reps (LSF) values(      9935)
exec dbo.RO_EXPORT_REPORT '#Reps', 2.000000000000000e+000



*/



GO
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


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)
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].[BB_DELETE_PROG]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].BB_DELETE_PROG
GO
/*
© Кейсистемс (Keysystems), 2005
*/

CREATE     PROCEDURE dbo.BB_DELETE_PROG
	@varKSintLINK	int
AS
DECLARE @varKStrancount	int,
	@varKSObjectLink	int,
	@varKSEventText	varchar(254)

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	SELECT @varKSEventText = 'Справочник Программы\подпрограммы' + ' ' + STR(LINK) FROM dbo.KL_PROG WITH (UPDLOCK) WHERE LINK = @varKSintLINK
	IF @@RowCount = 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 2
	END
	DELETE FROM dbo.KL_PROG WHERE LINK = @varKSintLINK
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
IF @@TRANCOUNT > @varKStrancount
	BEGIN
		SELECT @varKSObjectLink = LINK FROM S_OBJECTS WHERE CODE = 'BB_DICTION_PROG'
		EXECUTE WF_GENERATEEVENT 'Удаление из справочника', @varKSEventText, @varKSObjectLink, 'KL_PROG', @varKSintLINK
		COMMIT TRAN
	END
RETURN 0






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on BB_DELETE_PROG to public
GO

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

GO

CREATE PROCEDURE DBO.I_REPORT_FORMULA_P4_PREPARE
	@OUT_VAL 	VARCHAR(20) OUTPUT,
	@BDATE		DATETIME,
	@ENDDATE	DATETIME,
	@DEP_LINK	INT,
	@VARILSF	INT
AS BEGIN
	DECLARE @PEOPLE_COUNT VARCHAR(100)
	EXEC DBO.X_GET_TABLE_NAME @PEOPLE_COUNT OUTPUT
	EXEC DBO.I_REPORT_FORMULA_ERASE_TABLES 0

DECLARE @FILTER_SUBDIV_NAME VARCHAR(254), @FILTER_SUBDIV_LINK INT
DECLARE @SUBDIV TABLE (LINK INT)

SET @FILTER_SUBDIV_NAME = (SELECT DBO.RN_GET_ATR_VALUE(@VARILSF, 'REPORTS_FILTER_SUBDIV'))

IF @FILTER_SUBDIV_NAME IS NOT NULL
	SET @FILTER_SUBDIV_LINK = 
		( SELECT TOP 1 LINK FROM DBO.REPORT_KBK 
		WHERE ('№' + CONVERT(VARCHAR(3),PROPERTY) + ' - ' + NAME) = @FILTER_SUBDIV_NAME
			AND CODE_FORM='FILTER_NABOR' AND CODE='REPORTS_FILTER_SUBDIV')

DECLARE @BUFFER_SUBDIV VARCHAR(20)

IF @FILTER_SUBDIV_LINK IS NOT NULL 
BEGIN

	EXEC DBO.GETRANDSTR 20, @BUFFER_SUBDIV OUT

	INSERT INTO @SUBDIV (LINK) 
	SELECT LINK FROM DBO.RN_VIEW_FILTER WHERE LINK_SELF = @FILTER_SUBDIV_LINK

END

/**********************************************************************************************************************/
/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/
DECLARE @D1	DATETIME,
	@D2	DATETIME,
	@DBYEAR DATETIME

/* ДАЖЕ ЕСЛИ КВАРТАЛЬНАЯ ФОРМА, МЕСЯЧНЫЕ ДАНЫЕ БЕРУТСЯ ЗА ПОСЛЕДНИЙ МЕС. КВАРТАЛА */
SET @D1 = DBO.DATEBEGINOFMONTH (@ENDDATE) 
SET @D2 = DATEADD(MONTH,1,@D1)-1
SET @DBYEAR = DBO.DATEBEGINOFYEAR(@BDATE)

DECLARE @SALARY_OPTIONS_OPT7_1 INT 
SET @SALARY_OPTIONS_OPT7_1 =  dbo.SA_GET_OPTION_BY_CODE('SALARY_OPTIONS_OPT7_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))


/*** НАЧАЛЬНЫЕ УСТАНОВКИ ***/
/* ТАБЛИЦА РЕЗУЛЬТАТОВ РАСЧЕТА (СТОЛБЕЦ/ЗНАЧЕНИЕ) */
CREATE  TABLE #P4_PART1(COL	INT, VAL NUMERIC(18,1), VAL_STR VARCHAR(20))

INSERT INTO #P4_PART1 (COL, VAL_STR)
SELECT TOP 1 1 AS COL, OKVED FROM dbo.DEPARTMENTS WHERE LINK = @DEP_LINK


/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ */
IF @CNT > 15 
	INSERT INTO #P4_PART1 (COL, VAL) SELECT 2, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@D1, @D2, @DEP_LINK, 0, 1, 0, @BUFFER_SUBDIV))
ELSE	
	INSERT INTO #P4_PART1 (COL, VAL) SELECT 2, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@DBYEAR, @D2, @DEP_LINK, 0, 1, 0, @BUFFER_SUBDIV))

/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */
IF @CNT > 15 
	INSERT INTO #P4_PART1 (COL, VAL) SELECT 3, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@D1, @D2, @DEP_LINK, 0, 3, 0, @BUFFER_SUBDIV))
ELSE
	INSERT INTO #P4_PART1 (COL, VAL) SELECT 3, CONVERT(NUMERIC(18,1), DBO.SA_SSCH_EMPLS(@DBYEAR, @D2, @DEP_LINK, 0, 3, 0, @BUFFER_SUBDIV))


if @SALARY_OPTIONS_OPT7_1 = 1 
begin 
	update  p 
		set val = CEILING(p.val)  
	from #P4_PART1 p where p.col in (2)
end 

if @SALARY_OPTIONS_OPT7_1 = 2 
begin 
	update  p 
		set val = CEILING(p.val)  
	from #P4_PART1 p where p.col in (2,3)
end 


		
DELETE FROM DBO.BUFFER WHERE ID = @BUFFER_SUBDIV AND @BUFFER_SUBDIV IS NOT NULL	

CREATE TABLE #EMPL (LINK INT, PERS_LINK INT, DEP_LINK INT, [STATUS] TINYINT, PERIOD_BEG DATETIME, PERIOD_END DATETIME)
INSERT INTO #EMPL
SELECT 
	EMPL_LINK, PERS_LINK, DEP_LINK, [STATUS], PERIOD_BEG, PERIOD_END 
FROM 
	DBO.SA_EMPLS_INFO_PERIOD(@D1, @D2, DEFAULT, @DEP_LINK)
WHERE 
	(
	@BUFFER_SUBDIV IS NULL 
		OR 
	@BUFFER_SUBDIV IS NOT NULL AND SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
	)
ORDER BY 
	DEP_LINK, EMPL_LINK

CREATE TABLE #EMPL1 (LINK INT, PERS_LINK INT, DEP_LINK INT, [STATUS] TINYINT, PERIOD_BEG DATETIME, PERIOD_END DATETIME)
INSERT INTO #EMPL1
SELECT 
	EMPL_LINK, PERS_LINK, DEP_LINK, [STATUS], PERIOD_BEG, PERIOD_END 
FROM 
	DBO.SA_EMPLS_INFO_PERIOD(@BDATE, @D2, DEFAULT, @DEP_LINK)
WHERE 
	(
	@BUFFER_SUBDIV IS NULL 
		OR 
	@BUFFER_SUBDIV IS NOT NULL AND SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
	)
ORDER BY 
	DEP_LINK, EMPL_LINK

--ПОДКОРРЕКТИРУЕМ КОНЕЧНУЮ ДАТУ ДЛЯ ТЕХ, КТО ПЕРЕВОДИЛСЯ, ДЛЯ ТОГО ЧТОБЫ ОПРЕДЕЛИТЬ СУММЫ НАЧИСЛЕНИЙ, НАЧИСЛЕННЫХ ПОСЛЕ ДАТЫ ИХ УВОЛЬНЕНИЯ
UPDATE E
SET E.PERIOD_END = @D2
FROM 
	#EMPL E
	INNER JOIN (SELECT LINK, MAX_PERIOD_END = MAX(PERIOD_END) FROM  #EMPL E1 GROUP BY LINK HAVING COUNT(*) > 1) A 
		ON E.LINK = A.LINK AND E.PERIOD_END = A.MAX_PERIOD_END
WHERE
	A.MAX_PERIOD_END < @D2

--ПОДКОРРЕКТИРУЕМ КОНЕЧНУЮ ДАТУ ДЛЯ ТЕХ, КТО ПЕРЕВОДИЛСЯ, ДЛЯ ТОГО ЧТОБЫ ОПРЕДЕЛИТЬ СУММЫ НАЧИСЛЕНИЙ, НАЧИСЛЕННЫХ ПОСЛЕ ДАТЫ ИХ УВОЛЬНЕНИЯ
UPDATE E
SET E.PERIOD_END = @D2
FROM 
	#EMPL1 E
	INNER JOIN (SELECT LINK, MAX_PERIOD_END = MAX(PERIOD_END) FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1) A 
		ON E.LINK = A.LINK AND E.PERIOD_END = A.MAX_PERIOD_END
WHERE
	A.MAX_PERIOD_END < @D2		

/* ДОГОВОРНИКИ */
DECLARE @M NUMERIC(18,2) 

IF @CNT > 15
	SELECT --За месяц
		@M=SUM(CASE 
			WHEN DGH.DATE1<=@D1 AND COALESCE(DGH.DATE2,@D2)>=@D2 THEN DATEDIFF(DAY,@D1,@D2)		-- РАБОТАЛ ВЕСЬ ПЕРИОД
			WHEN DGH.DATE1<=@D1 AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE2>@D1 THEN DATEDIFF(DAY,@D1,DGH.DATE2)+1	-- УВОЛЕН В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@D1  AND COALESCE(DGH.DATE2,@D2)>=@D2 AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,@D2) 		-- ПРИНЯТ В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@D1  AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,DGH.DATE2)+1	-- ПРИНЯТ И УВОЛЕН В РАБОЧИЙ ПЕРИОД
			 ELSE 0
		END)
	FROM 
		dbo.REESTR_DGH DGH
	WHERE
			DEP_LINK = @DEP_LINK 
		AND
			DGH.DATE1 <= @D2 AND DGH.DATE2 >= @D1
		AND
		NOT EXISTS (
			SELECT E.PERS_LINK FROM DBO.SD_EMPL_FN(DEFAULT,@D2,DEFAULT,@DEP_LINK) E
			WHERE DGH.PERS_LINK = E.PERS_LINK AND DGH.DATE1 <= ISNULL(E.DATE_END,ISNULL(DGH.DATE2,@D2)) AND ISNULL(DGH.DATE2,@D2) >= E.DATE_BEGIN 
			)
ELSE
	SELECT --С начала года
		@M=SUM(CASE 
			WHEN DGH.DATE1<=@DBYEAR AND COALESCE(DGH.DATE2,@D2)>=@D2 THEN DATEDIFF(DAY,@DBYEAR,@D2)		-- РАБОТАЛ ВЕСЬ ПЕРИОД
			WHEN DGH.DATE1<=@DBYEAR AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE2>@DBYEAR THEN DATEDIFF(DAY,@DBYEAR,DGH.DATE2)+1	-- УВОЛЕН В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@DBYEAR  AND COALESCE(DGH.DATE2,@D2)>=@D2 AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,@D2) 		-- ПРИНЯТ В РАБОЧИЙ ПЕРИОД
			WHEN DGH.DATE1>@DBYEAR  AND COALESCE(DGH.DATE2,@D2)<@D2  AND DGH.DATE1<@D2 THEN DATEDIFF(DAY,DGH.DATE1,DGH.DATE2)+1	-- ПРИНЯТ И УВОЛЕН В РАБОЧИЙ ПЕРИОД
			 ELSE 0
		END)
	FROM 
		dbo.REESTR_DGH DGH
	WHERE
			DEP_LINK = @DEP_LINK 
		AND
			DGH.DATE1 <= @D2 AND DGH.DATE2 >= @DBYEAR
		AND
		NOT EXISTS (
			SELECT E.PERS_LINK FROM DBO.SD_EMPL_FN(DEFAULT,@D2,DEFAULT,@DEP_LINK) E
			WHERE DGH.PERS_LINK = E.PERS_LINK AND DGH.DATE1 <= ISNULL(E.DATE_END,ISNULL(DGH.DATE2,@D2)) AND ISNULL(DGH.DATE2,@D2) >= E.DATE_BEGIN 
			)				

DECLARE	@NDAYSFEBR	INT
IF @CNT > 15
	SET @NDAYSFEBR = DAY(DBO.DATEENDOFMONTH(@D1))
ELSE
	SET @NDAYSFEBR = ISNULL((SELECT SUM(DAY(DBO.DATEENDOFMONTH(DATE_BEGIN))) FROM dbo.MONTHS_EX(@DBYEAR, @D2)),99999999)

INSERT INTO #P4_PART1 (COL, VAL)
SELECT 4 AS COL, @M/@NDAYSFEBR

if @SALARY_OPTIONS_OPT7_1 = 1 
begin 
	update  p 
		set val = ROUND(p.val,0) 
	from #P4_PART1 p where p.col = 4
end 

if @SALARY_OPTIONS_OPT7_1 = 2 
begin 
	update  p 
		set val = CEILING(p.val)  
	from #P4_PART1 p where p.col =4
end 


/*
declare @a float 
set @a = '' 
 exec I_REPORT_FORMULA_P4_PREPARE @a output, '20130101' , '20131231' ,74578 ,  39348 
 */
---- ВСЕГО (СУММА ГРАФ 2,3,4)
--INSERT INTO #P4_PART1
--SELECT 1 AS COL, SUM(VAL) FROM #P4_PART1 WHERE COL > 1

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

/*КОЛИЧЕСТВО ОТРАБОТАННЫХ ЧЕЛОВЕКО-ЧАСОВ С НАЧАЛА ГОДА РАБОТНИКАМИ СПИСОЧНОГО СОСТАВА*/
INSERT INTO #P4_PART1 (COL, VAL)
SELECT [STATUS],  DBO.MINUTES_TO_NUM(SUM(DBO.NUM_TO_MINUTES([HOURS],@ISMINUTES)),@ISMINUTES)
FROM
(
	SELECT 
		[STATUS] = (CASE WHEN F.[STATUS] <> 3 THEN 5 ELSE 6 END),
		[HOURS] = DBO.SA_GET_EMPL_WH(LINK, DEFAULT,DEFAULT,PERIOD_BEG,PERIOD_END,DEFAULT,DEFAULT) 
	FROM 
		#EMPL1 F
) A
GROUP BY [STATUS]

-- очистка лишних задвоений для тех у кого перевод, и дальнейшая работа происходила в течении месяца
delete FROM 
	#EMPL1 
WHERE
	LINK in (SELECT LINK FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1 ) 
	AND PERIOD_END not in (SELECT min(PERIOD_END) FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1 /*and  min(PERIOD_END) = @D2*/ ) 

/* ФОНД НАЧИСЛ З/ПЛАТЫ */
CREATE  TABLE #P4_S_J_C (SUMMA NUMERIC(20,1), STAT_OTCHET TINYINT, DEP_TYPE TINYINT, COL TINYINT, PERIOD_END DATETIME)

DECLARE @LINKEKR213 INT
SELECT @LINKEKR213 = LINK FROM DBO.DICTIONARY_ITEM WHERE CODE = '213'

CREATE TABLE #CJ (PERS_LINK INT, LINK_EMPL INT, LINK_PAYS INT, PERIOD_END DATETIME, SUMMA NUMERIC(18,2), STAT_OTCHET TINYINT, WAY_CALC TINYINT, DEP_TYPE TINYINT)

INSERT INTO #CJ (PERS_LINK, LINK_EMPL, LINK_PAYS, PERIOD_END, SUMMA, STAT_OTCHET, WAY_CALC, DEP_TYPE)
SELECT 
	PERS_LINK, LINK_EMPL, LINK_PAYS, 
	CASE WHEN WAY_CALC <> 15 THEN JC.PERIOD_BEGIN ELSE JC.DATE_BEGIN END, 
	SUMMA, STAT_OTCHET, WAY_CALC,
	CASE WHEN PERS_LINK IS NULL THEN 0 ELSE 5 END /* 5 - ФИЗ ЛИЦО */
FROM
	DBO.CALCULATE_JURNAL JC 
	INNER JOIN DBO.PAYS P ON JC.LINK_PAYS = P.LINK 
WHERE
	P.[OBJECT] = 1 /* ТОЛЬКО НАЧИСЛЕНИЯ */
	AND (P.WAY_CALC <> 15 AND YEAR(JC.PERIOD_BEGIN)=  YEAR(@D1) AND MONTH(JC.PERIOD_BEGIN) <= MONTH(@D1)
 		OR P.WAY_CALC = 15 AND YEAR(JC.DATE_BEGIN)=  YEAR(@D1) AND MONTH(JC.DATE_BEGIN) <= MONTH(@D1))	
	AND P.STAT_OTCHET <> 3
	AND JC.LINK_DEP = @DEP_LINK

----------- суммы договорников, которые являются сотрудниками помеячаем считать как для сотрудников
UPDATE J
SET LINK_EMPL = E.LINK, DEP_TYPE = 0
FROM #CJ J INNER JOIN #EMPL E ON E.PERS_LINK = J.PERS_LINK AND J.[PERIOD_END] BETWEEN E.PERIOD_BEG AND E.PERIOD_END
		
------------
INSERT INTO #P4_S_J_C 
SELECT SUMMA, STAT_OTCHET, DEP_TYPE, COALESCE(F.COL,0), J.[PERIOD_END]
FROM #CJ J INNER JOIN (SELECT LINK, (CASE WHEN STATUS=3 THEN 9 ELSE 8 END) AS COL, PERIOD_BEG, PERIOD_END FROM #EMPL1) F 
		ON J.LINK_EMPL = F.LINK AND YEAR(J.[PERIOD_END]) * 100 + MONTH(J.[PERIOD_END]) 
				BETWEEN YEAR(F.PERIOD_BEG) * 100 + MONTH(F.PERIOD_BEG) AND YEAR(F.PERIOD_END) * 100 + MONTH(F.PERIOD_END)


------------		
INSERT INTO #P4_S_J_C
SELECT SUMMA, STAT_OTCHET, DEP_TYPE, 0, PERIOD_END
FROM #CJ WHERE LINK_EMPL IS NULL


	/* COL8! */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 8, SUM(SUMMA)/1000 FROM #P4_S_J_C
		WHERE COL=8 AND STAT_OTCHET=1 AND DEP_TYPE<>5
			AND  
			(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)

	/* COL9! */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 9, SUM(SUMMA)/1000 FROM #P4_S_J_C
		WHERE COL=9 AND STAT_OTCHET=1 AND DEP_TYPE<>5
			AND 
			(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)

	/* COL10! */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 10, SUM(SUMMA)/1000 FROM #P4_S_J_C
		WHERE STAT_OTCHET=1 AND DEP_TYPE=5
			AND 
			(	@CNT <= 15 AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				OR
				@CNT > 15 AND MONTH(PERIOD_END) = MONTH(@ENDDATE)
			)
	/* COL11! С НАЧАЛА ГОДА ЗА I КВАРТАЛ, I ПОЛУГОДИЕ, 9 МЕСЯЦЕВ, ГОД */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 11, SUM(SUMMA)/1000 FROM #P4_S_J_C
			WHERE STAT_OTCHET=2 -- СОЦВЫПЛАТЫ
				AND MONTH(PERIOD_END) <= MONTH(@ENDDATE)
				--AND MONTH(@ENDDATE) % 3 = 0


/* РАЗД. 3 - ДВИЖЕНИЕ РАБОТНИКОВ */
	/* ROW 21 */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 21, COUNT(*) FROM ITEM_MOVE I LEFT JOIN #EMPL1 DF ON I.EMPL_LINK = DF.LINK AND I.DATE_BEGIN BETWEEN DF.PERIOD_BEG AND DF.PERIOD_END
			WHERE DF.DEP_LINK = @DEP_LINK
				AND NEW_FACE = 1
				AND I.DATE_BEGIN >= @DBYEAR AND I.DATE_BEGIN <= @ENDDATE

	/* ROW 22 */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 22, COUNT(*) FROM ITEM_MOVE I LEFT JOIN #EMPL1 DF ON I.EMPL_LINK = DF.LINK AND I.DATE_BEGIN BETWEEN DF.PERIOD_BEG AND DF.PERIOD_END
			WHERE DF.DEP_LINK = @DEP_LINK 
				AND NEW_FACE = 1
				AND I.DATE_BEGIN >= @DBYEAR AND I.DATE_BEGIN <= @ENDDATE
				AND I.STAFF_LINK IN ( SELECT LINK_UP FROM STAFF WHERE DATE_BEGIN >= @DBYEAR)

	/* ROW 23 */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 23, COUNT(*) FROM ITEM_DIS_FACE I LEFT JOIN #EMPL1 DF ON I.EMPL_LINK = DF.LINK AND I.DIS_DATE BETWEEN DF.PERIOD_BEG AND DF.PERIOD_END
			WHERE DF.DEP_LINK = @DEP_LINK
				AND DIS_DATE >= @DBYEAR AND DIS_DATE <= @ENDDATE

	/* ROW 24 */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 24, COUNT(*) FROM ITEM_DIS_FACE I LEFT JOIN #EMPL DF ON I.EMPL_LINK = DF.LINK AND I.DIS_DATE BETWEEN DF.PERIOD_BEG AND DF.PERIOD_END
			WHERE DF.DEP_LINK = @DEP_LINK 
				AND DIS_DATE >= @DBYEAR AND DIS_DATE <= @ENDDATE
				AND REASON IN (SELECT LINK FROM DICTIONARY_PUV WHERE CODE = '0402')
	
	/* ROW 26 */
	INSERT INTO #P4_PART1 (COL, VAL)
		SELECT 26, COUNT(*) 
		FROM 
			DBO.ITEM_DIS_FACE I 
			INNER JOIN DBO.DICTIONARY_PUV DP ON DP.LINK = I.REASON
			LEFT JOIN #EMPL1 DF ON I.EMPL_LINK = DF.LINK AND I.DIS_DATE BETWEEN DF.PERIOD_BEG AND DF.PERIOD_END
		WHERE DF.DEP_LINK = @DEP_LINK 
				AND DIS_DATE >= @DBYEAR AND DIS_DATE <= @ENDDATE
				AND DP.CODE IN ('0300','0707','2030','2016','0000')
	
	/* ROW 27 */
	INSERT INTO #P4_PART1 (COL, VAL) 
	SELECT 27, @CNT

	--СВОБОДНЫЕ СТАВКИ
	INSERT INTO #P4_PART1 (COL, VAL)
	SELECT 28, SUM(S.FREE_STAKES)
	FROM DBO.DICTIONARY_STAFF_FN(@ENDDATE) S 
		INNER JOIN DBO.DICTIONARY_SUBDIVISION_FN(@ENDDATE) D ON D.LINK = S.SUBDIV_LINK
	WHERE 
		S.DELETED = 0 AND S.DEP_LINK = @DEP_LINK
		AND D.DELETED = 0
		AND (
				@BUFFER_SUBDIV IS NULL
				OR
				@BUFFER_SUBDIV IS NOT NULL AND S.SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
			)				
--select * from #P4_PART1
DROP TABLE #P4_S_J_C

/**********************************************************************************************************************/
/* СОЗДАЕМ ВРЕМЕНННУЮ ТАБЛИЦУ */
DECLARE @RESULT_TABLE VARCHAR(100)
EXEC DBO.X_GET_TABLE_NAME @RESULT_TABLE OUTPUT

EXEC DBO.I_REPORT_FORMULA_ERASE_TABLES 0
EXEC ('SELECT * INTO ' + @RESULT_TABLE + ' FROM #P4_PART1 ')
EXEC DBO.BUFFERPUSH -151, @RESULT_TABLE
	SET @OUT_VAL = ''
DROP TABLE #P4_PART1
END









GO


GRANT EXECUTE ON dbo.[I_REPORT_FORMULA_P4_PREPARE] TO PUBLIC

GO


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

GO
CREATE PROCEDURE dbo.SA_RSV1_EXPORT_TEST (@Res tinyint output, @link int, @m int) 
AS
BEGIN

	DECLARE @LINK_DEP INT
	SELECT @LINK_DEP = LINK_ORGANIZATION FROM dbo.REPORT_SAVED_FORMS WHERE LINK_SAVED_FORM = @link

	SELECT 				
		D.PFNUMBER,
		D.TFOMS_REG_NUM,
		D.OKATO AS OKATO,
		D.OKTMO,
		D.INN,
		D.OKVED,
		D.KPP,
		D.OKPO,
		D.OGRN,
		D.OKOPF,
		D.OKFS,
		GB_PHONE = GLBUH.PHONE,
		D.KLADR_LINK,
		D.TFOMS_KT,
		GLBUH_FIO = GLBUH.FM
	INTO #TMP	
	FROM 
		dbo.DEPARTMENTS D
		LEFT JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Главный бухгалтер') GLBUH ON GLBUH.link_dep = d.link
	WHERE 
		D.LINK = @LINK_DEP
	
	-- Проставлять ОКАТО или ОКТМО по настройке
	DECLARE @OKATO_OR_OKTMO int
	SET @OKATO_OR_OKTMO = dbo.SA_GET_OPTION_BY_CODE('NASTR_USE_OKATO_OKTMO') 
	
	
	SET @Res = 1		
	CREATE TABLE #ERR_MSG (MSG_BEFORE VARCHAR(254),Msg VARCHAR(254),msg_after VARCHAR(254))

	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(PFNUMBER,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Регистрационный номер в ПФР.',
			msg_after  = 'Необходимо указать Регистрационный номер в ПФР в настройках организации на вкладке РЕКВИЗИТЫ.'
	END

	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(INN,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ИНН',
			msg_after  = 'Необходимо указать ИНН в настройках организации на вкладке РЕКВИЗИТЫ.'
	END		
	
	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(KPP,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'КПП',
			msg_after  = 'Необходимо указать КПП в настройках организации на вкладке РЕКВИЗИТЫ.'
	END	

	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(OKPO,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКПО',
			msg_after  = 'Необходимо указать ОКПО в настройках организации на вкладке РЕКВИЗИТЫ.'
	END	

	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(OKPO,'')))) > 10) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Неверно указаны следующие реквизиты:',
			Msg = 'ОКПО не должен быть больше 10 знаков',
			msg_after  = 'Необходимо исправить ОКПО в настройках организации на вкладке РЕКВИЗИТЫ.'
	END		
	
	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(OGRN,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОГРН',
			msg_after  = 'Необходимо указать ОГРН в настройках организации на вкладке РЕКВИЗИТЫ.'
	END	
	
	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(GLBUH_FIO,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Ф.И.О. главного бухгалтера',
			msg_after  = 'Необходимо указать "Ф.И.О. главного бухгалтера" в настройках организации на вкладке ОТВЕТСТВЕННЫЕ ЛИЦА.'
	END

	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(GB_PHONE,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Телефон главного бухгалтера',
			msg_after  = 'Необходимо указать "Телефон главного бухгалтера" в настройках организации на вкладке ОТВЕТСТВЕННЫЕ ЛИЦА.'
	END
	
	
	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(OKATO,'')))) = 0) AND @OKATO_OR_OKTMO = 1 BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКАТО',
			msg_after  = 'Необходимо указать ОКАТО в настройках организации на вкладке АДРЕС.'
	END


	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(OKTMO,'')))) = 0) AND @OKATO_OR_OKTMO = 2 BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКТМО',
			msg_after  = 'Необходимо указать ОКТМО в настройках организации на вкладке АДРЕС.'
	END

	IF EXISTS (SELECT * FROM #TMP WHERE KLADR_LINK IS NULL) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Адрес организации',
			msg_after  = 'Необходимо указать "Адрес организации" в настройках организации на вкладке АДРЕС.'
	END				
	
	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(TFOMS_REG_NUM,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Регистрационный номер в ТФОМС.',
			msg_after  = 'Необходимо указать Регистрационный номер в ТФОМС в настройках организации на вкладке ПРОЧИЕ.'
	END	

	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(OKVED,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКВЭД',
			msg_after  = 'Необходимо указать ОКВЭД в настройках организации на вкладке ПРОЧИЕ.'
	END	


	
	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(OKOPF,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКОПФ',
			msg_after  = 'Необходимо указать ОКОПФ в настройках организации на вкладке ПРОЧИЕ.'
	END			

	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(OKFS,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКФС',
			msg_after  = 'Необходимо указать ОКФС в настройках организации на вкладке ПРОЧИЕ.'
	END

	IF EXISTS (SELECT * FROM #TMP WHERE LEN(LTRIM(RTRIM(ISNULL(TFOMS_KT,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Код тарифа',
			msg_after  = 'Необходимо указать "Код тарифа" в настройках организации на вкладке ПРОЧИЕ.'
	END	
	
	IF EXISTS (SELECT * FROM #TMP WHERE LTRIM(RTRIM(ISNULL(TFOMS_KT,''))) NOT IN ('01','02','03','04','05','09'))  BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Неверно указаны следующие реквизиты:',
			Msg = 'Код тарифа может принимать одно из возможных значений: 01, 02, 03, 04, 05, 09',
			msg_after  = 'Необходимо исправить "Код тарифа" в настройках организации на вкладке ПРОЧИЕ.'
	END		
	
	SELECT * FROM #ERR_MSG	
	
END





GO


GRANT EXECUTE ON dbo.[SA_RSV1_EXPORT_TEST] TO PUBLIC

GO



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

GO


CREATE PROCEDURE [dbo].[RO_CALC_NASTR]
	@intIS_NOT_CALC	TINYINT OUTPUT,
	@varKSiLSF		INT,
	@varKSiLT		INT = NULL,
	@varKSiOrderCol	INT = 0, -- внутренний порядок
	@varKScCodeRow	varchar(50) = '',
	@varKSfValue	float = 0 output 
AS

DECLARE @ldEnd		  DATETIME,
		@ldBegin      DATETIME,
		@liYear       INT,
		@ADM_CODE	  CHAR(3),
		@dCALC_DATE	  DATETIME,
		@iDEP_LINK	  INT,
		@LF		int, @LT int,
		@execStr		varchar(8000),
		@LC			int,
		@bid		varchar(100),
		@nabor_filter varchar(100),
		@orderCol	int,
		@iLinkCalcForm int,
		@lbKBK_FILTER int,
		@iForm737 tinyint

SET @intIS_NOT_CALC = 0

if exists(select * from dbo.REPORT_FORMS RF 
					inner join dbo.REPORT_SAVED_FORMS RSF on RF.Link_Form = RSF.Link_Form and RSF.Link_Saved_Form = @varKSiLSF
					where left(RF.CODE,7) = '0503737')
	set @iForm737 = 1
else	
	set @iForm737 = 0
	
declare @temp_nastr1 table (link int, [Link_Col] int NOT NULL, [Code_Row] varchar(50) NOT NULL,
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL, dt_z int, kt_z int, dt_mask varchar(1000), kt_mask varchar(1000), 
	dt_ekr varchar(1000), kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint)


declare @temp_nastr table (link int, [Link_Col] int NOT NULL, [Code_Row] varchar(50) NOT NULL,
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL, link_dt int, link_kt int, dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint)
declare @temp_nastr_xor table (	link int, [Link_Col] int NOT NULL , [Code_Row] varchar(50) NOT NULL,
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_dt int, link_kt int, dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, dt_kt tinyint)
declare @temp_nastr_rest table (	link int, [Link_Col] int NOT NULL , [Code_Row] varchar(50) NOT NULL,
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000),
	[type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint)
declare @temp_nastr_rest_xor table (link int, [Link_Col] int NOT NULL , [Code_Row] varchar(50) NOT NULL,
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000),
	[type] tinyint, type_kbk tinyint, dt_kt tinyint)

declare @filter_kbk table (kbk varchar(20))

CREATE TABLE #tTemp  (KBK varchar(50), Link_Col int, SUMMA FLOAT, Calc_Order int)
declare @t_Col table (Link_Col int, orderCol int)

-------- ЧИТАЕМ ДАННЫЕ ОТЧЕТА
select @LF = RSF.Link_Form, 
		@iDEP_LINK 	= Link_Organization, 
		@ldEnd		= Begin_Date + 1,
		@dCALC_DATE	= Begin_Date, 
		@liYear		= YEAR(Begin_Date),
		@ldBegin	= dbo.DateBeginOfYear(Begin_Date)
from report_saved_forms RSF  where RSF.link_saved_form = @varKSiLSF

--- Поиск расчета по заданным атрибутам ---
/*
set @iLinkCalcForm = (select top 1 CF.LINK
			from dbo.REPORT_ATRIBUT_VALUES RA
			inner join dbo.REPORT_CALC_ATRIBUTE CA on RA.code_atr = CA.code_atr
			inner join dbo.REPORT_CALC_FORMS CF on CA.LINK_CALC_FORM = CF.LINK and CF.LINK_FORM = @LF
			where RA.LINK_SAVED_FORM = @varKSiLSF and CF.USED = 1 
			order by CF.[ORDER] desc)

--- Если нет расчета с заданными атрибутами, то поиск расчета без атрибутов ---
IF @iLinkCalcForm is null 
	set @iLinkCalcForm = (select top 1 CF.LINK
				from dbo.REPORT_CALC_FORMS CF 
				where CF.LINK_FORM = @LF and CF.USED = 1 
				order by CF.[ORDER] desc)

*/
SET @iLinkCalcForm = dbo.RK_GET_NASTR_CALC_REPORT (@varKSiLSF, 0)

if @iLinkCalcForm is null 
BEGIN
	SET @intIS_NOT_CALC = 1
	RETURN 0
END

--- Удаление старых записей ---
if @varKSiLT is NULL or isnull(@varKSiOrderCol,0) = 0
BEGIN
	insert @t_Col (Link_Col, orderCol)
	select Link_Col, Export_Order
	from report_coloumns RC
	join report_tables RT on RC.Link_Table = RT.Link_Table
	where RT.Link_Form = @LF

	DELETE FROM dbo.REPORT_DINAMICS WHERE LINK_SF = @varKSiLSF
END
ELSE
BEGIN
	SELECT @orderCol = Export_Order, @LC = Link_Col
	FROM dbo.REPORT_COLOUMNS
	WHERE link_table = @varKSiLT and orders = @varKSiOrderCol
	INSERT @t_Col (Link_Col, orderCol)
	VALUES (@LC, @orderCol)
end

--select * from @t_Col where link_col = 57755

select @nabor_filter = dbo.rn_get_atr_value(@varKSiLSF,'REPORTS_FILTER_KBK')

select @nabor_filter = REPLACE (@nabor_filter, 'Не отобрано', '')

IF EXISTS(Select LINK FROM rn_get_filter(@varKSiLSF,'REPORTS_FILTER_KBK'))
	set @lbKBK_FILTER = 1
else
	set @lbKBK_FILTER = 0

-- Olga 2011.07.19
insert @filter_kbk (kbk)   
Select RTRIM(code) FROM rn_get_filter(@varKSiLSF,'REPORTS_FILTER_KBK')

SET @ADM_CODE = dbo.rn_get_atr_value(@varKSiLSF,'REPORTS_ATR_ADM')
IF isnull(@ADM_CODE, '') <> '' and isnull(@ADM_CODE, '') <> '000' 
BEGIN 
   insert @filter_kbk (kbk)   
   Select @ADM_CODE
   set @nabor_filter = 'REPORTS_ATR_ADM'
END 


insert @temp_nastr1
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign],
	DT_Z = case when charindex('.',CR.DT_Mask,charindex('.',DT_Mask) + 1) - charindex('.',DT_Mask) = 3 or len(DT_Mask) - charindex('.',DT_Mask) = 2 then 1 else 0 end, 
	KT_Z = case when charindex('.',CR.KT_Mask,charindex('.',KT_Mask) + 1) - charindex('.',KT_Mask) = 3 or len(KT_Mask) - charindex('.',KT_Mask) = 2 then 1 else 0 end,
	CR.DT_Mask , CR.KT_Mask, dt_ekr, kt_ekr,
	[type], type_kbk, mask_kbk, dt_kt
from dbo.REPORT_CALC C 
INNER JOIN @t_Col RC on RC.Link_Col = C.Link_Col
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
WHERE C.LINK_UP = @iLinkCalcForm

--   
---------------------------------------------------------------------
----- ПОЛУЧАЕМ ВЫБОРКУ ИЗ ТАБЛИЦЫ НАСТРОЕК ----
insert @temp_nastr 
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign],
	DT.link , KT.link, dt_ekr, kt_ekr,
	[type], type_kbk, mask_kbk, dt_kt
from @temp_nastr1 C
left join dbo.s_accounts DT on DT.Code like case when C.DT_Mask = '%' or rtrim (C.DT_Mask) = '' then 'x' else rtrim (C.DT_Mask) + '%' end
left join dbo.s_accounts KT on	KT.Code like case when C.KT_Mask = '%' or rtrim (C.KT_Mask) = ''then 'x' else rtrim (C.KT_Mask) + '%' end
WHERE C.[sign] in (1,2) and C.[type] = 1 
	AND (rtrim (C.DT_Mask) = '' OR C.DT_Mask = '%' OR rtrim (C.DT_Mask) <> '' AND DT.LINK IS NOT NULL and DT.zabalans = C.DT_Z)
	AND (rtrim (C.KT_Mask) = '' OR C.KT_Mask = '%' OR rtrim (C.KT_Mask) <> '' AND KT.LINK IS NOT NULL and KT.zabalans = C.KT_Z)
--select * from @temp_nastr where link_col = 57755

/*
SELECT S1.CODE AS DT, S2.CODE AS KT
FROM @temp_nastr T
LEFT JOIN S_ACCOUNTS S1 ON S1.LINK = LINK_DT
LEFT JOIN S_ACCOUNTS S2 ON S2.LINK = LINK_KT
*/
/*	AND DT.cSOURCE = KT.cSOURCE
	AND DT.ZABALANS = KT.ZABALANS
*/
-- проводки, которые мы исключаем --
insert @temp_nastr_xor 
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign], DT.link , KT.link, dt_ekr, kt_ekr, [type], type_kbk, dt_kt
from @temp_nastr1 C
left join dbo.s_accounts DT on DT.Code like case when C.DT_Mask = '%' or rtrim (C.DT_Mask) = '' then 'x' else rtrim (C.DT_Mask) + '%' end
left join dbo.s_accounts KT on	KT.Code like case when C.KT_Mask = '%' or rtrim (C.KT_Mask) = ''then 'x' else rtrim (C.KT_Mask) + '%' end
where C.[sign] = 3 and C.[type] = 1
	AND (rtrim (C.DT_Mask) = '' OR C.DT_Mask = '%' OR rtrim (C.DT_Mask) <> '' AND DT.LINK IS NOT NULL and DT.zabalans = C.DT_Z)
	AND (rtrim (C.KT_Mask) = '' OR C.KT_Mask = '%' OR rtrim (C.KT_Mask) <> '' AND KT.LINK IS NOT NULL and KT.zabalans = C.KT_Z)
 

/*	AND DT.cSOURCE = KT.cSOURCE
	AND DT.ZABALANS = KT.ZABALANS
*/

--select t.* from @temp_nastr t 

/*
select t.* from @temp_nastr t
select t1.* from @temp_nastr_xor t1 -- on t1.link_col = t.link_col
*/
--- Удаление лишних корреспонденций ---
/*
DELETE T1
FROM @temp_nastr T1
INNER JOIN @temp_nastr_xor T2 ON (T2.LINK = T1.LINK
	AND T2.LINK_COL = T1.LINK_COL
	AND T2.CODE_ROW = T1.CODE_ROW
	AND T2.LINK_DT = T1.LINK_DT
	AND T2.LINK_KT = T1.LINK_KT)
*/
-- select * from @temp_nastr 

--- Выборка счетов для расчета остатков ---
insert @temp_nastr_rest 
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign],
	case
		when DT.link is NULL then KT.link
		else DT.link
	end,
	case
		when DT.link is NULL then kt_ekr
		else dt_ekr
	end, [type],
	type_kbk,
	mask_kbk,
	dt_kt
from @temp_nastr1 C
left join dbo.s_accounts DT on DT.Code like case when C.DT_Mask = '%' or rtrim (C.DT_Mask) = '' then 'x' else rtrim (C.DT_Mask) + '%' end
left join dbo.s_accounts KT on	KT.Code like case when C.KT_Mask = '%' or rtrim (C.KT_Mask) = ''then 'x' else rtrim (C.KT_Mask) + '%' end
WHERE C.[type] in (2,3) and C.[sign] in (1,2) 
	AND (rtrim (C.DT_Mask) = '' OR C.DT_Mask = '%' OR rtrim (C.DT_Mask) <> '' AND DT.LINK IS NOT NULL and DT.zabalans = C.DT_Z)
	AND (rtrim (C.KT_Mask) = '' OR C.KT_Mask = '%' OR rtrim (C.KT_Mask) <> '' AND KT.LINK IS NOT NULL and KT.zabalans = C.KT_Z)

/*
select S1.CODE, * from @temp_nastr_rest T, S_ACCOUNTS S1 
WHERE S1.LINK = T.LINK_account
*/

--- Счета, которые исключаем для расчета остатков ---
insert @temp_nastr_rest_xor
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign],
	case
		when DT.link is NULL then KT.link
		else DT.link
	end,
	case
		when DT.link is NULL then kt_ekr
		else dt_ekr
	end,
	[type],
	type_kbk,
	dt_kt
from @temp_nastr1 C
left join dbo.s_accounts DT on DT.Code like case when C.DT_Mask = '%' or rtrim (C.DT_Mask) = '' then 'x' else rtrim (C.DT_Mask) + '%' end
left join dbo.s_accounts KT on	KT.Code like case when C.KT_Mask = '%' or rtrim (C.KT_Mask) = ''then 'x' else rtrim (C.KT_Mask) + '%' end
WHERE C.[type] in (2,3) and C.[sign] = 3 
	AND (rtrim (C.DT_Mask) = '' OR C.DT_Mask = '%' OR rtrim (C.DT_Mask) <> '' AND DT.LINK IS NOT NULL and DT.zabalans = C.DT_Z)
	AND (rtrim (C.KT_Mask) = '' OR C.KT_Mask = '%' OR rtrim (C.KT_Mask) <> '' AND KT.LINK IS NOT NULL and KT.zabalans = C.KT_Z)
--- Удаление лишних корреспонденций ---

----------------------------------------------------------------------
-- РАССЧИТЫВАЕМ
-- CREATE TABLE #tTemp  (KBK varchar(50), Link_Col int, SUMMA FLOAT, Calc_Order int)
---------------- проводки ----------------------------
insert #tTemp (KBK, Link_Col, SUMMA, Calc_Order)
SELECT 
CASE WHEN TMP.Code_Row <> '' THEN TMP.Code_Row
		ELSE
			 dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', TMP.Mask_KBK) = 0 THEN ''
						ELSE LEFT (TMP.Mask_KBK, CHARINDEX ('#', TMP.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(KBK.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6)
--			+ LEFT(ISNULL(REPLACE(CASE TMP.DT_KT when 0 THEN SAD.CODE ELSE SAK.CODE END,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(case dt_kt when 0 then DTS.CODE else KTS.CODE END, '000'), 3) 
			+ LEFT(ISNULL(case dt_kt when 0 then DTE.CODE else KTE.CODE END, '000'), 3), TMP.Mask_KBK)
		END,
	TMP.Link_Col,
	SUM(CASE [SIGN] WHEN 1 THEN G2.SUMMA WHEN 2 THEN -G2.SUMMA  ELSE 0 END), 
--CASE [SIGN] WHEN 1 THEN G2.SUMMA WHEN 2 THEN -G2.SUMMA  ELSE 0 END,
	TMP.Calc_Order

--g.*

FROM dbo.G_PROV G
INNER JOIN dbo.G_PROV1 G1 ON (G1.LINK_UP = G.LINK)
INNER JOIN dbo.G_PROV2 G2 ON (G2.LINK_UP = G1.LINK)


LEFT JOIN dbo.G_PROV_AP DT ON (DT.LINK_UP = G2.LINK
	AND DT.DB_KR = 0)
LEFT JOIN dbo.G_PROV_AP KT ON (KT.LINK_UP = G2.LINK
	AND KT.DB_KR = 1)

LEFT JOIN dbo.KOSGU DTS ON (DTS.Link = DT.SGU)
LEFT JOIN dbo.KOSGU DTE ON (DTE.Link = DT.EKR)
LEFT JOIN dbo.KOSGU KTS ON (KTS.Link = KT.SGU)
LEFT JOIN dbo.KOSGU KTE ON (KTE.Link = KT.EKR)

INNER JOIN @TEMP_NASTR TMP ON (TMP.LINK_DT = DT.ACCOUNT OR TMP.LINK_DT IS NULL)
		AND (TMP.LINK_KT = KT.ACCOUNT OR TMP.LINK_KT IS NULL)
	AND (@iForm737 = 0 and dbo.RO_LIKE_LIST(DTS.Code, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '' or @iForm737 = 1)
	AND (@iForm737 = 0 and dbo.RO_LIKE_LIST(KTS.Code, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '' or @iForm737 = 1)
	AND (@iForm737 = 1 and dbo.RO_LIKE_LIST(DTE.Code, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '' or @iForm737 = 0)
	AND (@iForm737 = 1 and dbo.RO_LIKE_LIST(KTE.Code, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '' or @iForm737 = 0)

LEFT JOIN dbo.S_ACCOUNTS SA ON (TMP.DT_KT = 0 AND SA.LINK = DT.ACCOUNT
	OR TMP.DT_KT = 1 AND SA.LINK = KT.ACCOUNT)

LEFT JOIN dbo.KL_KBK KBK ON (TMP.dt_kt = 0 AND KBK.LINK = DT.KBK
		OR TMP.DT_KT = 1 AND KBK.LINK = KT.KBK)
LEFT JOIN @filter_kbk F on KBK.Code LIKE F.kbk + '%' -- добавила Olga 2011.07.19 
WHERE G.DATE_PROV BETWEEN @ldBegin AND @dCALC_DATE
--and tmp.link_col = 57755
	--and tmp.Code_Row = '162'
	AND G.DEP = @iDEP_LINK
	AND (F.kbk IS NOT NULL
		OR isnull(@nabor_filter, '') = '')
	AND (TMP.TYPE_KBK = 0 
		OR (TMP.TYPE_KBK & KBK.[TYPE]) / KBK.[TYPE] = 1)
	AND not exists(select top 1 *
			from @temp_nastr_xor xor
			where xor.link = tmp.link
				and xor.link_dt = dt.account and xor.link_kt = kt.account
				AND (@iForm737 = 0 and dbo.RO_LIKE_LIST(DTS.Code, xor.DT_EKR) > 0 OR xor.DT_EKR = '' or @iForm737 = 1)
				AND (@iForm737 = 0 and dbo.RO_LIKE_LIST(KTS.Code, xor.KT_EKR) > 0 OR xor.KT_EKR = '' or @iForm737 = 1)
				AND (@iForm737 = 1 and dbo.RO_LIKE_LIST(DTE.Code, xor.DT_EKR) > 0 OR xor.DT_EKR = '' or @iForm737 = 0)
				AND (@iForm737 = 1 and dbo.RO_LIKE_LIST(KTE.Code, xor.KT_EKR) > 0 OR xor.KT_EKR = '' or @iForm737 = 0))

GROUP BY CASE WHEN TMP.Code_Row <> '' THEN TMP.Code_Row
		ELSE
			 dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', TMP.Mask_KBK) = 0 THEN ''
						ELSE LEFT (TMP.Mask_KBK, CHARINDEX ('#', TMP.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(KBK.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
--			+ LEFT(ISNULL(REPLACE(CASE TMP.DT_KT when 0 THEN SAD.CODE ELSE SAK.CODE END,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(case dt_kt when 0 then DTS.CODE else KTS.CODE END, '000'), 3) 
			+ LEFT(ISNULL(case dt_kt when 0 then DTE.CODE else KTE.CODE END, '000'), 3), TMP.Mask_KBK)
		END,
	TMP.Link_Col,
	TMP.Calc_Order

----------------- остатки ------------------------------
while exists(select top 1 * from @temp_nastr_rest)
begin
	select top 1 @LC = Link_Col from @temp_nastr_rest

	set @bid = 'calc_col_' + LTRIM(RTRIM(STR(@LC)))

	insert dbo.buffer(ID, Link)
	select @bid, link_account
	from @temp_nastr_rest
	where link_col = @LC

	-- остаток на начало периода
	INSERT #tTemp (KBK, Link_Col, SUMMA, Calc_Order)
	SELECT 
		CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'000'), 3) 
			+ LEFT(ISNULL(E.CODE,'000'), 3), R.Mask_KBK)
		END,
		@LC,
		SUM(CASE
			WHEN (SA.S_PASSIVE = 1 and [sign] = 1) OR (SA.S_ACTIVE = 1 and [sign] = 2)
				THEN  k_summa - d_summa
			ELSE d_summa - k_summa END),
		R.Calc_Order
	FROM dbo.ARestTableByDateAccounts(@ldBegin, @bid) A
	INNER JOIN @temp_nastr_rest R on R.link_account = A.account and R.Link_Col = @LC and R.[Type] = 2
	LEFT JOIN dbo.KL_KBK K on K.Link = A.KBK
	--		and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end) > 0)
	LEFT JOIN @filter_kbk F on K.Code LIKE F.kbk + '%' -- добавила Olga 2011.07.19 
	left join dbo.KOSGU S on (S.Link = A.SGU) --and (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
	left join dbo.KOSGU E on E.Link = A.EKR
	left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	where dep_link = @iDEP_LINK
		AND (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
		and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and (dbo.RO_LIKE_LIST(S.Code, R1.ekr) > 0  or R1.ekr = '') and r1.link = r.link)
		AND (R.TYPE_KBK = 0 
			OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		AND (F.kbk IS NOT NULL
			OR isnull(@nabor_filter, '') = '')
	GROUP BY 
		CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'000'), 3) 
			+ LEFT(ISNULL(E.CODE,'000'), 3), R.Mask_KBK)
		END,
		R.Calc_Order

	-- остаток на конец периода
	insert #tTemp(KBK, Link_Col, SUMMA, Calc_Order)
	select 
		CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'000'), 3) 
			+ LEFT(ISNULL(E.CODE,'000'), 3), R.Mask_KBK)
		END,
		@LC,
	        sum(case
			when (SA.S_PASSIVE = 1 and [sign] = 1) OR (SA.S_ACTIVE = 1 and [sign] = 2)
				then  k_summa - d_summa
			else d_summa - k_summa end),
		R.Calc_Order
	from dbo.ARestTableByDateAccounts(@ldEnd, @bid) A
	INNER JOIN @temp_nastr_rest R on R.link_account = account and R.Link_Col = @LC and R.[Type] = 3
	LEFT JOIN dbo.KL_KBK K on K.Link = A.KBK
	--		and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end) > 0)
	LEFT JOIN @filter_kbk F on K.Code LIKE F.kbk + '%' -- добавила Olga 2011.07.19  
	left join dbo.KOSGU S on (S.Link = A.SGU) --and (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
	left join dbo.KOSGU E on E.Link = A.EKR
	left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	where dep_link = @iDEP_LINK
		AND (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
			and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and (dbo.RO_LIKE_LIST(S.Code, R1.ekr) > 0  or R1.ekr = '') and r1.link = r.link)
		AND (R.TYPE_KBK = 0 
			OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		AND (F.kbk IS NOT NULL
			OR isnull(@nabor_filter, '') = '')

/*		join @temp_nastr_rest R on R.link_account = account and R.Link_Col = @LC and R.[Type] = 3
		left join dbo.KL_KBK K on K.Link = A.KBK and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end)>0)
		LEFT JOIN @filter_kbk F on F.kbk = K.Code 
		left join dbo.KOSGU S on (S.Link = A.EKR)  -- and (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
		left join dbo.KOSGU E on E.Link = A.EKR
		left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	where dep_link = @iDEP_LINK
		and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and (dbo.RO_LIKE_LIST(S.Code, R1.ekr) > 0 or R1.ekr =''))
		AND (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
		AND (R.TYPE_KBK = 0 
			OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		AND (F.kbk IS NOT NULL
			OR isnull(@nabor_filter, '') = '')
*/	group by 
		CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'000'), 3)
			+ LEFT(ISNULL(E.CODE,'000'), 3), R.Mask_KBK)
		END,
		/*R.Code_Row, */R.Calc_Order

-- select * from #tTemp
	
	delete @temp_nastr_rest where Link_Col = @LC

	exec dbo.BufferClear @bid	
end

 --select * from #tTemp
---------------------------------------------------------------------
-- СОХРАНЯЕМ ДАННЫЕ В ОТЧЕТ
-- динамическая таблица
delete T -- удаляем ячейки с меньшим приоритетом
from #tTemp T
where exists(select top 1 * from #tTemp T1 where T.Link_Col = T1.Link_Col and T.KBK = T1.KBK and T.Calc_Order < T1.Calc_Order)

delete #tTemp where KBK <> @varKScCodeRow and isnull(@varKScCodeRow, '') <> ''
	OR SUMMA = 0

UPDATE #tTemp SET KBK = REPLACE (KBK, '#', '')

if isnull(@varKScCodeRow, '') <> ''
	select @varKSfValue = sum(SUMMA)
	from #tTemp

update dbo.report_dinamics
set float_val = SUMMA
from (select KBK, Link_Col, sum(SUMMA) as SUMMA from #tTemp group by KBK, Link_Col) T join report_coloumns RC on T.Link_Col = RC.Link_Col
	join report_tables RT on RC.Link_Table = RT.Link_Table
where Link_SF = @varKSiLSF and T.Link_Col = report_dinamics.Link_Col and Code_Row = KBK and RT.Val_Type = 1

insert dbo.report_dinamics(Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
select @varKSiLSF, T.Link_Col, KBK, sum(SUMMA), ''
from #tTemp T join report_coloumns RC on T.Link_Col = RC.Link_Col
	join report_tables RT on RC.Link_Table = RT.Link_Table and RT.Val_Type = 1
where not exists(select top 1 * from dbo.report_dinamics RD where RD.Link_SF = @varKSiLSF and RD.Link_Col = T.Link_Col and RD.Code_Row = T.KBK)
group by T.Link_Col, KBK

-- статическая таблица
update S
set SUMMA = T.SUMMA
-- select *
from dbo.report_summa S
join dbo.i_report_rows RR on S.Link_Row = RR.Link_Row and Link_Saved_Form = @varKSiLSF
join (select KBK, Link_Col, sum(SUMMA) as SUMMA from #tTemp group by KBK, Link_Col) T on T.Link_Col = S.Link_Col and T.KBK = RR.Code

insert dbo.report_summa(Link_Saved_Form, Link_Col, Link_Row, Summa)
select @varKSiLSF, T.Link_Col, RR.Link_Row, sum(SUMMA)
from #tTemp T
join dbo.report_coloumns RC on T.Link_Col = RC.Link_Col
join dbo.i_report_rows RR on RC.Link_Table = RR.Link_Table and T.KBK = RR.Code
where not exists(select top 1 * from dbo.report_summa S where S.Link_Saved_Form = @varKSiLSF and S.Link_Col = T.Link_Col and S.Link_Row = RR.Link_Row)
group by T.Link_Col, RR.Link_Row

-- SELECT * FROM #tTemp where link_col = 57755 order by kbk, link_col



drop table #tTemp

return 0

GO


GRANT EXECUTE ON dbo.[RO_CALC_NASTR] TO PUBLIC

GO



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

GO


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

CREATE           
PROCEDURE dbo.BB_EXPORT_ZKR
	@cBuffId	varchar(30) = '',
	@cFormat	varchar(30) = ''

AS
DECLARE @iDepLink	int, 
	@cCodeOpt 	int,
	@iNoteDCL	tinyint,
	@cPrefDCL	varchar(10), 
	@cKorrName	varchar(254), 
	@iLongFio tinyint, 
	@iPostRuk tinyint, 
	@iPostGl tinyint


set @iPostRuk = dbo.sa_get_option_by_code('BB_ZAYAVKA_KR_OPTIONS_POST_RUK')
set @iPostGl = dbo.sa_get_option_by_code('BB_ZAYAVKA_KR_OPTIONS_POST_GL')
set @iLongFio = dbo.sa_get_option_by_code('BB_ZAYAVKA_KR_OPTIONS_FIO')

set @iDepLink = isnull(dbo.BK_GetDepZB(),dbo.GetOwnDepLink())
select @cCodeOpt = KODBP,
	@iNoteDCL = isnull(T_DCL,0),
	@cPrefDCL = isnull(rtrim(PREF_DCL) + ' ',''),
	@cKorrName = isnull(rtrim(KOR_NAME),'<Наим_орг_полн>')
from dbo.BB_ZAYAVKA_KR_OPTIONS

-- Таблица 2 (FROM)
SELECT 	BUDG_LEVEL  = case D.BUH_TYPE WHEN 1 then cast(replace(B.CODE_EL,'0','') as char(1)) else '6' end,
		KOD_UBP = case cast(replace(B.CODE_EL,'0','') as char(1)) when 1 then D.CODE_UBP else BUDG end,
		NAME_UBP	= left(rtrim(D.prefix) + rtrim(D.FULL_NAME) + case when charindex('(',D.prefix,0) > 0 then ')' else '' end,254),
		0 as link,
		0 as link_up
from dbo.DEPARTMENTS D
left join dbo.KL_ADMIN_BS V WITH (NOLOCK) on V.LINK = D.VED_LINK
left join dbo.KL_BUDG_TYPE B WITH (NOLOCK) on V.Link_Budg = B.LINK
where D.LINK = @iDepLink


-- Таблица 3 (TO)
SELECT 	KOD_TOFK  = TOFK.CODE,
		NAME_TOFK = TOFK.FULL_NAME,
		0 as link,
		0 as link_up
from dbo.DEPARTMENTS D
inner join dbo.TREASURY TOFK on D.TOFK_LINK = TOFK.LINK
where D.LINK = @iDepLink



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


	SELECT  LINK 		 = ZKR.LINK,
			LINK_UP		 = ZKR.LINK,
			GUID_FK		 = '',
			[TYPE]		 = cast(ZKR.SHORT + 1 as char(1)),
			NOM_ZR		 = ZKR.NUMBER,
			DATE_ZR		 = ZKR.DATE,
			KOD_UBP_PAY	 = case @cCodeOpt when 1 then ZKR.DEP_UBP else '' end,
			NAME_UBP_PAY = ZKR.DEP_FNAME, 
			LS_UBP_PAY	 = ZKR.ACC_CODE,
			INN_UBP		 = '',
			KPP_UBP		 = '',
			GLAVA_GRS	 = case ZKR.dep_type WHEN 1 then ZKR.GRBS_CODE else '' end,
			NAME_UBP_GRS = case ZKR.SHORT when 0 then case ZKR.dep_type WHEN 1 then ZKR.GRBS_NAME else ZKR.UCHR_NAME end  else '' end,
			NAME_BUD	 = case ZKR.dep_type WHEN 1 then ZKR.BUDG_NAME else '' end,
			NAME_FO		 = case ZKR.SHORT when 0 then case ZKR.dep_type WHEN 1 then ZKR.FO_NAME else '' end else '' end,
			OKPO_FO		 = case ZKR.SHORT when 0 then case ZKR.dep_type WHEN 1 then ZKR.FO_OKPO else '' end else '' end,
			KOD_TOFK	 = ZKR.TOFK_CODE,
			NAME_TOFK	 = ZKR.TOFK_NAME,
			DATE_ISP	 = ZKR.SROK,
			GUID_SV		 = '',
			NOM_BO		 = ZKR.BO_NUM,
			KOD_ISP		 = '',
			PR_ISP		 = '',
			FAIP_CODE	 = '',
			SUM_V		 = ZKR.SUMMA,
			KOD_V		 = '643',
			SUM_DOC		 = 0,
			TYPE_AP		 = cast(ZKR.AVANSE as char(1)),
			SUM_V_NDS	 = case ZKR.SHORT when 0 then ZKR.SUMMA_NDS else 0 end,
			ORDER_PL	 = ZKR.[ORDER],
			VID_PL		 = CASE	ZKR.KIND WHEN 'почтой'     THEN '1'
										 WHEN 'телеграфом' THEN '2'
										 WHEN 'электронно' THEN '3'
										 WHEN 'срочно' 	   THEN '4'
										 ELSE '0' END,
			PURPOSE		 = replace(replace(ZKR.TARGETTEXT,char(10),''),char(13),''),
			VID_OSN		 = ZKR.OSN_VID,
			NOM_OSN		 = ZKR.OSN_NUM,
			DATE_OSN	 = ZKR.OSN_DATE,
			OSN			 = ZKR.OSN_COM,
			NAME_RCP	 = dbo.BB_DEP_NAME_FOR_SHABLON(@cKorrName, ZKR.KOR_LINK,  ZKR.KOR_ACC_LINK), 
			INN_RCP		 = ZKR.KOR_INN,
			KPP_RCP		 = case when len(rtrim(ZKR.KOR_INN)) > 10 then '0' else ZKR.KOR_KPP end,
			LS_UBP_RCP	 = case ZKR.SHORT when 0 then ZKR.KOR_LACC else '' end,
			BS_RCP		 = replace(ZKR.KOR_RACC,'00000000000000000000',''),
			NAME_BIC_RCP = ZKR.KOR_BANK,
			BIC_RCP		 = ZKR.KOR_BIK,
			KS_BIC_RCP	 = ZKR.KOR_KS,
			PAYSTATUS	 = ZKR.STATUS,
			KDOH		 = replace(ZKR.DOH_CODE_L,'.',''),
			OKATO		 = ZKR.OKATO,
			OSN_PL		 = ZKR.P_REASON,
			NAL_PER		 = ZKR.[PERIOD],
			NOM_DOK		 = ZKR.TREBNUM,
			DATE_DOK	 = case ZKR.ZERODATE when 1 then /*'00.00.0000'*/ '0' else CONVERT(CHAR(10),ZKR.TREBDATE,104) end,
			TYPE_PL		 = ZKR.P_TYPE,
			DOL_RUK_UBP	 = case when ZKR.SHORT = 0 and @iPostRuk = 1 then B.POST_NAME else '' end,
			NAME_RUK_UBP = case @iLongFio when 1 then rtrim(B.FM) + ' ' + rtrim(B.IM) + ' ' + rtrim(B.OT) else B.SHORT_NAME end,
			DOL_BUH_UBP	 = case when ZKR.SHORT = 0 and @iPostGl = 1 then GB.POST_NAME else '' end,
			NAME_BUH_UBP = case @iLongFio when 1 then rtrim(GB.FM) + ' ' + rtrim(GB.IM) + ' ' + rtrim(GB.OT) else GB.SHORT_NAME end,
			DATE_POD_UBP = ZKR.DATE,
			NOM_ZR_FK	 = '',
			DATE_FK		 = cast(null as datetime),
			DOL_ISP_FK	 = '',
			NAME_ISP_FK	 = '',
			TEL_ISP_FK	 = ''
	FROM dbo.BB_ZAYAVKA_KR ZKR
	left join dbo.GetOtvFaceData(null, 'Руководитель') B on ZKR.DEP_LINK = B.LINK_DEP
	left join dbo.GetOtvFaceData(null, 'Главный бухгалтер') GB on ZKR.DEP_LINK = GB.LINK_DEP
	where ZKR.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId))


if @cFormat > 'TXZR100700' --or @cFormat = ''
/*	SELECT  LINK 		 = case when ZKR.OSNOV_LINK is null then ZKR.LINK else ZKR.DOG_LINK end,
			LINK_UP		 = ZKR.LINK,
			VID_OSN		 = ZKR.DOG_VID,
			NOM_OSN		 = ZKR.DOG_NUM,
			DATE_OSN	 = ZKR.DOG_DATE,
			OSN			 = case ZKR.SHORT when 0 then ZKR.DOG_COM else '' end
	FROM dbo.BB_ZAYAVKA_KR ZKR
	where ZKR.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId)) and ZKR.DOG_NUM is not null
	union all
	SELECT  LINK 		 = ZKR.LINK,
			LINK_UP		 = ZKR.LINK,
			VID_OSN		 = ZKR.OSN_VID,
			NOM_OSN		 = ZKR.OSN_NUM,
			DATE_OSN	 = ZKR.OSN_DATE,
			OSN			 = case ZKR.SHORT when 0 then ZKR.OSN_COM else '' end
	FROM dbo.BB_ZAYAVKA_KR ZKR
	where ZKR.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId)) and ZKR.OSN_NUM is not null 
				
*/
	SELECT  ZO.LINK, 
			ZO.LINK_UP,
			VID_OSN		 = ZO.[TYPE],
			NOM_OSN		 = ZO.NUMBER,
			DATE_OSN	 = ZO.[DATE],
			OSN			 = case ZKR.SHORT when 0 then ZO.COMMENT else '' end,
			OSN_PLAT	=	CASE ZKR.SHORT WHEN 0 THEN '' ELSE replace(str(ZO.OSN),'0','2') END
	FROM dbo.BB_ZAYAVKA_KR_OSNOV ZO
	inner join dbo.BB_ZAYAVKA_KR ZKR on ZKR.LINK = ZO.LINK_UP
	where ZKR.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by ZO.LINK


-- Таблица 4 (ZRST)
	select  ZT.LINK,
			LINK_UP = coalesce((select top 1 LINK from ZAYAVKA_KR_OSNOV where LINK_UP = ZT.LINK_UP order by LINK desc),ZT.LINK_UP),
			KOD_IST_KBK	  = cast(ZT.VID_SR as char(1)),
			TYPE_KBK_PAY  = case ZT.KBK_TYPE when 1 then '10'
											 when 2 then '20'
											 when 4 then '31'
											 when 8 then '32'
											 else '' end,
			KBK_PAY		  = left(replace(ZT.BK_CODE,'.',''),20),
			TYPE_KBK_RCP  = case ZKR.SHORT when 0 then case ZT.KBK_TYPE_d when 1 then '10'
																		  when 2 then '20'
																		  when 4 then '31'
																		  when 8 then '32'
																		  else '' end else '' end,
			KBK_RCP		  = case ZKR.SHORT when 0 then left(replace(ZT.BKD_CODE,'.',''),20) else '' end,
			ADD_KLASS_PAY = case when left(DA.CODE,2) = '21' or left(DA.CODE,2) = '31' then isnull(ZT.DCL_CODE, '-') else ZT.DCL_CODE end,
			ADD_KLASS_RCP = ZT.DCL_CODE_D,
			SUM_V_KBK	  = ZT.SUMMA,
			SUM_R_KBK	  = 0,
			PURPOSE_KBK	  = case ZKR.SHORT when 0 then ZT.TARGET else '' end,
			NOTE_KBK	  = case ZKR.SHORT when 0 then ZT.TITLE + case @iNoteDCL when 1 then @cPrefDCL + ZT.DCL_CODE else '' end else '' end 
	from dbo.BB_ZAYAVKA_KR_TABLE ZT
	inner join dbo.FINANSE_PAYS ZKR on ZKR.LINK = ZT.LINK_UP
	inner join dbo.G_PROV G on ZKR.LINK = G.LINK
	inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = G.ACC
	where ZT.LINK_UP in (select LINK from dbo.BufferGetTableByID(@cBuffId))




GO


GRANT EXECUTE ON dbo.[BB_EXPORT_ZKR] TO PUBLIC

GO


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


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




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

CREATE PROCEDURE dbo.BB_DEP_ACC_DETAILS_TABLE
	@varKSiDepAcc 	INT,
	@varKSdDateB 	DATETIME = null,
	@varKSdDateE 	DATETIME,
	@varKSiEmptyAcc tinyint = 0
	

AS

	IF @varKSdDateB IS NULL
		SET @varKSdDateB = dbo.DateBeginOfYear(@varKSdDateE)

	DECLARE @varKSiOwnDep	INT,
		@varKSiFYear	INT,
		@cSource	char(1)	


	set @varKSiOwnDep = isnull (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())
	set @varKSiFYear = YEAR(@varKSdDateE)

	-- Ассигнования
	DECLARE @varKSTableAssign TABLE(
		VKR INT,
		EKR INT,
		DOP_CL INT,
		SUMMA NUMERIC(28,2))

	--Лимиты
	DECLARE @varKSTableLimit TABLE(
		VKR INT,
		EKR INT,
		DOP_CL INT,
		SUMMA NUMERIC(28,2))

	-- Кассовый расход 
	DECLARE @varKSTableKassa TABLE(
		VKR INT,
		EKR INT,
		DOP_CL INT,
		SUMMA NUMERIC(28,2))

	-- Финансирование
	DECLARE @varKSTableFinans TABLE(
		VKR INT,
		EKR INT,
		DOP_CL INT,
		SUMMA NUMERIC(19,2))

	-- Бюджетные обязательства
	DECLARE @varKSTableBO TABLE(
		VKR INT,
		EKR INT,
		DOP_CL INT,
		SUMMA NUMERIC(28,2))

	-- Денжные обязательства
	DECLARE @varKSTableDO TABLE(
		VKR INT,
		EKR INT,
		DOP_CL INT,
		SUMMA NUMERIC(28,2))

	DECLARE @varKSTableKP TABLE(
		VKR INT,
		EKR INT,
		DOP_CL INT,
		SUMMA NUMERIC(28,2))

	if exists(select * from dbo.DEPARTMENT_ACCOUNT_SOURCE A inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc and S.CODE = '1')
		set @cSource = '1'
	else 
		set @cSource = '2'



	-- Ассигнования
	/*INSERT INTO @varKSTableAssign
	SELECT VKR, EKR, isnull(DOP_CL,0) , sum(SUMMA)
	FROM dbo.FB_REST_FINANS_PERIOD(	@varKSdDateB, @varKSdDateE, 'FINANS_ASSIGN', @cSource, 1, @varKSiOwnDep)
	WHERE DEP_ACC = @varKSiDepAcc or @varKSiEmptyAcc = 1 and DEP_ACC is null
	GROUP BY VKR, EKR, DOP_CL*/


	--Кассовый план
	INSERT INTO @varKSTableKP
	SELECT VKR, EKR, isnull(DOP_CL,0) , sum(SUMMA)
	FROM dbo.FB_REST_FINANS_PERIOD(	@varKSdDateB, @varKSdDateE, 'FB_PLAN', @cSource, 1, @varKSiOwnDep)
	WHERE DEP_ACC = @varKSiDepAcc or @varKSiEmptyAcc = 1 and DEP_ACC is null
	GROUP BY VKR, EKR, DOP_CL



	exec dbo.BufferClear 'ISP_BO'
	exec dbo.BufferClear 'ISP_DO'
	exec dbo.BufferClear 'ISP_KR'
	exec dbo.BufferClear 'ISP_KR_V'
	exec dbo.BufferClear 'LIMIT'
	exec dbo.BufferClear 'ASSIGN'
	exec dbo.BufferClear 'FIN'

	INSERT INTO BUFFER (link, id)
	select SA.link, 'ISP_BO' 
	from dbo.DEPARTMENT_ACCOUNT_SOURCE A
	inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
	inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and SA.cSinth = '502' and SA.cAnalit = '11'

	INSERT INTO BUFFER (link, id)
	select SA.link, 'ISP_DO' 
	from dbo.DEPARTMENT_ACCOUNT_SOURCE A
	inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
	inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and SA.cSinth = '502' and SA.cAnalit = '12'

	INSERT INTO BUFFER (link, id)
	select SA.link, 'ISP_KR' 
	from dbo.DEPARTMENT_ACCOUNT_SOURCE A
	inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
	inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and 
									(SA.cSinth = '304' and SA.cAnalit = '05' or 
									 SA.cSinth = '201' and (SA.cAnalit = '11' or SA.cAnalit = '21' or SA.cAnalit = '27'))

	INSERT INTO BUFFER (link, id)
	select SA.link, 'ISP_KR_V' 
	from dbo.DEPARTMENT_ACCOUNT_SOURCE A
	inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
	inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and SA.cSinth = '304' and SA.cAnalit = '05'

	INSERT INTO BUFFER (link, id)
	select SA.link, 'LIMIT' 
	from dbo.DEPARTMENT_ACCOUNT_SOURCE A
	inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
	inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and 
									(SA.cSinth = '501' and SA.cAnalit = '13' or 
									SA.cSinth = '506' and SA.cAnalit = '00'or 
									SA.cSinth = '506' and SA.cAnalit = '10')

	INSERT INTO BUFFER (link, id)
	select SA.link, 'ASSIGN' 
	from dbo.DEPARTMENT_ACCOUNT_SOURCE A
	inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
	inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and 
									(SA.cSinth = '503' and SA.cAnalit = '13' or 
									SA.cSinth = '504' and SA.cAnalit = '00'or 
									SA.cSinth = '504' and SA.cAnalit = '10')

	INSERT INTO BUFFER (link, id)
	select SA.link, 'FIN' 
	from dbo.DEPARTMENT_ACCOUNT_SOURCE A
	inner join dbo.BB_FIN_SOURCE S on S.LINK = A.[SOURCE] and A.ACC = @varKSiDepAcc 
	inner join dbo.S_ACCOUNTS SA on SA.cSource = S.CODE and SA.cSinth = '508' 


	
	--Ассиггнования
	INSERT INTO @varKSTableAssign
	SELECT kt_vkr, kt_ekr, isnull(kt_ap2,0), sum(SUMMA)
	FROM (select LINK, summa,KT_DEP_ACC, DEP_LINK, KT_VKR, KT_EKR, KT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, NULL, 'ASSIGN')) A	
	WHERE (KT_DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and KT_DEP_ACC = 0) and DEP_LINK = @varKSiOwnDep
	group by kt_vkr, kt_ekr, kt_ap2

	--Лимиты
	INSERT INTO @varKSTableLimit
	SELECT kt_vkr, kt_ekr, isnull(kt_ap2,0), sum(SUMMA)
	FROM (select LINK, summa,KT_DEP_ACC, DEP_LINK, KT_VKR, KT_EKR, KT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, NULL, 'LIMIT')) A	
	WHERE (KT_DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and KT_DEP_ACC = 0) and DEP_LINK = @varKSiOwnDep
	group by kt_vkr, kt_ekr, kt_ap2

	
	-- Бюджетные обязательства
	INSERT INTO @varKSTableBO
	SELECT kt_vkr, kt_ekr, isnull(kt_ap2,0), sum(SUMMA)
	FROM (select LINK, summa,KT_DEP_ACC, DEP_LINK, KT_VKR, KT_EKR, KT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, NULL, 'ISP_BO') ) A	
	WHERE (KT_DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and KT_DEP_ACC = 0) and DEP_LINK = @varKSiOwnDep
	group by kt_vkr, kt_ekr, kt_ap2
	
	-- Денежные обязательства
	INSERT INTO @varKSTableDO
	SELECT kt_vkr, kt_ekr, isnull(kt_ap2,0), sum(SUMMA)
	FROM (select LINK, summa,KT_DEP_ACC, DEP_LINK, KT_VKR, KT_EKR, KT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, NULL, 'ISP_DO')) A	
	WHERE (KT_DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and KT_DEP_ACC = 0) and DEP_LINK = @varKSiOwnDep
	group by kt_vkr, kt_ekr, kt_ap2

	-- Кассовый расход 
	INSERT INTO @varKSTableKassa
	SELECT kt_vkr, kt_ekr, isnull(kt_ap2,0), sum(SUMMA)
	FROM (select LINK, summa, KT_DEP_ACC, DEP_LINK, KT_VKR, KT_EKR, KT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, NULL, 'ISP_KR') union all
			select LINK, -summa, DT_DEP_ACC, DEP_LINK, DT_VKR, DT_EKR, DT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, 'ISP_KR_V', NULL)) A	
	WHERE (KT_DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and KT_DEP_ACC = 0) and DEP_LINK = @varKSiOwnDep
	group by kt_vkr, kt_ekr, kt_ap2

	-- Финансирование
	INSERT INTO @varKSTableFinans
	SELECT dt_vkr, dt_ekr, isnull(dt_ap2,0), sum(SUMMA)
	FROM (select LINK, summa,DT_DEP_ACC, DEP_LINK, DT_VKR, DT_EKR, DT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, 'FIN', NULL) union all
		  select LINK, summa, KT_DEP_ACC, DEP_LINK, KT_VKR, KT_EKR, KT_AP2 from dbo.AProvByBufferConditionsShortDate(@varKSdDateB, @varKSdDateE, NULL, 'FIN')) A	
	WHERE (DT_DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and DT_DEP_ACC = 0) and DEP_LINK = @varKSiOwnDep
	group by dt_vkr, dt_ekr, dt_ap2

	
	INSERT INTO @varKSTableFinans
	SELECT VKR, EKR, isnull(DOP_CL,0) , sum(SUMMA)
	FROM dbo.FB_REST_FINANS_PERIOD(	@varKSdDateB, @varKSdDateE, 'FB_RESULT_FINANS', @cSource, 1, @varKSiOwnDep) 
	WHERE DEP_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and DEP_ACC is null
	GROUP BY VKR, EKR, DOP_CL
	UNION
	SELECT F.VKR, F.EKR, 0, SUM(MONEY_CURRENT)
	FROM FIN_RR_TABLE F
	INNER JOIN FIN_RR FRR ON FRR.LINK_G_PROV = F.LINK_UP AND (DEST_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and DEST_ACC is null)  
	INNER JOIN G_PROV GP ON GP.LINK = FRR.LINK_G_PROV AND 
				GP.DATE_PROV <= @varKSdDateE AND
				YEAR(GP.DATE_PROV) = @varKSiFYear AND
				GP.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE='FIN_RR_IN')
				AND DEP = @varKSiOwnDep
				
	GROUP BY VKR, EKR
	UNION
	SELECT F.KBK, F.EKR, 0, SUM(SUMMA_Y1)
	FROM FINANSE_RR_TABLE F
	INNER JOIN FIN_RR FRR ON FRR.LINK_G_PROV = F.LINK_UP AND (DEST_ACC = @varKSiDepAcc  or @varKSiEmptyAcc = 1 and DEST_ACC is null)  
	INNER JOIN G_PROV GP ON GP.LINK = FRR.LINK_G_PROV AND 
				GP.DATE_PROV <= @varKSdDateE AND
				YEAR(GP.DATE_PROV) = @varKSiFYear AND
				exists (SELECT LINK FROM S_OBJECTS SO WHERE SO.code = 'FIN_RR_104N' and GP.OBJECT = SO.LINK)
				AND DEP = @varKSiOwnDep
				
	GROUP BY KBK, EKR
	
	exec dbo.BufferClear 'ISP_BO'
	exec dbo.BufferClear 'ISP_DO'
	exec dbo.BufferClear 'ISP_KR'
	exec dbo.BufferClear 'ISP_KR_V'
	exec dbo.BufferClear 'LIMIT'
	exec dbo.BufferClear 'ASSIGN'
	exec dbo.BufferClear 'FIN'

	--объединяем и добавляем расшифровку 
	SELECT CD.VKR, CD.EKR, CD.DOP_CL,
		[CHECKED] = 0,	
		[UPD] = 0,
		[DEL] = 0,
		[LOCKED] = convert(bit,0),
		[VKR_CODE] = VKR.CODE,
		[EKR_CODE] = EKR.CODE,
		[DOP_CL_CODE] = DC.CODE,
		[VKR_NAME] = VKR.NAME,
		[EKR_NAME] = EKR.NAME,
		[DOP_CL_NAME] = DC.NAME,
		[SUMMA_A] = ISNULL(A.SUMMA,0),
		[SALDO_A] = ISNULL(A.SUMMA,0) - case O.ASSIGN when 1 then ISNULL(A.SUMMA,0) 
													  when 2 then ISNULL(L.SUMMA,0)
													  when 3 then ISNULL(KP.SUMMA,0)
													  when 4 then ISNULL(F.SUMMA,0)
													  when 5 then ISNULL(B.SUMMA,0)
													  when 6 then ISNULL(D.SUMMA,0)
													  when 7 then ISNULL(K.SUMMA,0)
													  else 0 end,
		[SUMMA_L] = ISNULL(L.SUMMA,0),
		[SALDO_L] = ISNULL(L.SUMMA,0) - case O.LBO    when 1 then ISNULL(A.SUMMA,0) 
													  when 2 then ISNULL(L.SUMMA,0)
													  when 3 then ISNULL(KP.SUMMA,0)
													  when 4 then ISNULL(F.SUMMA,0)
													  when 5 then ISNULL(B.SUMMA,0)
													  when 6 then ISNULL(D.SUMMA,0)
													  when 7 then ISNULL(K.SUMMA,0)
													  else 0 end,
		[SUMMA_BO] = ISNULL(B.SUMMA,0),
		[SUMMA_DO] = ISNULL(D.SUMMA,0),
		[SUMMA_K] = ISNULL(K.SUMMA,0),
		[SUMMA_F] = ISNULL( F.SUMMA,0),
		[SALDO_F] = ISNULL(F.SUMMA,0) - case O.FIN	  when 1 then ISNULL(A.SUMMA,0) 
													  when 2 then ISNULL(L.SUMMA,0)
													  when 3 then ISNULL(KP.SUMMA,0)
													  when 4 then ISNULL(F.SUMMA,0)
													  when 5 then ISNULL(B.SUMMA,0)
													  when 6 then ISNULL(D.SUMMA,0)
													  when 7 then ISNULL(K.SUMMA,0)
													  else 0 end,
		[SUMMA_KP] = ISNULL( KP.SUMMA,0),
		[SALDO_KP] = ISNULL(KP.SUMMA,0) - case O.KP   when 1 then ISNULL(A.SUMMA,0) 
													  when 2 then ISNULL(L.SUMMA,0)
													  when 3 then ISNULL(KP.SUMMA,0)
													  when 4 then ISNULL(F.SUMMA,0)
													  when 5 then ISNULL(B.SUMMA,0)
													  when 6 then ISNULL(D.SUMMA,0)
													  when 7 then ISNULL(K.SUMMA,0)
													  else 0 end
		
	FROM (SELECT VKR, EKR, DOP_CL FROM @varKSTableAssign where SUMMA <> 0 UNION
		SELECT VKR, EKR, DOP_CL FROM @varKSTableLimit where SUMMA <> 0 UNION
		SELECT VKR, EKR, DOP_CL FROM @varKSTableBO where SUMMA <> 0 UNION
		SELECT VKR, EKR, DOP_CL FROM @varKSTableDO where SUMMA <> 0 UNION
		SELECT VKR, EKR, DOP_CL FROM @varKSTableKassa where SUMMA <> 0 UNION
		SELECT VKR, EKR, DOP_CL FROM @varKSTableFinans where SUMMA <> 0 UNION
		SELECT VKR, EKR, DOP_CL FROM @varKSTableKP where SUMMA <> 0) CD
	LEFT JOIN @varKSTableAssign A ON isnull(CD.VKR,0) = isnull(A.VKR,0) AND isnull(CD.EKR,0) = isnull(A.EKR,0) AND isnull(CD.DOP_CL,0) = isnull(A.DOP_CL,0)
	LEFT JOIN @varKSTableLimit L  ON isnull(CD.VKR,0) = isnull(L.VKR,0) AND isnull(CD.EKR,0) = isnull(L.EKR,0) AND isnull(CD.DOP_CL,0) = isnull(L.DOP_CL,0)
	LEFT JOIN @varKSTableBO B  ON isnull(CD.VKR,0) = isnull(B.VKR,0) AND isnull(CD.EKR,0) = isnull(B.EKR,0) AND isnull(CD.DOP_CL,0) = isnull(B.DOP_CL,0)
	LEFT JOIN @varKSTableDO D  ON isnull(CD.VKR,0) = isnull(D.VKR,0) AND isnull(CD.EKR,0) = isnull(D.EKR,0) AND isnull(CD.DOP_CL,0) = isnull(D.DOP_CL,0)
	LEFT JOIN @varKSTableKassa K  ON isnull(CD.VKR,0) = isnull(K.VKR,0) AND isnull(CD.EKR,0) = isnull(K.EKR,0) AND isnull(CD.DOP_CL,0) = isnull(K.DOP_CL,0)
	LEFT JOIN @varKSTableFinans F  ON isnull(CD.VKR,0) = isnull(F.VKR,0) AND isnull(CD.EKR,0) = isnull(F.EKR,0) AND isnull(CD.DOP_CL,0) = isnull(F.DOP_CL,0)
	LEFT JOIN @varKSTableKP KP  ON isnull(CD.VKR,0) = isnull(KP.VKR,0) AND isnull(CD.EKR,0) = isnull(KP.EKR,0) AND isnull(CD.DOP_CL,0) = isnull(KP.DOP_CL,0)
	LEFT JOIN KL_KBK VKR on CD.vkr = VKR.link
	LEFT JOIN KOSGU EKR on CD.ekr = EKR.link
	LEFT JOIN DOP_CLASSIF DC on CD.DOP_CL = DC.link
	left join DEP_ACC_DETAILS_OPTIONS O on 1 = 1
	ORDER BY VKR.CODE, EKR.CODE, DC.CODE 
	
SELECT * FROM @varKSTableFinans where SUMMA <> 0 and EKR = 44 



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant all on dbo.BB_DEP_ACC_DETAILS_TABLE to public
GO



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

GO
CREATE PROCEDURE dbo.SA_4FSS_EXPORT_TEST (@Res tinyint output, @link int, @m int=0) 
AS
BEGIN

	DECLARE @LINK_DEP INT
	SELECT @LINK_DEP = LINK_ORGANIZATION FROM dbo.REPORT_SAVED_FORMS WHERE LINK_SAVED_FORM = @link

	SELECT 		
		D.FSS_REG_NUM,	
		D.FSS_KOD_P,
		D.FSS_KOD_DOP,
		D.OKATO,
		D.OKTMO,
		D.INN,
		D.KPP,
		D.OKVED,
		D.OKPO,
		D.OGRN,
		D.OKOPF,
		D.OKFS,
		GB_PHONE = GLBUH.PHONE,
		GLBUH_FIO = GLBUH.FM,
		CHIEF_FIO = CHIEF.FM,
		AUTHOR= ISNULL(dbo.AdminGetUserFIO(default),'')
	INTO #DEP_INFO	
	FROM 
		dbo.DEPARTMENTS D
		LEFT JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Главный бухгалтер') GLBUH ON GLBUH.link_dep = d.link
		LEFT JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Руководитель') CHIEF ON CHIEF.link_dep = d.link
	WHERE 
		D.LINK = @LINK_DEP


	-- Проставлять ОКАТО или ОКТМО по настройке
	DECLARE @OKATO_OR_OKTMO int
	SET @OKATO_OR_OKTMO = dbo.SA_GET_OPTION_BY_CODE('NASTR_USE_OKATO_OKTMO') 

	SET @Res = 1		
	CREATE TABLE #ERR_MSG (MSG_BEFORE VARCHAR(254),Msg VARCHAR(254),msg_after VARCHAR(254))



	IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(INN,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ИНН',
			msg_after  = 'Необходимо указать ИНН в настройках организации на вкладке РЕКВИЗИТЫ.'
	END	

	IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(KPP,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'КПП',
			msg_after  = 'Необходимо указать КПП в настройках организации на вкладке РЕКВИЗИТЫ.'
	END			
	

	IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(OKPO,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКПО',
			msg_after  = 'Необходимо указать ОКПО в настройках организации на вкладке РЕКВИЗИТЫ.'
	END	

	IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(OKPO,'')))) > 10) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Неверно указаны следующие реквизиты:',
			Msg = 'ОКПО не должен быть больше 10 знаков',
			msg_after  = 'Необходимо исправить ОКПО в настройках организации на вкладке РЕКВИЗИТЫ.'
	END		
	
	IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(OGRN,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОГРН',
			msg_after  = 'Необходимо указать ОГРН в настройках организации на вкладке РЕКВИЗИТЫ.'
	END	
	
	IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(GLBUH_FIO,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Ф.И.О. главного бухгалтера',
			msg_after  = 'Необходимо указать "Ф.И.О. главного бухгалтера" в настройках организации на вкладке ОТВЕТСТВЕННЫЕ ЛИЦА.'
	END

	IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(CHIEF_FIO,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Ф.И.О. руководителя',
			msg_after  = 'Необходимо указать "Ф.И.О. руководителя" в настройках организации на вкладке ОТВЕТСТВЕННЫЕ ЛИЦА.'
	END	

	IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(GB_PHONE,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Телефон главного бухгалтера',
			msg_after  = 'Необходимо указать "Телефон главного бухгалтера" в настройках организации на вкладке ОТВЕТСТВЕННЫЕ ЛИЦА.'
	END
	

	IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(OKATO,'')))) = 0) AND @OKATO_OR_OKTMO = 1 BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКАТО',
			msg_after  = 'Необходимо указать ОКАТО в настройках организации на вкладке АДРЕС.'
	END



	IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(OKTMO,'')))) = 0) AND @OKATO_OR_OKTMO = 2 BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКТМО',
			msg_after  = 'Необходимо указать ОКТМО в настройках организации на вкладке АДРЕС.'
	END

	IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(OKVED,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКВЭД',
			msg_after  = 'Необходимо указать ОКВЭД в настройках организации на вкладке ПРОЧИЕ.'
	END	
	
	IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(OKOPF,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКОПФ',
			msg_after  = 'Необходимо указать ОКОПФ в настройках организации на вкладке ПРОЧИЕ.'
	END			

	IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(OKFS,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'ОКФС',
			msg_after  = 'Необходимо указать ОКФС в настройках организации на вкладке ПРОЧИЕ.'
	END

	IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(FSS_REG_NUM,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Регистрационный номер страхователя в ФСС',
			msg_after  = 'Необходимо указать "Регистрационный номер страхователя в ФСС" в настройках организации на вкладке ПРОЧИЕ.'
	END		

	IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(FSS_KOD_P,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Код подчиненности',
			msg_after  = 'Необходимо указать "Код подчиненности" в настройках организации на вкладке ПРОЧИЕ.'
	END	
	
	-- Проверку на доп код закомментарим , т.к. доп код при выгрузке не обязателен
	/*IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(FSS_KOD_DOP,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Дополнительный код',
			msg_after  = 'Необходимо указать "Дополнительный код" в настройках организации на вкладке ПРОЧИЕ.'
	END	*/		

	IF EXISTS (SELECT * FROM #DEP_INFO WHERE LEN(LTRIM(RTRIM(ISNULL(AUTHOR,'')))) = 0) BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Автор (сотрудник, соответсвующий текущему пользователю программы)',
			msg_after  = 'Необходимо указать соответствие текущему пользователю сотрудника в программе Администратор-КС' + CHAR(13) + CHAR(10) 
						+ ' в разделе "Безопасность" в режиме "Пользователяи и роли".'
	END	

	IF isnull((select top 1 TAX_RATE from I_REPORT_OPTIONS_outputs_4fss),0) <= 0 BEGIN
		SET @Res = 0
		INSERT INTO #ERR_MSG (MSG_BEFORE, Msg, msg_after)
		SELECT
			MSG_BEFORE = 'Не указаны следующие реквизиты:',
			Msg = 'Размер страхового тарифа',
			msg_after  = 'Необходимо указать "Размер страхового тарифа" в режиме "Настройки форм отчётности"' + CHAR(13) + CHAR(10) 
						+ ' меню (навигатор) [НАСТРОЙКИ]-->[НАСТРОЙКИ ФОРМ ОТЧЁТНОСТИ] вкладка "4-ФСС".' + CHAR(13) + CHAR(10)
						+ ' затем пересчитайте форму, либо укажите "Размер страхового тарифа" в таблице №9, графе №9.' 
	END				
	
	IF OBJECT_ID('TEMPDB..#RES') IS NOT NULL
	BEGIN
		--Запустили при проверки КС
        insert #Res (res,orders,cdoc)
        select MSG_BEFORE + ': ' + LTRIM(RTRIM(Msg)),1,msg_after from #ERR_MSG order by MSG_BEFORE
		
		SELECT 0
	END	
	ELSE	
		--Запустили при экспорте
		SELECT * FROM #ERR_MSG	
	
END





GO


GRANT EXECUTE ON dbo.[SA_4FSS_EXPORT_TEST] TO PUBLIC

GO



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

GO

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

	SELECT DISTINCT
		LINK_VEDOM = B.LINK, 
		LINK = R.FRMT_LINK, 
		R.CARD_LINK, 
		F.CODE, 
		F.NAME, 
		F.IsUserObject, 
		F.UserFilename, 
		F.PRINT_OBJECT_METHOD, 
		F.QUERY_ADD_MODULE, 
		F.QUERY_REPMAKER, 
		F.QUERY_REPORT, 
		F.QUERY_REPORT_PATH, 
		F.LastFileNumber, 
		F.IsDefaultFormat, 
		F.SumType,
		BANK_LINK = R.BBANK_LINK, 
		LINK_PAY = -1, 
		TYP_PAYMENT = -1,
		COMMENT = LEFT('ФОРМАТ: ' + LTRIM(RTRIM(COALESCE(F.NAME,'НЕ ЗАДАН')))
				+ ', ТИП КАРТЫ: ' + LTRIM(RTRIM(COALESCE(R.CARD_NAME,'НЕ ЗАДАН')))
				+ ', БАНК: ' + LTRIM(RTRIM(COALESCE(R.BACC_NAME,'НЕ ЗАДАН'))),254)
	FROM dbo.BUFFER B
	inner join dbo.BB_REESTR_DEN_SR R on R.LINK = B.LINK
	INNER JOIN dbo.S_BANK_FORMATS F ON F.LINK = R.FRMT_LINK
	inner join dbo.BB_REESTR_DEN_SR_TABLE T ON T.LINK_UP = R.LINK
	WHERE B.ID = @BUFFER_ID
		


GO


GRANT EXECUTE ON dbo.BB_REESTR_DEN_SR_BANK_FORMATS TO PUBLIC

GO

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

GO
CREATE PROCEDURE dbo.BK_EXPORT_F1152026_503 (@iLINK_FORM INT)
AS
BEGIN
--перенос формы из архивной базы
	exec dbo.RN_MOVE_FORM_FROM_ARH @iLINK_FORM

	DECLARE @FNAME VARCHAR (254),
		@FNAME_ID VARCHAR (254),

		@PART_NAME_NNN VARCHAR (100),

		@DEP_LINK	INT,
		@INN	VARCHAR (12),
		@KPP VARCHAR (9),
		@IMNS VARCHAR (4),
		@OKVED VARCHAR (8),
		@TLF_GL_BUH	VARCHAR (10),
		@DEP_NAME VARCHAR (254),

		@C_PLACE	VARCHAR (3),
		@C_TYPE		VARCHAR (1),

		@NAME_RUK	VARCHAR (60),
		@FAM_RUK	VARCHAR (60),
		@OT_RUK		VARCHAR (60),

		@dDATE_FORM	DATETIME,
		@PERIOD_TYPE	INT,
		@PERIOD_NUM	INT,
		@cPERIOD_NUM	VARCHAR (2),

		@iLINK_TABLE	INT,
		@PROC_NAME	VARCHAR (254),

		--- Раздел 1 ---
		@KBK		VARCHAR (20),
		@OKTMO		VARCHAR (15),
		@OKTMO_DEP	VARCHAR (15),
		@SUMMA		NUMERIC (15,0),

		--- Раздел 2 ---
		@ST_IMUSH	NUMERIC (15,0),
		@CODE_NL	VARCHAR (20),
		@ST_IMUSH_NO NUMERIC (15,0),
		@Dol_ST	VARCHAR (21),
		@CODE_LG_PNS VARCHAR (7),
		@NAL_STAV	NUMERIC (3,2),
		@NAL_BASE	NUMERIC (15,0),
		@SUM_NAL_PER	NUMERIC (15,0),
		@OST_SUM_ALL	NUMERIC (15,0),

		@SumAV	NUMERIC (15),
		@CODE_LG_UM	VARCHAR (7),
		@SUM_LG_UM NUMERIC (15),

		@SUM_NAL_PRED	NUMERIC (15),

		@strNUM_COR	VARCHAR (3),

		@strEXEC	VARCHAR (8000),

		@cREORG_CODE	VARCHAR (1),
		@cREORG_INN	VARCHAR (12),
		@cREORG_KPP	VARCHAR (12)

	--- ---
	SELECT @DEP_LINK = LINK_ORGANIZATION,
			@dDATE_FORM	= BEGIN_DATE,
			@PERIOD_TYPE = PERIOD_TYPE,
			@PERIOD_NUM	= PERIOD_NUMBER
	FROM dbo.REPORT_SAVED_FORMS RSF
	WHERE link_saved_form = @iLINK_FORM

	EXEC dbo.GetRandStr 36, @PART_NAME_NNN OUTPUT

	SELECT @INN	= CONVERT (VARCHAR (10), INN_LONG),
			@KPP = CONVERT (VARCHAR (9), KPP),
			@IMNS = CONVERT (VARCHAR (4), IMNS),
			@OKVED = CONVERT (VARCHAR (8), OKVED),
			@DEP_NAME = [NAME],
			@OKTMO_DEP = CONVERT (VARCHAR (11), REPLACE (OKTMO, ' ', ''))
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @DEP_LINK

	SELECT @TLF_GL_BUH = PHONE
	FROM dbo.DICTIONARY_OTV_FACE
	WHERE DEP_LINK = @DEP_LINK
		AND [NAME] = 'Главный бухгалтер'

	SELECT @NAME_RUK = IM,
			@FAM_RUK = FM,
			@OT_RUK = OT
	FROM dbo.KU_EMPL_PLACING 
	WHERE LINK = (SELECT FACE_LINK FROM dbo.DICTIONARY_OTV_FACE
					WHERE DEP_LINK = @DEP_LINK
						AND [NAME] = 'Руководитель')

	--- !!!РАСЧЕТ!!! ---
	-- Данные раздела 1 --
	SELECT
		@iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 1
		)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R1
		(CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (50),
		COL2 VARCHAR(254),	-- КБК
		FCOL2 VARCHAR (254),
		COL3 VARCHAR (100), 	-- ОКТМО
		FCOL3 VARCHAR (254),
		COL4 VARCHAR(100), 	-- Сумма к уплате
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Сумма к уменьшению
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- По месту нахождения
		FCOL6 VARCHAR (254),
		COL7 VARCHAR(100), 	-- Вид имущества
		FCOL7 VARCHAR (254),
		COL8 VARCHAR(100), 	-- Код налогового периода
		FCOL8 VARCHAR (254),
		COL9 VARCHAR(100), 	-- Форма реорганизации
		FCOL9 VARCHAR (254),
		COL10 VARCHAR(100), 	-- INN реорганизации
		FCOL10 VARCHAR (254),
		COL11 VARCHAR(100), 	-- KPP реорганизации
		FCOL11 VARCHAR (254),
		COL12 VARCHAR(100), 	-- Номер корректировки
		FCOL12 VARCHAR (254),
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R1 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, FCOL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, COL7, FCOL7,
		COL8, FCOL8, COL9, FCOL9,
		COL10, FCOL10, COL11, FCOL11, COL12, FCOL12, ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

	SELECT
		@KBK = ISNULL (COL2, ''),
		@OKTMO = ISNULL (COL3, ''),
		@SUMMA = CONVERT (NUMERIC (15), COL4) - ISNULL (CONVERT (NUMERIC (15), COL5), 0),
		@C_PLACE = ISNULL (COL6, ''),
		@cPERIOD_NUM = ISNULL (COL8, ''),

		@cREORG_CODE = ISNULL (COL9, ''),
		@cREORG_INN = ISNULL (COL10, ''),
		@cREORG_KPP = ISNULL (COL11, ''),

		@strNUM_COR = ISNULL (COL12, ''),
		@C_TYPE = ISNULL (COL7, '')
	FROM #TAB_R1

	-- ДАННЫЕ РАЗДЕЛА 2 --
	-- Данные раздела 2.1 --
	--- Остаточная стоимость имущества по месяцам ---
	SELECT 
		@iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 2
		)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R21
		(CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(254),	
		COL3 NUMERIC (20), 	-- Сумма
		FCOL3 VARCHAR (254),
		COL4 NUMERIC (20), 	-- Налоговая ставка
		FCOL4 VARCHAR (254),
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R21 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, COL3, FCOL3,
		COL4, FCOL4, ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

-- SELECT * FROM #TAB_R21

	-- Данные раздела 2.2 --
	-- !!!Расчет!!! --
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 3)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R22
		(CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(254),	
		COL3 NUMERIC (20), 	-- Сумма
		FCOL3 VARCHAR (254),
		COL4 NUMERIC (20, 2), 	-- Налоговая ставка
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Код налоговой льготы 1
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- Код налоговой льготы 2
		FCOL6 VARCHAR (254),
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R22 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, 
		ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

-- SELECT * FROM #TAB_R22

	SELECT @ST_IMUSH = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '150'

	SELECT @CODE_NL = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '160'

	SELECT @ST_IMUSH_NO = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '170'

	SELECT @Dol_ST = CONVERT (VARCHAR (22), COL5)
	FROM #TAB_R22
	WHERE CODE = '180'

	SELECT @NAL_BASE = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '190'

	SELECT @CODE_LG_PNS = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '200'

	SELECT @NAL_STAV = CONVERT (NUMERIC (4,2), COL4)
	FROM #TAB_R22
	WHERE CODE = '210'

	SELECT @SUM_NAL_PER = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '220'

	SELECT @SumAV = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '230'

	SELECT @CODE_LG_UM = CONVERT (VARCHAR (7), COL5)
		+ CASE
			WHEN LEN (COL6) = 0 THEN ''
			ELSE '/' + CONVERT (VARCHAR (12), COL6)
		END
	FROM #TAB_R22
	WHERE CODE = '240'

	SELECT @SUM_LG_UM = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '250'

	SELECT @SUM_NAL_PRED = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '260'

	SELECT
		@OST_SUM_ALL = CONVERT (NUMERIC (15), COL3)
	FROM #TAB_R22
	WHERE CODE = '270'

	-- Данные раздела 3 --
	-- !!!Расчет!!! --
	SELECT 
		@iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM
		AND RT.ORDERS = 4
		)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	CREATE TABLE #TAB_R3
		(
		CHECKED INT,
		UPD INT,
		DEL INT,
		LINK_SAVED_FORM INT,
		LINK_ROW INT,
		ORDERS INT,
		CALC_ORDERS INT,
		PRINT_NULL INT,
		CODE VARCHAR (50),
		COL1 VARCHAR (254),
		COL2 VARCHAR(254),	
		COL3 NUMERIC (20), 	-- Сумма
		FCOL3 VARCHAR (254),
		COL4 NUMERIC (20, 2), 	-- Налоговая ставка
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Код налоговой льготы 1
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- Код налоговой льготы 2
		FCOL6 VARCHAR (254),
		COL7 VARCHAR (100), 	-- Кадастровый номер
		FCOL7 VARCHAR (254),
		ITOG NUMERIC (20)
		) 	
	
	SET @strEXEC = 'INSERT INTO #TAB_R3 (CHECKED, UPD, DEL,
		LINK_SAVED_FORM, LINK_ROW, ORDERS, CALC_ORDERS, PRINT_NULL,
		CODE, COL1, COL2, COL3, FCOL3,
		COL4, FCOL4, COL5, FCOL5,
		COL6, FCOL6, COL7, FCOL7, 
		ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

--	SET @strEXEC = 'EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
--				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

-- SELECT * FROM #TAB_R3

	--- Формирование XML ---
	SELECT @FNAME_ID = 'NO_IMUD_' + ISNULL (RTRIM (@IMNS), '0000') + '_' + ISNULL (RTRIM (@IMNS), '0000') + '_'
		+ ISNULL (RTRIM (@INN), '0000000000') + ISNULL (RTRIM (@KPP), '000000000')
		+ '_' + CONVERT (VARCHAR (10), GETDATE (), 112) + '_'
		+ SUBSTRING (@PART_NAME_NNN, LEN (@PART_NAME_NNN) - 36, 36) 

	SELECT @FNAME = RTRIM (@FNAME_ID) + '.XML'

	DECLARE @OUTPUT TABLE (ID int identity(1,1), F_NAME VARCHAR(254) DEFAULT (''),
			OUT_TEXT TEXT DEFAULT (''))

	--Строка заголовка
	CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))

	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
	INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

	DECLARE @NAME_PROG VARCHAR(254),
		@VERS_PROG VARCHAR(254)

	SELECT @NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
		@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
		+ '.' + (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
		+ '.' + (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
	FROM dbo.DICTIONARY_TASK
	WHERE CODE = 'SMETA'

	SET @NAME_PROG = RTRIM (@NAME_PROG) + ' ' + @VERS_PROG

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'OEM')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<?xml version="1.0" encoding="windows-1251" ?>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Файл xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИдФайл="' + RTRIM (@FNAME_ID) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсПрог="' + RTRIM (LEFT (@NAME_PROG, 40)) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсФорм="5.03">')

-- Документ

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Документ КНД="1152026"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ДатаДок="' + CONVERT (VARCHAR (10), GETDATE (), 104) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Период="' + @cPERIOD_NUM + '"')	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ОтчетГод="' + LTRIM (STR (YEAR (@dDATE_FORM))) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КодНО="' + ISNULL (@IMNS, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НомКорр="' + ISNULL (@strNUM_COR, '0') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ПоМесту="' + ISNULL (@C_PLACE, '') + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СвНП ОКВЭД="' + ISNULL (@OKVED, '') + '"')
	IF ISNULL (@TLF_GL_BUH, '') <> ''
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Тлф="' + RTRIM (ISNULL (@TLF_GL_BUH, '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НПЮЛ НаимОрг="'
			 + RTRIM (ISNULL (REPLACE (@DEP_NAME, '"', '&quot;'), '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИННЮЛ="' + ISNULL (@INN, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КПП="' + ISNULL (@KPP, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '>')

	-- Сведения о реорганизованной (ликвидированной) организации (СвРеоргЮЛ)
	IF LEN (@cREORG_CODE) > 0	
	BEGIN
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СвРеоргЮЛ ФормРеорг="'
			+ ISNULL (@cREORG_CODE, '') + '"')

		IF @cREORG_CODE LIKE '[1-3, 5-6]'
		BEGIN
			INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИННЮЛ="' + @cREORG_INN + '"')
			INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КПП="' + @cREORG_KPP + '"')
		END	
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '/>')
	END

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</НПЮЛ>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СвНП>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Подписант ПрПодп="1">')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ФИО Фамилия="' + RTRIM (ISNULL (@FAM_RUK, '')) 
					+ '" Имя="' + RTRIM (@NAME_RUK) + '"'
					+ CASE WHEN ISNULL (@OT_RUK, '') <> '' THEN ' Отчество="' + RTRIM (ISNULL (@OT_RUK, '')) + '"'
							ELSE '' END
					+ '/>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Подписант>')

	-- Данные налога на имущество --
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ИмущНД>')

   	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СумНалПУ КБК="' + ISNULL (@KBK, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ОКТМО="'
										+ CASE
											WHEN ISNULL (@OKTMO, '') = '' THEN ISNULL (@OKTMO_DEP, '')
											ELSE @OKTMO
										END + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + LTRIM (STR (ISNULL (@SUMMA, 0))) + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОбДеятРФ>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОб ВидИмущ="' + ISNULL (@C_TYPE, '') + '">')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ДанРас СтИмущ="' + LTRIM (STR (ISNULL (@ST_IMUSH, 0))) + '"'
			+	CASE WHEN ISNULL (@CODE_NL, '') = '' THEN ''
					ELSE ' КодНалЛьг="' + @CODE_NL + '"'
				END
			+	CASE WHEN ISNULL (@ST_IMUSH_NO, 0) = 0 THEN ''
					ELSE ' СтИмущНеобл="' + LTRIM (STR (ISNULL (@ST_IMUSH_NO, 0))) + '"'
				END
			+	CASE WHEN ISNULL (@Dol_ST, '') = '' THEN ''
					ELSE ' ДолСт="' + @Dol_ST + '"'
				END
			+	CASE WHEN ISNULL (@CODE_LG_PNS, '') = '' THEN ''
					ELSE ' КодЛгПНС="' + @CODE_LG_PNS + '"'
				END
			+	' НалСтав="' + LTRIM (STR (ISNULL (@NAL_STAV, 0.0), 4, 2)) + '"'
			+ '>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СтоимМес>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) 
	SELECT @FNAME,
		CASE
			WHEN CODE = '141' THEN '<ВтчНедИм'
			ELSE '<ОстСтом' + REPLACE (RTRIM (COL1), '.', '')
		END
		+ CASE WHEN ISNULL (COL3, 0) = 0 THEN ''
				ELSE ' СтОст="' + LTRIM (STR (COL3)) +'"'
			END
		+ CASE WHEN ISNULL (COL4, 0) = 0 THEN ''
				ELSE ' СтЛьгИмущ="' + LTRIM (STR (COL4)) +'"'
			END
		+ '/>'
	FROM #TAB_R21
	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СтОстВс>' + LTRIM (STR (ISNULL (@OST_SUM_ALL, 0))) + '</СтОстВс>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СтоимМес>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ДанРас>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НалПер НалБаза="' + LTRIM (STR (ISNULL (@NAL_BASE, 0))) + '"'
			+ ' СумНалИсчисл="' + LTRIM (STR (ISNULL (@SUM_NAL_PER, 0))) + '"'
			+ CASE WHEN ISNULL (@SumAV, 0) = 0 THEN ''
					ELSE ' СумАвИсчисл="' + LTRIM (STR (ISNULL (@SumAV, 0))) + '"'
				END
			+ CASE WHEN ISNULL (@CODE_LG_UM, '') = '' THEN ''
					ELSE ' КодЛгУмен="' + RTRIM (@CODE_LG_UM) + '"'
			END
			+ CASE WHEN ISNULL (@SUM_LG_UM, 0) = 0 THEN ''
					ELSE ' СумЛгУмен="' + LTRIM (STR (ISNULL (@SUM_LG_UM, 0))) + '"'
			END
			+ CASE WHEN ISNULL (@SUM_NAL_PRED, 0) = 0 THEN ''
					ELSE ' СумНалПред="' + LTRIM (STR (ISNULL (@SUM_NAL_PRED, 0))) + '"'
			END
			+ '/>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОб>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОбДеятРФ>')
	
	-- Выгрузка 3 раздела --
	IF EXISTS (SELECT 1 FROM #TAB_R3 WHERE (CODE = '014' OR CODE = '015') AND ISNULL (COL7, '') <> '')
	BEGIN
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОБНедИО>')

		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасОб>')
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ДанРас>')
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) 
		SELECT
			@FNAME,
			CASE
				WHEN CODE = '014' THEN '<НомКадЗдан>' + LTRIM (ISNULL (COL7, '')) + '</НомКадЗдан>'
				WHEN CODE = '015' AND (ISNULL (COL7, '')) <> '' THEN '<НомКадПом>' + LTRIM (COL7) + '</НомКадПом>'
				WHEN CODE = '040' AND (ISNULL (COL5, '')) <> '' THEN '<КодНалЛьг>' + LTRIM (COL5)
						+
						CASE
							WHEN ISNULL (COL6, '') = '' THEN ''
							ELSE '/' + LTRIM (COL6)
						END
						+ '</КодНалЛьг>'
				WHEN CODE = '050' AND (ISNULL (COL5, '')) <> '' THEN '<ДолСт>' + LTRIM (COL5) + '</ДолСт>'		
				WHEN CODE = '070' AND (ISNULL (COL5, '')) <> '' THEN '<КодЛгПНС>' + LTRIM (COL5)
						+
						CASE
							WHEN ISNULL (COL6, '') = '' THEN ''
							ELSE '/' + LTRIM (COL6)
						END
						+ '</КодЛгПНС>'
				WHEN CODE = '080' THEN '<НалСтав>' + CONVERT (VARCHAR (10), ISNULL (COL4, 0)) + '</НалСтав>'		
				WHEN CODE = '090' AND (ISNULL (COL5, '')) <> '' THEN '<КоэфК>' + LTRIM (COL5)
						+
						CASE
							WHEN ISNULL (COL6, '') = '' THEN ''
							ELSE '/' + LTRIM (COL6)
						END
						+ '</КоэфК>'
				ELSE ''
			END
		FROM #TAB_R3
		WHERE CODE = '014'
			OR CODE = '015' 
			OR CODE = '040'
			OR CODE = '050'
			OR CODE = '070'
			OR CODE = '080'
			OR CODE = '090'
		ORDER BY CODE	

		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СведСтКад>')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) 
		SELECT
			@FNAME,
			CASE 
				WHEN CODE = '020' THEN '<СтИмущК>' + CONVERT (VARCHAR (20), ISNULL (COL3, 0)) + '</СтИмущК>'
				WHEN CODE = '025' AND ISNULL (COL3, 0) <> 0 THEN '<СтИмущНеоблК>' + CONVERT (VARCHAR (20), COL3) + '</СтИмущНеоблК>'
				ELSE ''
			END
		FROM #TAB_R3
		WHERE
			CODE = '020'
			OR CODE = '025' 
		ORDER BY CODE	
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СведСтКад>')

		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СведСтИнв>')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) 
		SELECT
			@FNAME,
			CASE 
				WHEN CODE = '030' THEN '<СтИмущИ>' + CONVERT (VARCHAR (20), ISNULL (COL3, 0)) + '</СтИмущИ>'
				WHEN CODE = '035' AND ISNULL (COL3, 0) <> 0 THEN '<СтИмущНеоблИ>' + CONVERT (VARCHAR (20), COL3) + '</СтИмущНеоблИ>'
				ELSE ''
			END
		FROM #TAB_R3
		WHERE
			CODE = '030'
			OR CODE = '035' 
		ORDER BY CODE	
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СведСтИнв>')

		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ДанРас>')
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НалПер>')
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT)
		SELECT
			@FNAME,
			CASE 
				WHEN CODE = '060' THEN '<НалБаза>' + CONVERT (VARCHAR (20), ISNULL (COL3, 0)) + '</НалБаза>'
				WHEN CODE = '100' THEN '<СумНалИсчисл>' + CONVERT (VARCHAR (20), ISNULL (COL3, 0)) + '</СумНалИсчисл>'
				WHEN CODE = '110' AND ISNULL (COL3, 0) <> 0 THEN '<СумАвИсчисл>' + CONVERT (VARCHAR (20), COL3) + '</СумАвИсчисл>'
				WHEN CODE = '120' AND (ISNULL (COL5, '')) <> '' THEN '<КодЛгУмен>' + LTRIM (COL5)
						+
						CASE
							WHEN ISNULL (COL6, '') = '' THEN ''
							ELSE '/' + LTRIM (COL6)
						END
						+ '</КодЛгУмен>'
				WHEN CODE = '130' AND ISNULL (COL3, 0) <> 0 THEN '<СумЛгУмен>' + CONVERT (VARCHAR (20), COL3) + '</СумЛгУмен>'
				ELSE ''
			END
		FROM #TAB_R3
		WHERE
			CODE = '060' 
			OR CODE = '100' 
			OR CODE = '110' 
			OR CODE = '120' 
			OR CODE = '130' 
		ORDER BY CODE	
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</НалПер>')

		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОб>')
		
		INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</РасОБНедИО>')
	END	-- Выгрузка 3 раздела --

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СумНалПУ>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ИмущНД>')

	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Документ>')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</Файл>')

	SELECT * FROM @OUTPUT ORDER BY ID

	DROP TABLE #TAB_R1
	DROP TABLE #TAB_R21
	DROP TABLE #TAB_R22
	DROP TABLE #TAB_R3
	DROP TABLE #TASK_PROP
END 

GO

GRANT EXECUTE ON dbo.[BK_EXPORT_F1152026_503] TO PUBLIC

GO

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


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

GO


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

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

SET NOCOUNT  ON

--Строка заголовка
CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))

INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

declare @NAME_PROG varchar(254), @VERS_PROG VARCHAR(254)
Select @NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
	@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
from dbo.DICTIONARY_TASK where CODE = 'SALARY'
--------------------------------------------
-- Проставлять ОКАТО или ОКТМО по настройке
DECLARE @OKATO_OR_OKTMO int
SET @OKATO_OR_OKTMO = dbo.SA_GET_OPTION_BY_CODE('NASTR_USE_OKATO_OKTMO') 




DECLARE @LINK_DEP INT, @YEAR INT, @Version TINYINT, @Period_Number TINYINT, @LINK_FORM INT, @Begin_Date DATETIME, @End_Date DATETIME, @modify_date DATETIME
SELECT 
	@LINK_DEP = LINK_ORGANIZATION, 
	@YEAR = YEAR(Begin_Date),
	@Version = [Version],
	@Period_Number = Period_Number,
	@LINK_FORM = LINK_FORM,
	@Begin_Date = dbo.DateBeginOfYear(Begin_Date),
	@End_Date = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,Period_Number*3,YEAR(Begin_Date))),
	@modify_date = modify_date
FROM dbo.REPORT_SAVED_FORMS WHERE LINK_SAVED_FORM = @link

SELECT top 1
	DD1.OKPO AS OKPO1, 
	DD1.INN AS INN1, DD1.KPP AS KPP1, 
	FULL_NAME = UPPER(DD1.FULL_NAME),
	UPPER(DD1.NAME) AS ORGNAME,
	DD2.NALOG AS IMNS_SONO, DD2.NAME AS IMNS_NAME, 
	DD2.NALOG AS SONO, 
	DD1.OGRN AS OGRN1,
	LTRIM(RTRIM(dbo.GetAddressBykladr(DD1.REF_LINK_A))) 
		+ CASE WHEN ISNULL(DD1.HOUSE, '') = '' THEN '' ELSE  ' ' + LTRIM(RTRIM(DD1.HOUSE)) END
		+ CASE WHEN ISNULL(DD1.FLAT, '') = '' THEN '' ELSE ' - ' + LTRIM(RTRIM(DD1.FLAT)) END
	AS ADDR_STR,
	CAST(NULL AS DATETIME) AS DATE_END,
	UPPER(RTRIM(CHIEF.FM) + ' ' + LEFT(CHIEF.IM, 1) + '. ' + LEFT(CHIEF.OT,1) + '.') AS CHIEF_FIO,
	RTRIM(CHIEF.PHONE) AS CH_PHONE,
	UPPER(RTRIM(GLBUH.FM) + ' ' + LEFT(GLBUH.IM, 1) + '. ' + LEFT(GLBUH.OT,1) + '.') AS GLBUH_FIO,
	RTRIM(GLBUH.PHONE) AS GL_PHONE,
	DD1.OGRN,
	DD1.OKATO,
	DD1.OKTMO,
	DD1.OKVED,
	DD1.OKPO,
	DD1.FSS_REG_NUM, --Регистрационный номер (код) страхователя ТФОМС
	DD1.FSS_KOD_P, --Код подчиненности - код, состоящий из пяти цифр, указывающий на территориальный орган Фонда, в котором страхователь зарегистрирован в текущий момент;	
	DD1.FSS_KOD_DOP, --Дополнительный код предусмотрен для обособленных подразделений организаций
	DD1.OKOPF, --- код Общероссийского классификатора организационно-правовых форм;
	DD1.OKFS, --- код Общероссийского классификатора форм собственности;
	DD1.PFNUMBER,
	DA.PINDEX, REGION = UPPER(DA.REGION), DA.REGCODE, RAION = UPPER(DA.RAION), GOROD = UPPER(DA.GOROD), 
	NASEL = UPPER(DA.NASEL), STREET = UPPER(DA.STREET), DA.HOUSE, DA.KORP, DA.FLAT,
	TFOMS_RNUM = DD1.TFOMS_REG_NUM,
	TFOMS_KT = DD1.TFOMS_KT
INTO #DEP_DATA	
FROM DICTIONARY_DEPARTMENT DD1 
	LEFT OUTER JOIN DICTIONARY_DEPARTMENT DD2 ON DD1.IMNS_LINK = DD2.LINK
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Руководитель') chief on chief.link_dep = dd1.link
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Главный бухгалтер') GLBUH ON GLBUH.link_dep = dd1.link
	LEFT JOIN DBO.DEP_ADRESS(@LINK_DEP) DA ON 1=1
WHERE DD1.LINK = @LINK_DEP

DECLARE @Cur0 CURSOR, @TAB_NUM TINYINT, @TAB_NAME VARCHAR(254), @Cur CURSOR, @Cur1 CURSOR, @NUM INT, @BLOK_NAME VARCHAR(254), @RAZDEL_NUM TINYINT, @RAZDEL_NAME VARCHAR(254)

DECLARE @lcFNAME varchar(254)
SELECT @lcFNAME = FSS_REG_NUM + '_' + CONVERT(VARCHAR(4),@YEAR)  + '_' +  (CASE @Period_Number WHEN 1 THEN '3' WHEN 2 THEN '6' WHEN 3 THEN '9' ELSE '0' END) + '.XML' FROM #DEP_DATA

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
  SELECT @lcFNAME, 'OEM' --Имя файла
  UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="windows-1251"?>'
  UNION ALL SELECT @lcFNAME, SPACE(0) + '<?F4FORM version="0.1"?>'
  UNION ALL SELECT @lcFNAME, SPACE(0) + '<F4REPORT>'
  
  /** Титул **/
  
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<TITLE' 
		+ ' REG_NUM="' + LTRIM(RTRIM(FSS_REG_NUM)) + '"'
		+ ' KPS_NUM="' + LTRIM(RTRIM(FSS_KOD_P)) + '"'
		+ ' DOP_NUM="' + LTRIM(RTRIM(FSS_KOD_DOP)) + '"'
		+ ' INN="' + LTRIM(RTRIM(INN1)) + '"'
		+ ' KPP="' + LTRIM(RTRIM(KPP1)) + '"'
		+ ' OGRN="' + LTRIM(RTRIM(OGRN)) + '"'
		+ ' OKOPF="' + LTRIM(RTRIM(OKOPF)) + '"'
		+ CASE WHEN @OKATO_OR_OKTMO = 1 THEN  (' OKATO="' + REPLACE(LTRIM(RTRIM(OKATO)),' ','') + '"') ELSE (' OKTMO="' + REPLACE(LTRIM(RTRIM(OKTMO)),' ','') + '"') END
		+ ' OKPO="' + LTRIM(RTRIM(OKPO)) + '"'
		+ ' OKFS="' + LTRIM(RTRIM(OKFS)) + '"'
		+ ' OKVED="' + LTRIM(RTRIM(OKVED)) + '"'
		+ ' QUART_NUM="' + (CASE @Period_Number WHEN 1 THEN '3' WHEN 2 THEN '6' WHEN 3 THEN '9' ELSE '0' END) + '"'
		+ ' YEAR_NUM="' + CONVERT(VARCHAR(4),@YEAR) + '"'
		+ ' NAME="' + LTRIM(RTRIM(FULL_NAME)) + '"'
		+ ' CRE_DATE="' + convert(varchar(10),@modify_date,120) + '"'
		+ ' WRO="' + LEFT(FSS_REG_NUM,4) + '"'
		+ ' CEO="' + LTRIM(RTRIM(CHIEF_FIO)) + '"'
		+ ' CFO="' + LTRIM(RTRIM(GLBUH_FIO)) + '"'
		+ ' AUTHOR="' + dbo.AdminGetUserFIO(default) + '"'
		+ ' PHONE="' +(SELECT LTRIM(RTRIM(phone)) FROM DICTIONARY_OTV_FACE  WHERE Dep_LINK=dbo.GetOwnDepLink() and name = 'Главный бухгалтер') + '"'
		+ '/>'
		FROM #DEP_DATA
  /** Раздел I **/
  
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '<F4INF1 TaxType="071"'
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' C4="' + CONVERT(VARCHAR(20),CONVERT(INT,SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 1, 1, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' F3="' + CONVERT(VARCHAR(20),CONVERT(INT,SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 1, 2, 3) WHERE SUMMA <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' H3="' + CONVERT(VARCHAR(20),CONVERT(INT,SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 1, 3, 3) WHERE SUMMA <> 0				
		--Таблица 1 строка 1 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 1, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 2 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 3, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' Ch' + LTRIM(STR(ROW +1 - 5)) + '="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, DEFAULT, 3) WHERE SUMMA2 <> 0 AND ROW IN (5,6,7)				
		--Таблица 1 строка 3 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' N0="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 9, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' N' + LTRIM(STR(ROW + 1 - 11)) + '="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, DEFAULT, 3) WHERE SUMMA2 <> 0 AND ROW IN (11,12,13)				
		--Таблица 1 строка 4 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 14, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 5 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NRe0="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 16, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NRe1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 18, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NRe2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 19, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R13="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 20, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 6 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2F0="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 22, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2F1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 24, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2F2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 25, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R16="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 26, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 7 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2N="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 27, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 9 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' FssDebt="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 29, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 11 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R18="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 31, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 12 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R19="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 32, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 14 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R20="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 34, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 15  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R21="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 36, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' Re' + LTRIM(STR(ROW + 1 - 38)) + '="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, DEFAULT, 3) WHERE SUMMA2 <> 0 AND ROW IN (38,39,40)				
		--Таблица 1 строка 16  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R27="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 42, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R29="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 44, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R30="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 45, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R26="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 46, 3) WHERE SUMMA2 <> 0
		--Таблица 1 строка 17  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R32="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 47, 3) WHERE SUMMA2 <> 0
		--Таблица 1 строка 19  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' InsDebt="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 49, 3) WHERE SUMMA2 <> 0
		--Таблица 1 строка 20  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' InsDelDebt="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 50, 3) WHERE SUMMA2 <> 0

		--Таблица 2 строка 1  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 1, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R1C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 1, 4) WHERE SUMMA <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R1C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 1, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R1C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 1, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 2  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 2, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R2C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 2, 4) WHERE SUMMA <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R2C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 2, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R2C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 2, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 3  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R4C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 3, 4) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R4C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 3, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R4C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 3, 6) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 4  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R41C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 4) WHERE SUMMA <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R41C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R41C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 5  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R5C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 5, 4) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R5C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 5, 5) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 6  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R6C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 6, 4) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R6C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 6, 5) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 7  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP7="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 7, 3) WHERE SUMMA <> 0
		--Таблица 2 строка 7  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP75="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 8, 3) WHERE SUMMA <> 0
		--Таблица 2 строка 9  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP71="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 9, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R71C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 9, 4) WHERE SUMMA <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R71C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 9, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R71C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 9, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 10  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP72="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 10, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R72C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 10, 4) WHERE SUMMA <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R72C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 10, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R72C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 10, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 11  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP76="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 11, 3) WHERE SUMMA <> 0
		--Таблица 2 строка 12  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP73="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 12, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R73C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 12, 4) WHERE SUMMA <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R73C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 12, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R73C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 12, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 13  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP74="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 13, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R74C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 13, 4) WHERE SUMMA <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R74C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 13, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R74C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 13, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 14  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R3C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 14, 4) WHERE SUMMA <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R3C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 14, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R3C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 14, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 15  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R8C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 15, 4) WHERE SUMMA <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R8C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 15, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R8C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 15, 6) WHERE SUMMA2 <> 0				

--?  Невыплаченных пособий по временной           ?Сумма (14,2) ?  [0..1]   ?
--?нетрудоспособности                             ?             ?           ?
--?  (S3R1C2N)                                    ?             ?           ?
--???????????????????????????????????????????????????????????????????????????
--?  Невыплаченных пособий по беременности и      ?Сумма (14,2) ?  [0..1]   ?
--?родам                                          ?             ?           ?
--?  (S3R4C2N)                                    ?             ?           ?
--???????????????????????????????????????????????????????????????????????????
--?  Невыплаченных пособий по уходу за ребенком   ?Сумма (14,2) ?  [0..1]   ?
--?  (S3R7C2N)                                    ?             ?           ?

		--Таблица 3 строка 1  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S' + LTRIM(STR(COL + 1 - 3)) + '="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 1, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)				
		--Таблица 3 строка 3  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S' + LTRIM(STR(COL + 1 - 3)) + '_1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 3, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)				
		--Таблица 3 строка 4  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S' + LTRIM(STR(COL + 1 - 3)) + '_2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 4, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)				
		--Таблица 3 строка 5  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S' + LTRIM(STR(COL + 1 - 3)) + '_3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 5, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)				
		--Таблица 4 строка 1  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' FINE_LEFT="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, 1, 3) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' PNLT_LEFT="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, 1, 4) WHERE SUMMA2 <> 0		
		--Таблица 4 строка 2  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' FINE_TAX="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, 2, 3) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' PNLT_TAX="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, 2, 4) WHERE SUMMA2 <> 0		
		--Таблица 4 строка 4  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' FINE_PAY="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, 4, 3) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' PNLT_PAY="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, 4, 4) WHERE SUMMA2 <> 0		
		--Таблица 4 строка 5  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' FINE_RET="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, 5, 3) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' PNLT_RET="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, 5, 4) WHERE SUMMA2 <> 0		
	
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(0) + ' >'
	
		/*Раздел I Платежное поручение*/
		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 44, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,ROW+1-44,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 44, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 44, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 45, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,ROW+1-45,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 45, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 45, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 46, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,ROW+1-46,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 46, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 46, 4)


		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '</F4INF1>'

  /** Раздел II **/

	IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 3, 3) WHERE SUMMA2 <> 0)
	BEGIN

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '<F4INF2 TaxType="021"'
		--Таблица 5  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T1R1C3="' + CONVERT(VARCHAR(20),CONVERT(INT,SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 1, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T1R2C3="' + CONVERT(VARCHAR(20),CONVERT(INT,SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 2, 3) WHERE SUMMA <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T1R3C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 3, 3) WHERE SUMMA2 <> 0				
		--Таблица 6 строка 1 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T2R16C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 1, 3) WHERE SUMMA2 <> 0				
		--Таблица 6 строка 2 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T2R18C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 2, 3) WHERE SUMMA2 <> 0				
		--Таблица 6 строка 3 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T2R19C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 3, 3) WHERE SUMMA2 <> 0				
		--Таблица 6 строка 4 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T2R25C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 4, 3) WHERE SUMMA2 <> 0				

		--Таблица 7 строка 1 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' QCase="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 1, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R1C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 1, 4) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R1C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 1, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R1C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 1, 6) WHERE SUMMA2 <> 0				
		--Таблица 7 строка 2 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' QCase2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 2, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R2C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 2, 4) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R2C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 2, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R2C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 2, 6) WHERE SUMMA2 <> 0				
		--Таблица 7 строка 3 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R4C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 3, 4) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R4C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 3, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R4C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 3, 6) WHERE SUMMA2 <> 0				
		--Таблица 7 строка 4 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R41C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 4, 4) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R41C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 4, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R41C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 4, 6) WHERE SUMMA2 <> 0				
		--Таблица 7 строка 5 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R5C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 5, 4) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R5C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 5, 5) WHERE SUMMA2 <> 0				
		--Таблица 7 строка 6 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R6C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 6, 4) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R6C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 6, 5) WHERE SUMMA2 <> 0				
		--Таблица 7 строка 7 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RCP7="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 7, 3) WHERE SUMMA <> 0				
		--Таблица 7 строка 8 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RCP75="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 8, 3) WHERE SUMMA <> 0				
		--Таблица 7 строка 9 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RCP71="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 9, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R71C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 9, 4) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R71C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 9, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R71C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 9, 6) WHERE SUMMA2 <> 0				
		--Таблица 7 строка 10 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RCP72="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 10, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R72C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 10, 4) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R72C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 10, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R72C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 10, 6) WHERE SUMMA2 <> 0				
		--Таблица 7 строка 11 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RCP76="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 11, 3) WHERE SUMMA <> 0				
		--Таблица 7 строка 12 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RCP73="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 12, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R73C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 12, 4) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R73C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 12, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R73C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 12, 6) WHERE SUMMA2 <> 0				
		--Таблица 7 строка 13 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RCP74="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 13, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R74C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 13, 4) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R74C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 13, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R74C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 13, 6) WHERE SUMMA2 <> 0				
		--Таблица 7 строка 14  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R3C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 14, 4) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R3C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 14, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R3C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 14, 6) WHERE SUMMA2 <> 0				
		--Таблица 7 строка 15  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R8C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 15, 4) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R8C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 15, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T3R8C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 15, 6) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(0) + ' />'

	END	

	/** Раздел III */

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '<F4INFO '
		--Таблица 8 строка 1  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C4="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 6) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C14="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 7) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 8) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C6="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 9) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C16="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 10) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 11) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C8="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 12) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C18="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 13) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C7="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 14) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C10="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 15) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C20="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 16) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 17) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C12="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 18) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C22="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 19) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C11="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 20) WHERE SUMMA2 <> 0		
		--Таблица 8 строка 2  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C4="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 2, 6) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C14="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 2, 7) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 2, 8) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C6="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 2, 9) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C16="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 2, 10) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 2, 11) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C10="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 2, 15) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C20="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 2, 16) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 2, 17) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C12="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 2, 18) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C22="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 2, 19) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C11="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 2, 20) WHERE SUMMA2 <> 0		
		--Таблица 8 строка 3  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R3C4="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 3, 6) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R3C6="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 3, 9) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R3C10="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 3, 15) WHERE SUMMA <> 0
		--Таблица 8 строка 4  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C4="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 4, 6) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C14="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 4, 7) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 4, 8) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C6="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 4, 9) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C16="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 4, 10) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 4, 11) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C10="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 4, 15) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C20="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 4, 16) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 4, 17) WHERE SUMMA2 <> 0		
		--Таблица 8 строка 5  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C4="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 5, 6) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C14="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 5, 7) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 5, 8) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C6="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 5, 9) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C16="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 5, 10) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 5, 11) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C10="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 5, 15) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C20="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 5, 16) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 5, 17) WHERE SUMMA2 <> 0		
		--Таблица 8 строка 6  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C4="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 6, 6) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C14="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 6, 7) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 6, 8) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C6="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 6, 9) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C16="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 6, 10) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 6, 11) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C10="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 6, 15) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C20="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 6, 16) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 6, 17) WHERE SUMMA2 <> 0		
		--Таблица 9   
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T1R1C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T1R4C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, 4) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T1R6C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, 5) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T1R3C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, 6) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T1R5C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, 7) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 3, 6) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 4, 6) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 5, 6) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' I1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 3, 7) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' I2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 4, 7) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' I3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 5, 7) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, 8) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RATE_MIS="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,1),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, 9) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RATE_DEC="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, 10) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' INC_DATE="' + CONVERT(VARCHAR(10),CONVERT(DATETIME,STR_VAL,104),120) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, 11) WHERE STR_VAL <> ''
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RATE_INC="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, 12) WHERE SUMMA <> 0

		--Таблица 10 строка 1 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R1C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 3) WHERE SUMMA2 <> 0				
		--Таблица 10 строка 2 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R3C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 3, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' T7R' + LTRIM(STR(ROW +1 - 1)) + 'C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, DEFAULT, 3) WHERE SUMMA2 <> 0 AND ROW IN (5,6,7)				
		--Таблица 10 строка 3 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R9C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 8, 3) WHERE SUMMA2 <> 0				
		--Таблица 10 строка 4 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R13C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 10, 3) WHERE SUMMA2 <> 0				
		--Таблица 10 строка 5 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R11C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 9, 3) WHERE SUMMA2 <> 0				
		--Таблица 10 строка 6 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R16C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 11, 3) WHERE SUMMA2 <> 0				
		--Таблица 10 строка 8 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R18C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 13, 3) WHERE SUMMA2 <> 0				
		--Таблица 10 строка 9 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R19C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 14, 3) WHERE SUMMA2 <> 0				
		--Таблица 10 строка 10
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' T7R2' + LTRIM(STR(ROW +1 - 16)) + 'C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, DEFAULT, 3) WHERE SUMMA2 <> 0 AND ROW IN (16,18,19,20)				
		--Таблица 10 строка 11
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' T7R' + LTRIM(STR(ROW +21 - 16)) + 'C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, DEFAULT, 3) WHERE SUMMA2 <> 0 AND ROW IN (22,24,25,26)				
		--Таблица 10 строка 12 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R38C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 27, 3) WHERE SUMMA2 <> 0				
		--Таблица 10 строка 14 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R34C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 29, 3) WHERE SUMMA2 <> 0				
		--Таблица 10 строка 15 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R35C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 30, 3) WHERE SUMMA2 <> 0				

		--Таблица 11 строка 1 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R3C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R3C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R13C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R13C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R4C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 3, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R4C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 3, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R8C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R8C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R14C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R14C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R9C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R9C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R5C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 7, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R5C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 7, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R6C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 8, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R6C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 8, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R10C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 9, 4) WHERE SUMMA2 <> 0				

		--Таблица 12 строка 1 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' FINE_LEFT="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' PNLT_LEFT="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 4) WHERE SUMMA2 <> 0						
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' FINE_TAX="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 2, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' PNLT_TAX="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 2, 4) WHERE SUMMA2 <> 0						
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' FINE_PAY="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 4, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' PNLT_PAY="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 4, 4) WHERE SUMMA2 <> 0						
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' FINE_RET="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 5, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' PNLT_RET="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 5, 4) WHERE SUMMA2 <> 0						

		--Таблица 13 
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' M' + LTRIM(STR(ROW +1 - 1)) + '="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, DEFAULT, 3) WHERE SUMMA <> 0 AND ROW IN (1,2,3,5)				


		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(0) + ' >'

		/*Раздел III Платежное поручение*/
		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 24, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,ROW+1-24,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 24, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 24, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 25, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,ROW+1-25,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 25, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 25, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 26, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,ROW+1-26,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 26, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 26, 4)
		

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '</F4INFO>'

	
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, SPACE(0) + '</F4REPORT>'

SET NOCOUNT OFF

select * from #OUTPUT order by [ID]


GO


GRANT EXECUTE ON dbo.[SA_4FSS_EXPORT] TO PUBLIC

GO




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

GO


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

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

SET NOCOUNT  ON

--Строка заголовка
CREATE TABLE #TASK_PROP (ID int identity(1,1), VAL VARCHAR (254))


INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MAJOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_MINOR',1
INSERT INTO #TASK_PROP (VAL) exec dbo.X_GET_PROP_CLIENT 'PROJECT','VERSION_FIX',1

declare @NAME_PROG varchar(254), @VERS_PROG VARCHAR(254)
Select @NAME_PROG = UPPER(RTRIM(LTRIM([NAME]))), 
	@VERS_PROG = (SELECT RTRIM(LTRIM(VAL)) FROM #TASK_PROP WHERE [ID] = 1)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 2)
	+ (SELECT REPLACE(STR(RTRIM(LTRIM(VAL)),2),' ','0') FROM #TASK_PROP WHERE [ID] = 3)
from dbo.DICTIONARY_TASK where CODE = 'SALARY'
--------------------------------------------
-- Проставлять ОКАТО или ОКТМО по настройке
DECLARE @OKATO_OR_OKTMO int
SET @OKATO_OR_OKTMO = dbo.SA_GET_OPTION_BY_CODE('NASTR_USE_OKATO_OKTMO') 


DECLARE @LINK_DEP INT, @YEAR INT, @Version TINYINT, @Period_Number TINYINT, @LINK_FORM INT, 
		@Begin_Date DATETIME, @End_Date DATETIME, @modify_date DATETIME
SELECT 
	@LINK_DEP = LINK_ORGANIZATION, 
	@YEAR = YEAR(Begin_Date),
	@Version = [Version],
	@Period_Number = Period_Number,
	@LINK_FORM = LINK_FORM,
	@Begin_Date = dbo.DateBeginOfYear(Begin_Date),
	@End_Date = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,Period_Number*3,YEAR(Begin_Date))),
	@modify_date = modify_date
FROM dbo.REPORT_SAVED_FORMS 
WHERE LINK_SAVED_FORM = @link

DECLARE 
	@first_month_of_quarter TINYINT, 
	@second_month_of_quarter TINYINT, 
	@third_month_of_quarter TINYINT

IF @Period_Number = 1
	SELECT @first_month_of_quarter = 1, @second_month_of_quarter = 2, @third_month_of_quarter = 3
IF @Period_Number = 2
	SELECT @first_month_of_quarter = 4, @second_month_of_quarter = 5, @third_month_of_quarter = 6
IF @Period_Number = 3
	SELECT @first_month_of_quarter = 7, @second_month_of_quarter = 8, @third_month_of_quarter = 9
IF @Period_Number = 4
	SELECT @first_month_of_quarter = 10, @second_month_of_quarter = 11, @third_month_of_quarter = 12

SELECT  @first_month_of_quarter = ISNULL(@first_month_of_quarter,1), @second_month_of_quarter = ISNULL(@second_month_of_quarter,2), @third_month_of_quarter = ISNULL(@third_month_of_quarter,3)

SELECT top 1
	DD1.OKPO AS OKPO1, 
	DD1.INN AS INN1, DD1.KPP AS KPP1, 
	FULL_NAME = UPPER(DD1.FULL_NAME),
	UPPER(DD1.NAME) AS ORGNAME,
	DD2.NALOG AS IMNS_SONO, DD2.NAME AS IMNS_NAME, 
	DD2.NALOG AS SONO, 
	DD1.OGRN AS OGRN1,
	LTRIM(RTRIM(dbo.GetAddressBykladr(DD1.REF_LINK_A))) 
		+ CASE WHEN ISNULL(DD1.HOUSE, '') = '' THEN '' ELSE  ' ' + LTRIM(RTRIM(DD1.HOUSE)) END
		+ CASE WHEN ISNULL(DD1.FLAT, '') = '' THEN '' ELSE ' - ' + LTRIM(RTRIM(DD1.FLAT)) END
	AS ADDR_STR,
	CAST(NULL AS DATETIME) AS DATE_END,
	UPPER(RTRIM(CHIEF.FM) + ' ' + LEFT(CHIEF.IM, 1) + '. ' + LEFT(CHIEF.OT,1) + '.') AS CHIEF_FIO,
	RTRIM(CHIEF.PHONE) AS CH_PHONE,
	UPPER(RTRIM(GLBUH.FM) + ' ' + LEFT(GLBUH.IM, 1) + '. ' + LEFT(GLBUH.OT,1) + '.') AS GLBUH_FIO,
	RTRIM(GLBUH.PHONE) AS GL_PHONE,
	DD1.OGRN,
	DD1.OKATO,
	DD1.OKTMO,
	DD1.OKVED,
	DD1.OKPO,
	DD1.FSS_REG_NUM, --Регистрационный номер (код) страхователя ТФОМС
	DD1.FSS_KOD_P, --Код подчиненности - код, состоящий из пяти цифр, указывающий на территориальный орган Фонда, в котором страхователь зарегистрирован в текущий момент;	
	DD1.FSS_KOD_DOP, --Дополнительный код предусмотрен для обособленных подразделений организаций
	DD1.OKOPF, --- код Общероссийского классификатора организационно-правовых форм;
	DD1.OKFS, --- код Общероссийского классификатора форм собственности;
	DD1.PFNUMBER,
	DA.PINDEX, REGION = UPPER(DA.REGION), DA.REGCODE, RAION = UPPER(DA.RAION), GOROD = UPPER(DA.GOROD), 
	NASEL = UPPER(DA.NASEL), STREET = UPPER(DA.STREET), DA.HOUSE, DA.KORP, DA.FLAT,
	TFOMS_RNUM = DD1.TFOMS_REG_NUM,
	TFOMS_KT = DD1.TFOMS_KT,
	TaxType = DD1.FSS_KP_PC1,
	TaxType2 = DD1.FSS_KP_PC2,
	TaxType3 = DD1.FSS_KP_PC3
INTO #DEP_DATA	
FROM DICTIONARY_DEPARTMENT DD1 
	LEFT OUTER JOIN DICTIONARY_DEPARTMENT DD2 ON DD1.IMNS_LINK = DD2.LINK
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Руководитель') chief on chief.link_dep = dd1.link
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Главный бухгалтер') GLBUH ON GLBUH.link_dep = dd1.link
	LEFT JOIN DBO.DEP_ADRESS(@LINK_DEP) DA ON 1=1
WHERE DD1.LINK = @LINK_DEP

DECLARE @NumDotC VARCHAR(2), @NumDot INT
SELECT @NumDotC = ISNULL(dbo.RN_GET_ATR_VALUE(@LINK, 'REPORTS_ATR_NOM_OBR'),'00')
SET @NumDot = CASE WHEN ISNUMERIC(@NumDotC) =1 THEN CONVERT(INT,@NumDotC) ELSE 0 END

DECLARE @Cur0 CURSOR, @TAB_NUM TINYINT, @TAB_NAME VARCHAR(254), @Cur CURSOR, @Cur1 CURSOR, @NUM INT, @BLOK_NAME VARCHAR(254), @RAZDEL_NUM TINYINT, @RAZDEL_NAME VARCHAR(254)

DECLARE @lcFNAME varchar(254)
SELECT @lcFNAME = FSS_REG_NUM + '_' + CONVERT(VARCHAR(4),@YEAR)  + '_' +  (CASE @Period_Number WHEN 1 THEN '03' WHEN 2 THEN '06' WHEN 3 THEN '09' ELSE '12' END) + '.XML' FROM #DEP_DATA

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
  SELECT @lcFNAME, 'OEM' --Имя файла
  UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="windows-1251"?>'
  UNION ALL SELECT @lcFNAME, SPACE(0) + '<?F4FORM version="0.5"?>'
  UNION ALL SELECT @lcFNAME, SPACE(0) + '<F4REPORT>'
  
  /** Титул **/
  
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<TITLE' 
		+ ' REG_NUM="' + LTRIM(RTRIM(FSS_REG_NUM)) + '"'
		+ ' KPS_NUM="' + LTRIM(RTRIM(FSS_KOD_P)) + '"'
		+ ' DOP_NUM="' + ISNULL(LTRIM(RTRIM(FSS_KOD_DOP)),'') + '"'
		+ ' INN="' + LTRIM(RTRIM(INN1)) + '"'
		+ ' KPP="' + LTRIM(RTRIM(KPP1)) + '"'
		+ ' OGRN="' + LTRIM(RTRIM(OGRN)) + '"'
		--+ ' OKOPF="' + LTRIM(RTRIM(OKOPF)) + '"'
		+ CASE WHEN @OKATO_OR_OKTMO = 1 THEN  (' OKATO="' + REPLACE(LTRIM(RTRIM(OKATO)),' ','') + '"') ELSE (' OKTMO="' + REPLACE(LTRIM(RTRIM(OKTMO)),' ','') + '"') END
		--+ ' OKPO="' + LTRIM(RTRIM(OKPO)) + '"'
		--+ ' OKFS="' + LTRIM(RTRIM(OKFS)) + '"'
		--+ ' OKVED="' + LTRIM(RTRIM(OKVED)) + '"'
		+ ' QUART_NUM="' + (CASE @Period_Number WHEN 1 THEN '03' WHEN 2 THEN '06' WHEN 3 THEN '09' ELSE '12' END) + '"'
		+ ' YEAR_NUM="' + CONVERT(VARCHAR(4),@YEAR) + '"'
		+ ' NAME="' + LTRIM(RTRIM(REPLACE(FULL_NAME,'"','&quot;'))) + '"'
		+ ' CRE_DATE="' + convert(varchar(10),@modify_date,120) + '"'
		+ ' WRO="' + LEFT(FSS_REG_NUM,4) + '"'
		+ ' CEO="' + LTRIM(RTRIM(CHIEF_FIO)) + '"'
		+ ' CFO="' + LTRIM(RTRIM(GLBUH_FIO)) + '"'
		+ ' AUTHOR="' + ISNULL(dbo.AdminGetUserFIO(default),'') + '"'
		+ ' PHONE="' +(SELECT LTRIM(RTRIM(phone)) FROM DICTIONARY_OTV_FACE  WHERE Dep_LINK=dbo.GetOwnDepLink() and name = 'Главный бухгалтер') + '"'
		+ ' NumCorr="' + LTRIM(RTRIM(CONVERT(VARCHAR(3),@Version))) + '"' --Номер корректировки
		+ ' NumDot="' + LTRIM(RTRIM(CONVERT(VARCHAR(2),@NumDot))) + '"' --Номер корректировки
		+ ' TaxType="' + LEFT(LTRIM(RTRIM(TaxType)),3) + '"' --Шифр (первая часть)
		+ ' TaxType2="' + LEFT(LTRIM(RTRIM(TaxType2)),2) + '"' --Шифр (вторая часть)
		+ ' TaxType3="' + LEFT(LTRIM(RTRIM(TaxType3)),2) + '"' --Шифр (третья часть)		
		+ ' T1R1C2="' + LTRIM(RTRIM(CONVERT(VARCHAR(6),ISNULL((SELECT TOP 1 SUMMA FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 1, 1, 3)),0)))) + '"' --Численность работников	
		+ ' T1R2C2="' + LTRIM(RTRIM(CONVERT(VARCHAR(6),ISNULL((SELECT TOP 1 SUMMA FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 1, 2, 3)),0)))) + '"' --из них: женщин	
		+ ' T1R4C2="' + LTRIM(RTRIM(CONVERT(VARCHAR(6),ISNULL((SELECT TOP 1 SUMMA FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 1, 3, 3)),0)))) + '"' --из них: работающих инвалидов	
		+ ' T1R6C2="' + LTRIM(RTRIM(CONVERT(VARCHAR(6),ISNULL((SELECT TOP 1 SUMMA FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 1, 4, 3)),0)))) + '"' --из них: работающих, занятых на работах с вредными и (или) опасными производственными факторами	
		+ '/>'
		FROM #DEP_DATA
--  /** Раздел I **/

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '<F4INF1 '

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' OKVED="' + LTRIM(RTRIM(OKVED)) + '"' FROM #DEP_DATA
		--Таблица 1 строка 1 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 1, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 2 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 3, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' Ch' + LTRIM(STR(ROW +1 - 5)) + '="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, DEFAULT, 3) WHERE SUMMA2 <> 0 AND ROW IN (5,6,7)				
		--Таблица 1 строка 3 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' N0="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 9, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' N' + LTRIM(STR(ROW + 1 - 11)) + '="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, DEFAULT, 3) WHERE SUMMA2 <> 0 AND ROW IN (11,12,13)				
		--Таблица 1 строка 4 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 14, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 5 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NRe0="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 16, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NRe1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 18, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NRe2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 19, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R13="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 20, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 6 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2F0="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 22, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2F1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 24, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2F2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 25, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R16="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 26, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 7 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2N="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 27, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 9 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' FssDebt="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 29, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 11 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R18="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 31, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 12 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R19="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 32, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 14 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R20="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 34, 3) WHERE SUMMA2 <> 0				
		--Таблица 1 строка 15  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R21="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 36, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' Re' + LTRIM(STR(ROW + 1 - 38)) + '="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, DEFAULT, 3) WHERE SUMMA2 <> 0 AND ROW IN (38,39,40)				
		--Таблица 1 строка 16  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R27="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 42, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R29="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 44, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R30="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 45, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R26="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 46, 3) WHERE SUMMA2 <> 0
		--Таблица 1 строка 17  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S2R32="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 47, 3) WHERE SUMMA2 <> 0
		--Таблица 1 строка 19  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' InsDebt="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 49, 3) WHERE SUMMA2 <> 0
		--Таблица 1 строка 20  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' InsDelDebt="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 50, 3) WHERE SUMMA2 <> 0

		--Таблица 2 строка 1  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 1, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R1C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 1, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R1C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 1, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R1C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 1, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 2  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 2, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R2C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 2, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R2C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 2, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R2C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 2, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 3  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase4="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 3, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R4C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 3, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R4C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 3, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R4C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 3, 6) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 4 
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R41C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R41C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R41C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 5  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R5C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 5, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R5C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 5, 5) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 6  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R6C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 6, 4) WHERE SUMMA2<> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R6C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 6, 5) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 7  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP7="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 7, 3) WHERE SUMMA2 <> 0
		--Таблица 2 строка 8  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP71="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 8, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R71C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 8, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R71C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 8, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R71C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 8, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 9  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP72="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 9, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R72C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 9, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R72C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 9, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R72C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 9, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 10  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R3C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 10, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R3C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 10, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R3C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 10, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 11  
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R8C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 11, 4) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R8C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 11, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R8C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 11, 6) WHERE SUMMA2 <> 0				

		--Таблица 3 строка 1  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S1' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 1, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 2  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S2' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 2, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 3  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S4' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 3, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 5  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S3' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 5, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 6  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S6' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 6, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 7  
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S7' + CASE WHEN COL = 3 THEN '' ELSE '_' + CONVERT(VARCHAR(3),COL-3) END +'="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, 7, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		
		
		--Таблица 4 строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_C="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 1, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 1, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 1, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 1, 6) WHERE SUMMA2 <> 0				
		--Таблица 4 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_CI="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 2, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_CI1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 2, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_CI2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 2, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IOO_CI3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, 2, 6) WHERE SUMMA2 <> 0				
		
		--Таблица 4.1 строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_C="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 1, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 1, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 1, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 1, 6) WHERE SUMMA2 <> 0				
		--Таблица 4.1 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_CI="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 2, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_CI1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 2, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_CI2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 2, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_CI3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,0),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 2, 6) WHERE SUMMA2 <> 0				
		--Таблица 4.1 строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_S="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 4, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_S1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 4, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_S2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 4, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_S3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 4, 6) WHERE SUMMA2 <> 0				
		--Таблица 4.1 строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_SI="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 5, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_SI1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 5, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_SI2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 5, 5) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IUK_SI3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, 5, 6) WHERE SUMMA2 <> 0				

		-- Таблица 4.2 строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_WRK_CNT="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 1, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT2WRK_CNT1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 1, 6) WHERE SUMMA2 <> 0	
		-- Таблица 4.2 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_PRF_ALL="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 2, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT2PRF_ALL="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 2, 6) WHERE SUMMA <> 0				
		-- Таблица 4.2 строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_PRF_SPC="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 3, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT2PRF_SPC="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 3, 6) WHERE SUMMA <> 0				
		-- Таблица 4.2 строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_ACC_DT="' 
							+ CASE LEN(LTRIM(RTRIM(LEFT(STR_VAL,10))))
								WHEN 10 THEN 
									SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),7,4)
									+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),4,2)
									+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),1,2)
								WHEN 8 THEN 
									'20' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),7,2)
									+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),4,2)
									+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),1,2)								
								ELSE
								''
							END	+ '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 5, 4) WHERE ISNULL(STR_VAL,'') <> ''
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' IT_ACC_NM="' + LEFT(STR_VAL,8) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, 5, 5) WHERE ISNULL(STR_VAL,'') <> ''
	
		--Таблица 4.3 строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' OKV_S1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 1, 3) WHERE SUMMA <> 0				
		--Таблица 4.3 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' OKV_S2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, 2, 3) WHERE SUMMA <> 0				


		--Таблица 4.4 строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' CUL_SP1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' CUL_S1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 1, 4) WHERE SUMMA <> 0				
		--Таблица 4.4 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' CUL_SP2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 2, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' CUL_S2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 2, 4) WHERE SUMMA <> 0				
		--Таблица 4.4 строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' CUL_SP3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 3, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' CUL_S3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 3, 4) WHERE SUMMA <> 0				
		--Таблица 4.4 строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' CUL_SP4="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 4, 3) WHERE SUMMA <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' CUL_S4="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 4, 4) WHERE SUMMA <> 0				
	
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(0) + ' >'

		/*Раздел I Платежное поручение*/
		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 44, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@first_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 44, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 44, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 45, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@second_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 45, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 45, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 46, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@third_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 46, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 46, 4)

		--Сведения об инвалидах
		CREATE TABLE #INVALID (
			LINK INT, FIO VARCHAR(254), FIO2 VARCHAR(254), NUM_SPR VARCHAR(30), DATE_SPR VARCHAR(10), 
			GRP VARCHAR(25), GRP2 VARCHAR(25), PER_BEG VARCHAR(10), PER_END VARCHAR(10), 
			SM_ALL 	NUMERIC(18,2), SM_QWART NUMERIC(18,2), SM1 NUMERIC(18,2), SM2 NUMERIC(18,2), SM3 NUMERIC(18,2) )

		CREATE TABLE #TAB5 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
		INSERT INTO #TAB5 (ROW_CODE, COL, SUMMA, STR_VAL)
		SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

		INSERT INTO #INVALID (FIO2, DATE_SPR, PER_END, SM_ALL, SM1, SM2, SM3)
		SELECT DISTINCT 
			FIO2 = (SELECT TOP 1 REPLACE(STR_VAL,SPACE(1), ', ') FROM #TAB5 T WHERE T.COL = 2 AND T.ROW_CODE = T5.ROW_CODE),
			DATE_SPR = (SELECT TOP 1 STR_VAL FROM #TAB5 T WHERE T.COL = 3 AND T.ROW_CODE = T5.ROW_CODE),
			PER_END = (SELECT TOP 1 STR_VAL FROM #TAB5 T WHERE T.COL = 4 AND T.ROW_CODE = T5.ROW_CODE),
			SM_ALL = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 5 AND T.ROW_CODE = T5.ROW_CODE),
			SM1 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 6 AND T.ROW_CODE = T5.ROW_CODE),
			SM2 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 7 AND T.ROW_CODE = T5.ROW_CODE),
			SM3 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 8 AND T.ROW_CODE = T5.ROW_CODE)
		FROM
			#TAB5 T5

		DROP TABLE #TAB5

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, 
			SPACE(1) + ' <F4INVAL'  + 
				' LNAME="' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,1,','),'')))) + '"' +
				' FNAME="' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,2,','),'')))) + '"' +
				' MNAME="' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,3,','),'')))) + '"' +
				' MSEDATE="' + CASE LEN(LTRIM(RTRIM(ISNULL(DATE_SPR,''))))
									WHEN 10 THEN 
										SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),7,4)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),4,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),1,2)
									WHEN 8 THEN 
										'20' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),7,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),4,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),1,2)								
									ELSE
										''
								END + '"' +
				CASE WHEN ISNULL(PER_END,'') <> ''
				THEN 
					' MSEDATEF="' 
								+ CASE LEN(LTRIM(RTRIM(ISNULL(PER_END,''))))
									WHEN 10 THEN 
										SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),7,4)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),4,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),1,2)
									WHEN 8 THEN 
										'20' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),7,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),4,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),1,2)								
									ELSE
									''
								END + '"'
				ELSE
					''	
				END +
				' S="' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM_ALL,0)))) + '"' +
				' S1="' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM1,0)))) + '"' +
				' S2="' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM2,0)))) + '"' +
				' S3="' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM3,0)))) + '"' +
			' />' 
		FROM #INVALID 
		ORDER BY FIO2

		DROP TABLE #INVALID

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '</F4INF1>'

/** Раздел II **/
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(1)

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '<F4INFO '		
		--Таблица 5 Строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C8="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 12) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C18="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 13) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C7="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 14) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 17) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C12="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 18) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C22="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 19) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C11="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 1, 20) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 17) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C12="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 18) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C22="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 19) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C11="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 2, 20) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R3C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 3, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R3C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 3, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R3C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 3, 15) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 4, 17) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 5, 17) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 11, 6, 17) WHERE SUMMA2 <> 0				

		--Таблица 6 Строка 1
		UNION ALL SELECT @lcFNAME, SPACE(1)		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' OKVED="' + LTRIM(RTRIM(OKVED)) + '"' FROM #DEP_DATA
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T1R3C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T1R5C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 5) WHERE SUMMA2 <> 0
		--Таблица 6 Строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 3, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' I1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 3, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 3, 5) WHERE SUMMA2 <> 0
		--Таблица 6 Строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' I2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 5) WHERE SUMMA2 <> 0
		--Таблица 6 Строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' I3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 5) WHERE SUMMA2 <> 0
		--Таблица 6 графа 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RATE_MIS="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,1),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 6) WHERE SUMMA2 <> 0
		--Таблица 6 графа 7
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RATE_DEC="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 7) WHERE SUMMA2 <> 0
		--Таблица 6 графа 8
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' INC_DATE="' 
					+ CASE LEN(LTRIM(RTRIM(LEFT(STR_VAL,10))))
						WHEN 10 THEN 
							SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),7,4)
							+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),4,2)
							+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),1,2)
						WHEN 8 THEN 
							'20' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),7,2)
							+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),4,2)
							+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),1,2)								
						ELSE
						''
					END + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 8) WHERE ISNULL(STR_VAL,'') <> ''

		--Таблица 6 графа 9
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RATE_INC="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 9) WHERE SUMMA2 <> 0

		--Таблица 7 строка 1 
		UNION ALL SELECT @lcFNAME, SPACE(1)		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R1C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R3C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 3, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R5C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 5, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R6C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 6, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R7C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 7, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R9C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 8, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R13C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 9, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R11C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 10, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R16C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 11, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 7
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R17C61="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 12, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 9
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R18C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 14, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 10
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R19C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 15, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 11
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R21C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 17, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R23C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 19, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R24C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 20, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R25C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 21, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 12
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R27C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 23, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R29C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 25, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R30C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 26, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R31C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 27, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 13
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R38C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 28, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 15
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R34C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 30, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 16
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R35C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 31, 3) WHERE SUMMA2 <> 0


		--Таблица 8 строка 1
		UNION ALL SELECT @lcFNAME, SPACE(1)		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R3C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 1, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R3C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 1, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R13C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 2, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R13C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 2, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R4C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 3, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R4C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 3, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R8C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 4, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R8C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 4, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R14C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 5, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R14C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 5, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R9C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 6, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R9C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 6, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 7
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R5C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 7, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R5C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 7, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 8
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R6C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 8, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R6C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 8, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 9
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R10C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 9, 4) WHERE SUMMA2 <> 0

		--Таблица 9
		UNION ALL SELECT @lcFNAME, SPACE(1)
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' M' + CONVERT(VARCHAR(2),ROW) + '="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, DEFAULT, 3) WHERE ROW IN (1,2,3,5) AND SUMMA <> 0

		--Таблица 10 строка 1
		UNION ALL SELECT @lcFNAME, SPACE(1)
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' ATT_C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, 1, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' ATT_C2="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, 1, 4) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' ATT_CL3="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, 1, 5) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' ATT_CL4="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, 1, 6) WHERE SUMMA <> 0

		--Таблица 10 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' MED_C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, 2, 7) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' MED_C2="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, 2, 8) WHERE SUMMA <> 0
		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(0) + ' >'

		/*Раздел I Платежное поручение*/
		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 25, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@first_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 25, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 25, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 26, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@second_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 26, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 26, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 27, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@third_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 27, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 27, 4)
		
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '</F4INFO>'
	
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME, SPACE(0) + '</F4REPORT>'

SET NOCOUNT OFF

select * from #OUTPUT order by [ID]







GO


GRANT EXECUTE ON dbo.[SA_4FSS_EXPORT_v05] TO PUBLIC

GO


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

GO

CREATE PROCEDURE dbo.SD_CONTROL_INCTAX

AS
DECLARE @varKSCalcPer datetime
CREATE TABLE #TempControlTable (OBJ_CODE varchar(30), OBJ_NAME varchar(50), FIELD_NAME varchar(30), LINK	int, COMMENTS varchar(254), Type int)

declare
	@varKSControlObjLink int,
	@varKSControlObjCode varchar(30),
	@varKSControlObjName varchar(100)

declare @DEP_LINK int
exec dbo.xd_whats_zb @DEP_LINK output
	
---
SELECT @varKSControlObjLink = LINK, @varKSControlObjCode = RTRIM(LTRIM(CODE)), @varKSControlObjName = RTRIM(LTRIM(NAME)) 
FROM S_OBJECTS WHERE CODE = 'SD_EMPL'

insert into #TempControlTable
select distinct @varKSControlObjCode, @varKSControlObjName,
'Резидент', link, 'Cтрудник: '+ rtrim(COALESCE(tab,''))+' '+ rtrim(COALESCE(FIO,'')) + ' не является резидентом',1 
FROM SD_EMPL WHERE RESIDENT  = 0

---
SELECT @varKSControlObjLink = LINK, @varKSControlObjCode = RTRIM(LTRIM(COALESCE(CODE,''))), @varKSControlObjName = RTRIM(LTRIM(COALESCE(NAME,''))) 
FROM S_OBJECTS WHERE CODE = 'DICTIONARY_MROT'

declare @link_minrot int, @CalcPeriod datetime
Select  @CalcPeriod = dbo.SalaryPeriodCalcEnd()
Set @link_minrot = ISNULL((select top 1 LINK_MINROT from dbo.Salary_deductions(@CalcPeriod) WHERE TYPE = 5),0)

insert into #TempControlTable
select distinct @varKSControlObjCode, @varKSControlObjName,
'Пределы вычетов', @link_minrot, 'У вычета с кодом ' + rtrim(COALESCE(COD_DED,'')) + ' не задан размер в настройках по зарплате', 1
from DICTIONARY_TYP_INCOMS DTI inner join dbo.pays P on DTI.LINK = P.LINK_INC  
where REF_DEDUCT is not null
and REF_DEDUCT not in (select REF_PAY from dbo.Salary_deductions(@CalcPeriod) WHERE SUMMA > 0)

---
insert into #TempControlTable
select distinct @varKSControlObjCode, @varKSControlObjName,
'Пределы вычетов', @link_minrot, 
(CASE when isnull(P.link_empl,0) = 0 and isnull(P.link_dgh,0) <> 0 
	 then ('У внешт.сотрудника:' + (select ' ФИО ' + FIO +' дог '+ number from salary_reestr_dgh where link = P.link_dgh)) 
	 else ('У сотрудника:' + (select ' таб '+ltrim(TAB) + ' ФИО ' + FIO from sd_empl where link = P.link_empl))  end)  + ', действует вычет с кодом ' + rtrim(COALESCE(DTI.SNAME,'')) + ', который не задан в настройках по зарплате',  
	 1
from DICTIONARY_TYP_DEDUCTION DTI inner join dbo.SD_EMPL_DED P on DTI.LINK = P.LINK_DED  and @CalcPeriod between DATE1 and DATE2
where DTI.LINK not in (select REF_PAY from dbo.Salary_deductions(@CalcPeriod) WHERE SUMMA > 0)

--RESIDENT 1 - НЕРЕЗИДЕНТ БЕЗ ПОСТОЯННОГО ПРОЖИВАНИЯ, 2 - РЕЗИДЕНТ, 3 - НЕРЕЗИДЕНТ С ПОСТОЯННЫМ ПРОЖИВАНИЕМ
IF EXISTS (SELECT * FROM dbo.EMPL E INNER JOIN dbo.PERSON P ON P.LINK = E.PERS_LINK where COALESCE(P.RESIDENT,0) > 0 AND DEP_LINK = @DEP_LINK)
BEGIN

	if not exists (SELECT TOP 1  LINK_PAYS FROM DICTIONARY_RANGE  DR
							WHERE TARIF = 1 AND 2 = (SELECT OBJECT FROM PAYS WHERE link = DR.LINK_PAYS) AND 
							 4 =  (SELECT way_calc FROM PAYS WHERE link = DR.LINK_PAYS) ORDER BY DATE DESC)

	BEGIN

		SELECT @varKSControlObjLink = LINK, @varKSControlObjCode = RTRIM(LTRIM(COALESCE(CODE,''))), @varKSControlObjName = RTRIM(LTRIM(COALESCE(NAME,''))) 
		FROM S_OBJECTS WHERE CODE = 'DICTIONARY_TAX_SALARY'

		insert into #TempControlTable
		select distinct @varKSControlObjCode, @varKSControlObjName,
		'Удержание', 0, 'Среди сотрудников есть резидент Таб.№: ' + LTRIM(RTRIM(E.TAB)) + ' ' + RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.' + ' Не найдено удержание для НФДЛ с резидентов (13%)', 1
		from 
			dbo.EMPL E INNER JOIN dbo.PERSON P ON P.LINK = E.PERS_LINK
		WHERE
			COALESCE(P.RESIDENT,0) > 0 AND DEP_LINK = @DEP_LINK
		
	END	

	if not exists (SELECT TOP 1 [PERCENT] FROM dbo.DICTIONARY_RANGE 
			WHERE TARIF = 1 AND LINK_PAYS = (SELECT TOP 1  LINK_PAYS FROM dbo.DICTIONARY_RANGE  DR
							WHERE  TARIF = 1 AND 2 = (SELECT OBJECT FROM dbo.PAYS WHERE link = DR.LINK_PAYS) AND 
							 4 =  (SELECT way_calc FROM dbo.PAYS WHERE link = DR.LINK_PAYS) ORDER BY DATE DESC)
			AND 
			DATE <= @CalcPeriod ORDER BY DATE DESC )
	BEGIN

		SELECT @varKSControlObjLink = LINK, @varKSControlObjCode = RTRIM(LTRIM(CODE)), @varKSControlObjName = RTRIM(LTRIM(NAME)) 
		FROM S_OBJECTS WHERE CODE = 'DICTIONARY_RANGE'

		insert into #TempControlTable
		select distinct @varKSControlObjCode, @varKSControlObjName,
		'Ставка', 0, 'Не задана ставка для НДФЛ с резидентов (13%)', 1
		from dbo.DICTIONARY_TYP_DEDUCTION DTI inner join dbo.SD_EMPL_DED P on DTI.LINK = P.LINK_DED  and @CalcPeriod between DATE1 and DATE2
	END	

END

--
IF EXISTS (SELECT * FROM dbo.EMPL E INNER JOIN dbo.PERSON P ON P.LINK = E.PERS_LINK where COALESCE(P.RESIDENT,0) = 0 AND DEP_LINK = @DEP_LINK)
BEGIN

	if not exists (SELECT TOP 1  LINK_PAYS FROM dbo.DICTIONARY_RANGE  DR
							WHERE  TARIF = 1 AND 2 = (SELECT OBJECT FROM dbo.PAYS WHERE link = DR.LINK_PAYS) AND 
							 5 =  (SELECT way_calc FROM dbo.PAYS WHERE link = DR.LINK_PAYS) ORDER BY DATE DESC)

	BEGIN

		SELECT @varKSControlObjLink = LINK, @varKSControlObjCode = RTRIM(LTRIM(COALESCE(CODE,''))), @varKSControlObjName = RTRIM(LTRIM(COALESCE(NAME,''))) 
		FROM S_OBJECTS WHERE CODE = 'DICTIONARY_TAX_SALARY'

		insert into #TempControlTable
		select distinct @varKSControlObjCode, @varKSControlObjName,
		'Удержание', 0, 'Среди сотрудников есть не резидент Таб.№: ' + LTRIM(RTRIM(E.TAB)) + ' ' + RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.' + ' Не найдено удержание для НФДЛ с не резидентов (30%)', 1
		from 
			dbo.EMPL E INNER JOIN dbo.PERSON P ON P.LINK = E.PERS_LINK
		WHERE
			COALESCE(P.RESIDENT,0) = 0 AND E.DEP_LINK = @DEP_LINK
	END	

	if not exists (SELECT TOP 1 [PERCENT] FROM dbo.DICTIONARY_RANGE 
			WHERE TARIF = 1 AND LINK_PAYS = (SELECT TOP 1  LINK_PAYS FROM dbo.DICTIONARY_RANGE  DR
							WHERE  TARIF = 1 AND 2 = (SELECT OBJECT FROM dbo.PAYS WHERE link = DR.LINK_PAYS) AND 
							 5 =  (SELECT way_calc FROM dbo.PAYS WHERE link = DR.LINK_PAYS) ORDER BY DATE DESC)
			AND 
			DATE <= @CalcPeriod ORDER BY DATE DESC )
	BEGIN

		SELECT @varKSControlObjLink = LINK, @varKSControlObjCode = RTRIM(LTRIM(CODE)), @varKSControlObjName = RTRIM(LTRIM(NAME)) 
		FROM S_OBJECTS WHERE CODE = 'DICTIONARY_RANGE'

		insert into #TempControlTable
		select distinct @varKSControlObjCode, @varKSControlObjName,
		'Ставка', 0, 'Не задана ставка для НДФЛ с не резидентов (30%)', 1
	END	
END

Select CJ_LINK_DOC = CJ.LINK_DOC, CJ_LINK_VKR = CJ.LINK_VKR, P_link= P.link, P_name = P.name, p_code = p.code
into #CJ
from dbo.CALCULATE_JURNAL CJ inner join dbo.pays p on CJ.LINK_PAYS = p.link and Year(PERIOD_END) = Year(@CalcPeriod) and Month(PERIOD_END) <= Month(@CalcPeriod)
where p.OBJECT = 1 and CJ.LINK_DEP = @DEP_LINK

SELECT @varKSControlObjLink = LINK, @varKSControlObjCode = RTRIM(LTRIM(COALESCE(CODE,''))), @varKSControlObjName = RTRIM(LTRIM(COALESCE(NAME,''))) 
FROM S_OBJECTS WHERE CODE = 'DICTIONARY_PAY_SALARY'

insert into #TempControlTable

Select DISTINCT O_CODE = O.CODE, O_NAME = RTRIM(COALESCE(O.NAME,'')), 'КБК начисления', D_link = COALESCE(D.link,0), 'Сформированы операции без КБК в начислении "' + RTRIM(COALESCE(O.NAME,'')) +'" №' + COALESCE(RTRIM(CONVERT(varchar(100), D.NUMBER)),'') + ' от ' + COALESCE(CONVERT(VARCHAR(10),D.DATE, 104),'')  + ' Установите КБК и переформируйте операции!', 1
from #CJ 
	left join dbo.sdoc D on  CJ_LINK_DOC = D.link
	inner join s_objects O on D.OBJECT = O.link
where coalesce(CJ_LINK_VKR,0) = 0

Select * from #TempControlTable

Return 0



GO


GRANT EXECUTE ON dbo.[SD_CONTROL_INCTAX] TO PUBLIC

GO




GO

--AFTER CODE 12.02.2014
--- ОТЧЕТ: ВЫГРУЗКА ДАННЫХ ОБ ОС (SQL_REP_EXPORT_INV1) --- 
DELETE FROM dbo.OBJECT_VAR WHERE LINK_SELF = (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_EXPORT_INV1_NAS1')
DELETE FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_EXPORT_INV1_NAS1'
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_EXPORT_INV1')
	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_ASSETS'), 'SQL_REP_EXPORT_INV1', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_EXPORT_INV1_NAS1')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'QUERY_NASTRS'), 'Группа настроек', 1, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_EXPORT_INV1'), 'SQL_REP_EXPORT_INV1_NAS1', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_EXPORT_INV1_NAS11')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_DATEBOX_WD'), 'Расчетная дата', 2, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_EXPORT_INV1_NAS1'), 'SQL_REP_EXPORT_INV1_NAS11', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_EXPORT_INV1_NAS12')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_TEXTBOX'), 'Выгрузить ОС стоимостью до (тыс.р.)', 3, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_EXPORT_INV1_NAS1'), 'SQL_REP_EXPORT_INV1_NAS12', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_EXPORT_INV1_NAS13')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_CHECKBOX'), 'Выгрузить данные', 4, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_EXPORT_INV1_NAS1'), 'SQL_REP_EXPORT_INV1_NAS13', NULL, NULL, 1
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'INIT_OBJECT_METHOD', 'm_print_query(nLink_Var)', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'CHECK_VALUE_IN_TABLE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'AFTER_CHANGE_PROG_NASTR', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'BEFORE_CHANGE_PROG_NASTR', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'NASTR_XL_CENTER_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'NASTR_XL_DATETIME', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'NASTR_XL_FOOTER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'NASTR_XL_FREEZEPANES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'NASTR_XL_LEFT_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'NASTR_XL_PAGES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'NASTR_XL_RIGHT_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_ADDFROM', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_ADDINTO', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_ADDSELECT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_ADDWHERE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_AFTER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_BEFORE', 'EXEC dbo.BK_EXPORT_INV1
	@dDateW1,
	@cText1,
	0
', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_DATETIME', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_DISTINCT', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_FOOTER', '="Исполнитель                               " & User_FIO
                                 подпись', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_FREEZEPANES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_HEADER', '=User_Name', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_PAGES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_PROCEDURE', '#REP_EXPORT_INV1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_REPMAKER', 'KIRREPMAKER.XLS', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_REPORT', 'IIF(.T.,"EXPORT_INV1.XLT","")', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_REPORT_PATH', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_SQL', 'CREATE PROCEDURE #REP_EXPORT_INV1
	@dDateW1 datetime	/* Расчетная дата */,
	@cText1 varchar(8000)	/* Выгрузить ОС стоимостью до (тыс.р.) */,
	@nCheck1 int	/* Выгрузить данные */
AS
BEGIN

EXEC dbo.BK_EXPORT_INV1
	@dDateW1,
	@cText1,
	0


END', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_SYSTEM', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_TOP', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_TOTAL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_TOTALCOL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_TOTALROW', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_AP_LIST', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'EOD_PROTOCOL', 'EOD_EXPORT_INV1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'AFTER_REPORT_PROG', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_ADD_MODULE', 'KirRepCommon.bas', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_CODE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_DATE_TYPE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'SQUERY_NO_SHOW', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'QUERY_ALTERNATIVE_PRINT_METHOD', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1', 'REPORT_EXTERNAL_GENERATOR', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS1', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS11', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS11', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS11', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS11', 'QUERY_NASTR_CAPTION', 'Расчетная дата', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS11', 'QUERY_NASTR_CONTROL', 'DATEBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS11', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS11', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS11', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS11', 'QUERY_NASTR_SOURCE', 'Текущая дата,Расчетная дата,Начало расч. периода,Конец расч. периода,Начало года,Конец года,Начало расч. месяца,Конец расч. месяца', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS11', 'QUERY_NASTR_SQLPARAM', '@dDateW1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS11', 'QUERY_NASTR_SQLTYPE', 'datetime', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS11', 'QUERY_NASTR_VALUE', 'Расчетная дата', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS11', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS11', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS12', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS12', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS12', 'FORMAT', '999 999 999 999 999', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS12', 'QUERY_NASTR_CAPTION', 'Выгрузить ОС стоимостью до (тыс.р.)', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS12', 'QUERY_NASTR_CONTROL', 'TEXTBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS12', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS12', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS12', 'QUERY_NASTR_SAVE', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS12', 'QUERY_NASTR_SOURCE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS12', 'QUERY_NASTR_SQLPARAM', '@cText1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS12', 'QUERY_NASTR_SQLTYPE', 'varchar(8000)', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS12', 'QUERY_NASTR_VALUE', '300', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS12', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS12', 'SQUERY_NASTR_OPTIONAL', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS13', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS13', 'SQUERY_NASTR_NON_VISIBLE', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS13', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS13', 'QUERY_NASTR_CAPTION', 'Выгрузить данные', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS13', 'QUERY_NASTR_CONTROL', 'CHECKBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS13', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS13', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS13', 'QUERY_NASTR_SAVE', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS13', 'QUERY_NASTR_SOURCE', 'Выкл.,Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS13', 'QUERY_NASTR_SQLPARAM', '@nCheck1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS13', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS13', 'QUERY_NASTR_VALUE', 'Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS13', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_EXPORT_INV1_NAS13', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO




GO
IF NOT EXISTS (SELECT * FROM dbo.S_NAVIGATOR WHERE CODE = 'SQL_REP_EXPORT_INV1')
	INSERT INTO dbo.S_NAVIGATOR (CODE, NAME, ORDERS, SYS, LINK_SELF, OBJECT, LINK_VAR, IMAGE_KEY, USERS, VISIBLE)
	SELECT 'SQL_REP_EXPORT_INV1', 'Выгрузка данных об ОС', 9, 1, (SELECT LINK FROM dbo.S_NAVIGATOR WHERE CODE = 'DIR_REP_SV_INV'), (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'QUERY_SQL'), (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_EXPORT_INV1'), 'REPORT', NULL, 3
GO

GO
update report_calc_rows
set Mask_KBK = replace(Mask_KBK, 'ОКАТО', 'ОКТМО') 
where Mask_KBK like '%ОКАТО%'
GO

GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_CREDIT_PLAT_DAY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_CREDIT_PLAT_DAY', 'Дней до платежа', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_CREDIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_CREDIT_PLAT_DAY', NAME = 'Дней до платежа', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_CREDIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_CREDIT_PLAT_DAY'
GO
EXEC X_SET_PROP 'BB_CREDIT_PLAT_DAY', 'TITLE', 'Дней до платежа'
GO
EXEC X_SET_PROP 'BB_CREDIT_PLAT_DAY', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_CREDIT_PLAT_DAY', 'CONTROLSOURCE', 'm.cAlias + ".PLAT_DAY"'
GO

GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN', 'Расшифровка сумм неиспользованных средств', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='GROUP_KASSA_DOCUMENTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN', NAME = 'Расшифровка сумм неиспользованных средств', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='GROUP_KASSA_DOCUMENTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='BB_DET_RETURN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_DEP_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_DEP_LINK', 'Организация', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_DEP_LINK', NAME = 'Организация', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_DEP_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_DEP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_DEP_NAME', 'Наименование организации', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_DEP_NAME', NAME = 'Наименование организации', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_DEP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_CARD_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_CARD_LINK', 'Сыллка на  банковскую карту', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_CARD_LINK', NAME = 'Сыллка на  банковскую карту', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_CARD_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_CARD_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_CARD_CODE', 'Номер банковской карты', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_CARD_CODE', NAME = 'Номер банковской карты', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_CARD_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_CARD_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_CARD_NAME', 'Банк', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_CARD_NAME', NAME = 'Банк', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_CARD_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_VID')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_VID', 'Вид операции', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_VID', NAME = 'Вид операции', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_VID'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_TABLE', 'Таблица для расшифровки', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_TABLE', NAME = 'Таблица для расшифровки', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_TABLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_EXPORT_OPT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_EXPORT_OPT', 'Настройки экспорта', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_EXPORT_OPT', NAME = 'Настройки экспорта', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_EXPORT_OPT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_TABLE_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_TABLE_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_TABLE_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE_REC_NO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_TABLE_REC_NO', 'Номер', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_TABLE_REC_NO', NAME = 'Номер', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_TABLE_REC_NO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_T_FIN_S_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_T_FIN_S_NAME', 'Наименование источника финансирования', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_T_FIN_S_NAME', NAME = 'Наименование источника финансирования', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_T_FIN_S_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_T_T_VID_SR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_T_T_VID_SR', 'Наименование источника финансирования', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_T_T_VID_SR', NAME = 'Наименование источника финансирования', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_T_T_VID_SR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_T_KBK_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_T_KBK_CODE', 'Код КБК', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_T_KBK_CODE', NAME = 'Код КБК', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_T_KBK_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_T_EKR_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_T_EKR_CODE', 'Код ЭКР', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_T_EKR_CODE', NAME = 'Код ЭКР', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_T_EKR_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_T_DOP_CL_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_T_DOP_CL_CODE', 'Код доп. классификации', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_T_DOP_CL_CODE', NAME = 'Код доп. классификации', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_T_DOP_CL_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE_ITOG')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_TABLE_ITOG', 'Сумма', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_TABLE_ITOG', NAME = 'Сумма', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_TABLE_ITOG'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE_TITLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_TABLE_TITLE', 'Примечание', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_TABLE_TITLE', NAME = 'Примечание', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_TABLE_TITLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_OPTIONS_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_OPTIONS_NUM', 'Номер файла за дату', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_EXPORT_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_OPTIONS_NUM', NAME = 'Номер файла за дату', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_EXPORT_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_OPTIONS_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_OPTIONS_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_DET_RETURN_OPTIONS_DATE', 'Дата выгрузки', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_EXPORT_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_DET_RETURN_OPTIONS_DATE', NAME = 'Дата выгрузки', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_DET_RETURN_EXPORT_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_DET_RETURN_OPTIONS_DATE'
GO
EXEC X_SET_PROP 'BB_DET_RETURN', 'TITLE', 'Расшифровка сумм неиспользованных средств'
GO
EXEC X_SET_PROP 'BB_DET_RETURN', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "BB_DET_RETURN", "BV_DELETE_DOCUMENTS", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'BB_DET_RETURN', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_DET_RETURN'', m.cAlias,"NUMBER, SQLNULL(DATE), SQLNULL(DATE_PROV), SUMMA, COMMENT, SQLNULL(DEP_LINK), SQLNULL(ACC_LINK), SQLNULL(CARD_LINK), SQLNULL(VID)","BB_DET_RETURN")



'
GO
EXEC X_SET_PROP 'BB_DET_RETURN', 'PRINT_OBJECT_METHOD', 'bb_print_DET_RETURN(oForm.Alias,oForm.Pages.Page3.Table.bGrid1.RecordSource)'
GO
EXEC X_SET_PROP 'BB_DET_RETURN', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''BB_DET_RETURN'')'
GO
EXEC X_SET_PROP 'BB_DET_RETURN', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_LIST_ZB("BB_DET_RETURN")'
GO
EXEC X_SET_PROP 'BB_DET_RETURN', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST("BB_DET_RETURN")'
GO
EXEC X_SET_PROP 'BB_DET_RETURN', 'SNAME', 'Расшифровка сумм неиспользованных средств'
GO
EXEC X_SET_PROP 'BB_DET_RETURN', 'QUERY_REPORT', 'bb_det_return.XLT'
GO
EXEC X_SET_PROP 'BB_DET_RETURN', 'HELP_TOPIC', '21'
GO
EXEC X_SET_PROP 'BB_DET_RETURN', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'BB_DET_RETURN', 'EXCH_MODEL_CODE', 'RN'
GO
EXEC X_SET_PROP 'BB_DET_RETURN', 'EXCHANGE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_DEP_NAME', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_DEP_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_DEP_NAME', 'CONTROLSOURCE', 'm.cAlias+".DEP_NAME"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_DEP_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_DEP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DEP_NAME"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_CARD_LINK', 'SHORT_CODE_OBJ', 'CARD_LINK'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_CARD_LINK', 'CONTROLSOURCE_EDIT', 'm.cALIAS+".CARD_LINK"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_CARD_CODE', 'TITLE', '№ карты'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_CARD_CODE', 'EDIT_OBJECT_METHOD', 'N_VIBOR_01 ("SD_PERSON_ECARD", oForm.ALIAS, "LINK,LIC_SCHET,BANK_NAME", "CARD_LINK, CARD_CODE, CARD_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_CARD_CODE', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_CARD_CODE', 'CONTROLSOURCE', 'm.cALIAS+".CARD_CODE"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_CARD_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_CARD_CODE', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_CARD_CODE', 'SHORT_CODE_OBJ', 'CARD_CODE'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_CARD_CODE', 'CONTROLSOURCE_EDIT', 'm.cALIAS+".CARD_CODE"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_CARD_CODE', 'CONTROL_NAME_EDIT', 'aSel_spr6'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_CARD_NAME', 'TITLE', 'Банк карты'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_CARD_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_CARD_NAME', 'SHORT_CODE_OBJ', 'CARD_NAME'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_CARD_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CARD_NAME"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_CARD_NAME', 'CONTROL_NAME_EDIT', 'aTxtBank'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_VID', 'TITLE', 'Вид операции'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_VID', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_VID', 'CONTROLSOURCE', 'm.cAlias + ".VID"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_VID', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_VID', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".VID"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_VID', 'CONTROL_NAME_EDIT', 'aOptVid'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE', 'SAVE_OBJECT_METHOD', 'x_save(''X_UPDATE_RECEPTION_CASH_TABLE'', m.cAlias, ''LINK_UP, FS_CODE,VID_SR, KBK, EKR, D_CL_LINK, SUMMA, RECORD_NO, "", TITLE, ""'', ''BB_DET_RETURN_TABLE'')
'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE', 'SELECT_RECORDS_METHOD', 'ftable_reception_cash_select(m.cAlias, m.nLink, ''BB_DET_RETURN_TABLE_VIEW'')'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE', 'SERVER_TABLE_NAME', 'RECEPTION_CASH_TABLE'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_EXPORT_OPT', 'TITLE', 'Настройки "Заявка на получение наличных денег"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_EXPORT_OPT', 'OPTIONS_OBJECT_CODE', 'DOC_REC_CARD_OPTIONS'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_CHECKED', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_CHECKED', 'CONTROLSOURCE', 'm.cAlias+''.CHECKED'''
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_CHECKED', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_REC_NO', 'TITLE', 'Номер'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_REC_NO', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_REC_NO', 'CONTROLSOURCE', 'm.cAlias + ".RECORD_NO"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_REC_NO', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_REC_NO', 'TYPE_FIELD_DICT', 'NUMERIC(9)'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_REC_NO', 'SHORT_CODE_OBJ', 'RECORD_NO'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_REC_NO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".RECORD_NO"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_REC_NO', 'INPUT_MASK', '999999999'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_FIN_S_NAME', 'TITLE', 'Источник финансирования'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_FIN_S_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_FIN_S_NAME', 'CONTROLSOURCE', 'm.cAlias + ".FS_NAME"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_FIN_S_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_FIN_S_NAME', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_FIN_S_NAME', 'SHORT_CODE_OBJ', 'FS_NAME'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_FIN_S_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".FS_NAME"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_T_VID_SR', 'TITLE', 'Вид средств'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_T_VID_SR', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_T_VID_SR', 'CONTROLSOURCE', 'm.cAlias + ".VID_SR_SNAME"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_T_VID_SR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_T_VID_SR', 'TYPE_FIELD_DICT', 'varchar(150)'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_T_VID_SR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".VID_SR_SNAME"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_KBK_CODE', 'TITLE', 'КБК'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_KBK_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("bi_diction_kbk", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "KBK, KBK_CODE, KBK_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_KBK_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_KBK_CODE', 'CONTROLSOURCE', 'm.cAlias + ".KBK_CODE"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_KBK_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_KBK_CODE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_KBK_CODE', 'REFERENCE_TO_DICT', 'AVANCE_ACCEPT_TABLE_KBK_LINK'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_KBK_CODE', 'TYPE_FIELD_DICT', 'char(5)'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_KBK_CODE', 'SHORT_CODE_OBJ', 'KBK_CODE'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_KBK_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".KBK_CODE"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_KBK_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_EKR_CODE', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_EKR_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_ITEM", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "EKR, EKR_CODE, EKR_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_EKR_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_EKR_CODE', 'CONTROLSOURCE', 'm.cAlias + ".EKR_CODE"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_EKR_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_EKR_CODE', 'SHORT_CODE_OBJ', 'EKR_CODE'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_EKR_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".EKR_CODE"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_DOP_CL_CODE', 'TITLE', 'Доп. классиф-ия'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_DOP_CL_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("BD_DOP_CLASSIF", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "D_CL_LINK, D_CL_CODE, D_CL_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_DOP_CL_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_DOP_CL_CODE', 'CONTROLSOURCE', 'm.cAlias + ".D_CL_CODE"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_DOP_CL_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_DOP_CL_CODE', 'SHORT_CODE_OBJ', 'D_CL_CODE'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_T_DOP_CL_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".D_CL_CODE"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_ITOG', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_ITOG', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_ITOG', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_ITOG', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_ITOG', 'SHORT_CODE_OBJ', 'SUMMA'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_ITOG', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_TITLE', 'TITLE', 'Примечание'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_TITLE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_TITLE', 'CONTROLSOURCE', 'm.cAlias+".TITLE"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_TITLE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_TITLE', 'SHORT_CODE_OBJ', 'TITLE'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_TABLE_TITLE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TITLE"'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_OPTIONS_NUM', 'TITLE', 'Номер файла за дату'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_OPTIONS_NUM', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_OPTIONS_NUM', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_OPTIONS_NUM', 'SHORT_CODE_OBJ', 'NUM'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_OPTIONS_NUM', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_OPTIONS_DATE', 'TITLE', 'Дата выгрузки'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_OPTIONS_DATE', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_OPTIONS_DATE', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_OPTIONS_DATE', 'SHORT_CODE_OBJ', 'DATE'
GO
EXEC X_SET_PROP 'BB_DET_RETURN_OPTIONS_DATE', 'CONTROL_NAME_EDIT', 'ATxtN1'
GO
/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Расшифровка сумм неиспользованных средств"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

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

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

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

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'BB_DET_RETURN', 'Расшифровка сумм неиспользованных средств', @ORD, NULL, 1, @LINK_SELF, 'DOCUMENT', @OBJECT, @LINK_VAR, 3
GO


GO
update EXPORT_MODELS set DATE_END   = '20131231' WHERE MODEL_VER = 'TXZR090101' AND CODE = 'AP'
update EXPORT_MODELS set DATE_END   = '20140228' WHERE MODEL_VER = 'TXZR100701' AND CODE = 'AP'
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXAP140101' AND CODE = 'AP'
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 'AP','Расходное расписание','TXAP140101',0,'','XXXXXDNN.TTM','fb_file_name_doc','FB_EXPORT_RR','cObjCode','KOD_UBP','fb_import_rr_104()',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Расходное расписание',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'FB_EXPORT_RR',
		PROC_DOP_PARAM   = 'cObjCode',
		PROG_SAVE   = 'fb_import_rr_104()',
		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	= 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	= 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, 3,'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 		= 4,
		NAME   		= 'Код УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'KOD_UBP','Код УБП','STRING',5,1,0,0,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Наименование УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'NAME_UBP','Наименование УБП','STRING',2000,0,0,0,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 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	= 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, 3,'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 		= 4,
		NAME   		= 'Код УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'KOD_UBP','Код УБП','STRING',5,1,0,0,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Наименование УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'NAME_UBP','Наименование УБП','STRING',2000,0,1,0,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'AP'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'AP',4,2,'Информация об участнике бюджетного процесса, формирующего расходное расписание и о реестре расходных расписаний',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 2,
			NAME   = 'Информация об участнике бюджетного процесса, формирующего расходное расписание и о реестре расходных расписаний',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK_R')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 30,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID_FK_R',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK_R'
else		
	INSERT INTO EXPORT_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_R','Глобальный уникальный идентификатор','STRING',30,0,0,0,'GUID_FK_R','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_R_RR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= '№ реестра расходных расписаний',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_R_RR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_R_RR'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NOM_R_RR','№ реестра расходных расписаний','STRING',3,0,0,0,'NOM_R_RR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_R_RR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Дата реестра расходных расписаний',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_R_RR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_R_RR'
else		
	INSERT INTO EXPORT_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_R_RR','Дата реестра расходных расписаний','DATE',NULL,0,0,0,'DATE_R_RR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код распорядителя средств (получателя бюджетных средств) / администратора источников финансирования с отдельными полномочиями главного администратора источников финансирования',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'KOD_UBP','Код распорядителя средств (получателя бюджетных средств) / администратора источников финансирования с отдельными полномочиями главного администратора источников финансирования','STRING',5,1,0,0,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Полное наименование распорядителя средств (получателя бюджетных средств)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'NAME_UBP','Полное наименование распорядителя средств (получателя бюджетных средств)','STRING',2000,0,0,0,'NAME_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA_GRS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Код главного распорядителя средств (главного администратора источников финансирования)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GLAVA_GRS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA_GRS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'GLAVA_GRS','Код главного распорядителя средств (главного администратора источников финансирования)','STRING',3,1,0,0,'GLAVA_GRS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_GRS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Полное наименование главного распорядителя средств (главного администратора источников финансирования)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_GRS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_GRS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'NAME_GRS','Полное наименование главного распорядителя средств (главного администратора источников финансирования)','STRING',2000,0,0,0,'NAME_GRS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Номер лицевого счета участника бюджетного процесса, сформировавшего расходное расписание или реестр расходных расписаний',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'LS_UBP','Номер лицевого счета участника бюджетного процесса, сформировавшего расходное расписание или реестр расходных расписаний','STRING',11,1,0,0,'LS_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		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, 9,'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 		= 10,
		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, 10,'NAME_TOFK','Полное наименование органа ФК, в котором главному (распорядителю) бюджетных средств, формирующему расходное расписание, открыт соответствующий лицевой счет','STRING',2000,0,0,0,'NAME_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Наименование бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_BUD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'NAME_BUD','Наименование бюджета','STRING',512,0,0,1,'NAME_BUD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Финансовый орган',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'NAME_FO','Финансовый орган','STRING',2000,0,0,0,'NAME_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Должность руководителя (уполномоченного им лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_RUK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'DOL_RUK','Должность руководителя (уполномоченного им лица)','STRING',100,0,0,0,'DOL_RUK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'ФИО руководителя (уполномоченного им лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_RUK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'NAME_RUK','ФИО руководителя (уполномоченного им лица)','STRING',50,0,0,1,'NAME_RUK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Должность ответственного исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DOL_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'DOL_ISP','Должность ответственного исполнителя','STRING',100,0,0,1,'DOL_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'ФИО ответственного исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 16,'NAME_ISP','ФИО ответственного исполнителя','STRING',50,0,0,1,'NAME_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Телефон ответственного исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'TEL_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'TEL_ISP','Телефон ответственного исполнителя','STRING',50,0,0,1,'TEL_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATA_POD_RR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Дата подписания расходного расписания руководителем (уполномоченным лицом)',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATA_POD_RR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATA_POD_RR'
else		
	INSERT INTO EXPORT_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,'DATA_POD_RR','Дата подписания расходного расписания руководителем (уполномоченным лицом)','DATE',NULL,1,0,1,'DATA_POD_RR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_BU')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Дата учета Расходного расписания в бюджетном учете в органе ФК отправителе.',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_BU',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_BU'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 19,'DATE_BU','Дата учета Расходного расписания в бюджетном учете в органе ФК отправителе.','DATE',NULL,0,0,0,'DATE_BU','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_UTV_R_R')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'Дата введения в действие реестра расходных расписаний',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_UTV_R_R',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_UTV_R_R'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 20,'DATE_UTV_R_R','Дата введения в действие реестра расходных расписаний','DATE',NULL,0,0,0,'DATE_UTV_R_R','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATA_POD_RR_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Дата подписания расходного расписания ответственным исполнителем',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATA_POD_RR_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATA_POD_RR_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 21,'DATA_POD_RR_ISP','Дата подписания расходного расписания ответственным исполнителем','DATE',NULL,0,0,1,'DATA_POD_RR_ISP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'APRC'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'APRC',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 = 'GUID_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'GUID_FK','Глобальный уникальный идентификатор','STRING',36,0,0,0,'GUID_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_RR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= '№ расходного расписания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 13,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_RR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_RR'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NOM_RR','№ расходного расписания','STRING',13,0,1,1,'NOM_RR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_FORM_RR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Дата расходного расписания',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_FORM_RR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_FORM_RR'
else		
	INSERT INTO EXPORT_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_FORM_RR','Дата расходного расписания','DATE',NULL,1,1,1,'DATE_FORM_RR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_UTV_RR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Дата введения в действие расходного расписания',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_UTV_RR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_UTV_RR'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'DATE_UTV_RR','Дата введения в действие расходного расписания','DATE',NULL,0,0,0,'DATE_UTV_RR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_RR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Признак секретности расходного расписания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'VID_RR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_RR'
else		
	INSERT INTO EXPORT_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_RR','Признак секретности расходного расписания','STRING',1,1,0,1,'VID_RR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Код участника бюджетного процесса, которому должно быть доведено данное расходное расписание (Кому)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'KOD_UBP','Код участника бюджетного процесса, которому должно быть доведено данное расходное расписание (Кому)','STRING',5,1,0,0,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Полное наименование участника бюджетного процесса, которому должно быть доведено данное расходное расписание (Кому)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		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, 7,'NAME_UBP','Полное наименование участника бюджетного процесса, которому должно быть доведено данное расходное расписание (Кому)','STRING',2000,0,0,1,'NAME_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Номер лицевого счета участника бюджетного процесса, которому должно быть доведено данное расходное расписание (Кому)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'LS_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'LS_UBP','Номер лицевого счета участника бюджетного процесса, которому должно быть доведено данное расходное расписание (Кому)','STRING',11,1,1,1,'LS_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		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, 9,'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 		= 10,
		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, 10,'NAME_TOFK','Полное наименование органа ФК, в котором открыт лицевой счет распорядителю (получателю, иному получателю) бюджетных средств, в адрес которого будет направлено расходное расписание (Куда)','STRING',2000,0,0,0,'NAME_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE_RR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Специальные указания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 700,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOTE_RR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE_RR'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'NOTE_RR','Специальные указания','STRING',700,0,0,0,'NOTE_RR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE_CODE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Код специального указания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOTE_CODE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE_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, 12,'NOTE_CODE','Код специального указания','STRING',5,0,0,0,'NOTE_CODE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Тип БК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'TYPE_KBK','Тип БК','STRING',2,1,0,1,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_BA_1Y')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'ИТОГО изменений бюджетных ассигнования на текущий финансовый год по расходному расписанию',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_BA_1Y',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_BA_1Y'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'SUM_BA_1Y','ИТОГО изменений бюджетных ассигнования на текущий финансовый год по расходному расписанию','NUMBER2',NULL,0,0,2,'SUM_BA_1Y','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_BA_2Y')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'ИТОГО изменений бюджетных ассигнования на 1-й год планового периода по расходному расписанию',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_BA_2Y',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_BA_2Y'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'SUM_BA_2Y','ИТОГО изменений бюджетных ассигнования на 1-й год планового периода по расходному расписанию','NUMBER2',NULL,0,0,2,'SUM_BA_2Y','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_BA_3Y')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'ИТОГО изменений бюджетных ассигнования на 2-й год планового периода по расходному расписанию',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_BA_3Y',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_BA_3Y'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 16,'SUM_BA_3Y','ИТОГО изменений бюджетных ассигнования на 2-й год планового периода по расходному расписанию','NUMBER2',NULL,0,0,2,'SUM_BA_3Y','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_LBO_1Y')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'ИТОГО изменений лимитов бюджетных обязательств на текущий финансовый год по расходному расписанию',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_LBO_1Y',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_LBO_1Y'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'SUM_LBO_1Y','ИТОГО изменений лимитов бюджетных обязательств на текущий финансовый год по расходному расписанию','NUMBER2',NULL,0,0,2,'SUM_LBO_1Y','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_LBO_2Y')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'ИТОГО изменений лимитов бюджетных обязательств на 1-й год планового периода по расходному расписанию',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_LBO_2Y',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_LBO_2Y'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 18,'SUM_LBO_2Y','ИТОГО изменений лимитов бюджетных обязательств на 1-й год планового периода по расходному расписанию','NUMBER2',NULL,0,0,2,'SUM_LBO_2Y','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_LBO_3Y')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'ИТОГО изменений лимитов бюджетных обязательств на 2-й год планового периода по расходному расписанию',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_LBO_3Y',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_LBO_3Y'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 19,'SUM_LBO_3Y','ИТОГО изменений лимитов бюджетных обязательств на 2-й год планового периода по расходному расписанию','NUMBER2',NULL,0,0,2,'SUM_LBO_3Y','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_POF_1Y')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'ИТОГО изменений предельных объемов финансирования на текущий финансовый год по расходному расписанию',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_POF_1Y',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_POF_1Y'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 20,'SUM_POF_1Y','ИТОГО изменений предельных объемов финансирования на текущий финансовый год по расходному расписанию','NUMBER2',NULL,0,0,2,'SUM_POF_1Y','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Номер Заявки на кассовый расход',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 21,'NOM_PP','Номер Заявки на кассовый расход','STRING',15,0,0,0,'NOM_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Дата Заявки на кассовый расход',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_PP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_PP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 22,'DATE_PP','Дата Заявки на кассовый расход','DATE',NULL,0,0,0,'DATE_PP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_UTV_BA')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Дата введения в действие раздела БА расходного расписания',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_UTV_BA',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_UTV_BA'
else		
	INSERT INTO EXPORT_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_UTV_BA','Дата введения в действие раздела БА расходного расписания','DATE',NULL,0,0,0,'DATE_UTV_BA','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_UTV_LBO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Дата введения в действие раздела ЛБО расходного расписания',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_UTV_LBO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_UTV_LBO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 24,'DATE_UTV_LBO','Дата введения в действие раздела ЛБО расходного расписания','DATE',NULL,0,0,0,'DATE_UTV_LBO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_UTV_POF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Дата введения в действие раздела ПОФ расходного расписания',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_UTV_POF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_UTV_POF'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 25,'DATE_UTV_POF','Дата введения в действие раздела ПОФ расходного расписания','DATE',NULL,0,0,0,'DATE_UTV_POF','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'APBASTR'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'APBASTR',6,2,'Бюджетные ассигнования',0
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 6,
			ISONCE = 2,
			NAME   = 'Бюджетные ассигнования',
			OBLIGATORY = 0
	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	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KBK','Код по БК','STRING',20,1,1,1,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		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, 2,'ADD_KLASS','Код цели','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_BA_Y1')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'БА на текущий финансовый год',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_BA_Y1',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_BA_Y1'
else		
	INSERT INTO EXPORT_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_BA_Y1','БА на текущий финансовый год','NUMBER2',NULL,0,1,2,'SUM_BA_Y1','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_BA_Y2')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'БА на 1-й год планового периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_BA_Y2',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_BA_Y2'
else		
	INSERT INTO EXPORT_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,'SUM_BA_Y2','БА на 1-й год планового периода','NUMBER2',NULL,0,1,2,'SUM_BA_Y2','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_BA_Y3')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'БА на 2-й год планового периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_BA_Y3',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_BA_Y3'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'SUM_BA_Y3','БА на 2-й год планового периода','NUMBER2',NULL,0,1,2,'SUM_BA_Y3','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE_BASTR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Примечание',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOTE_BASTR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE_BASTR'
else		
	INSERT INTO EXPORT_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,'NOTE_BASTR','Примечание','STRING',254,0,0,0,'NOTE_BASTR','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'APLBOSTR'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'APLBOSTR',7,2,'Лимиты бюджетных обязательств',0
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 7,
			ISONCE = 2,
			NAME   = 'Лимиты бюджетных обязательств',
			OBLIGATORY = 0
	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	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KBK','Код по БК','STRING',20,1,1,1,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		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, 2,'ADD_KLASS','Код цели','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_LBO_Y1')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'ЛБО на текущий финансовый год',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_LBO_Y1',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_LBO_Y1'
else		
	INSERT INTO EXPORT_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_LBO_Y1','ЛБО на текущий финансовый год','NUMBER2',NULL,0,1,2,'SUM_LBO_Y1','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_LBO_Y2')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'ЛБО на 1-й год планового периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_LBO_Y2',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_LBO_Y2'
else		
	INSERT INTO EXPORT_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,'SUM_LBO_Y2','ЛБО на 1-й год планового периода','NUMBER2',NULL,0,1,2,'SUM_LBO_Y2','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_LBO_Y3')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'ЛБО на 2-й год планового периода',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_LBO_Y3',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_LBO_Y3'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'SUM_LBO_Y3','ЛБО на 2-й год планового периода','NUMBER2',NULL,0,1,2,'SUM_LBO_Y3','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE_LBOSTR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Примечание',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOTE_LBOSTR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE_LBOSTR'
else		
	INSERT INTO EXPORT_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,'NOTE_LBOSTR','Примечание','STRING',254,0,0,0,'NOTE_LBOSTR','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'APPOFSTR'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'APPOFSTR',8,2,'Предельные объемы финансирования',0
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 8,
			ISONCE = 2,
			NAME   = 'Предельные объемы финансирования',
			OBLIGATORY = 0
	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	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KBK','Код по БК','STRING',20,1,1,1,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		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, 2,'ADD_KLASS','Код цели','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_POF_Y1')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'ПОФ на текущий финансовый год',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_POF_Y1',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_POF_Y1'
else		
	INSERT INTO EXPORT_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_POF_Y1','ПОФ на текущий финансовый год','NUMBER2',NULL,0,1,2,'SUM_POF_Y1','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE_POFSTR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Примечание',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOTE_POFSTR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE_POFSTR'
else		
	INSERT INTO EXPORT_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,'NOTE_POFSTR','Примечание','STRING',254,0,0,0,'NOTE_POFSTR','',''
GO

GO
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 = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 25,'PURPOSE','Назначение платежа','STRING',210,0,0,0,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'Статус составителя расчетного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PAYSTATUS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 26,'PAYSTATUS','Статус составителя расчетного документа','STRING',2,0,0,0,'PAYSTATUS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'Код бюджетной классификации',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 27,'KBK','Код бюджетной классификации','STRING',20,1,0,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Код ОКТМО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKATO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 28,'OKATO','Код ОКТМО','STRING',11,0,0,0,'OKATO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OSNPLAT')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 29,
		NAME   		= 'Показатель основания платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OSNPLAT',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OSNPLAT'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 29,'OSNPLAT','Показатель основания платежа','STRING',2,0,0,0,'OSNPLAT','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAL_PER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 30,
		NAME   		= 'Показатель налогового периода',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAL_PER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAL_PER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 30,'NAL_PER','Показатель налогового периода','STRING',10,0,0,0,'NAL_PER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 31,
		NAME   		= 'Показатель номера документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_DOK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 31,'NOM_DOK','Показатель номера документа','STRING',15,0,0,0,'NOM_DOK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'Показатель даты документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_DOK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 32,'DATE_DOK','Показатель даты документа','STRING',10,0,0,0,'DATE_DOK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 33,
		NAME   		= 'Тип платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 33,'TYPE_PL','Тип платежа','STRING',2,0,0,0,'TYPE_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PL_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 34,
		NAME   		= 'Номер частичного платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_PL_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_PL_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 34,'NOM_PL_PO','Номер частичного платежа','STRING',3,0,0,0,'NOM_PL_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SHIFR_RD_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 35,
		NAME   		= 'Шифр платежно-го документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SHIFR_RD_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SHIFR_RD_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 35,'SHIFR_RD_PO','Шифр платежно-го документа','STRING',2,1,0,0,'SHIFR_RD_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_RD_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 36,
		NAME   		= 'Номер платежного документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_RD_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_RD_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 36,'NOM_RD_PO','Номер платежного документа','STRING',3,0,0,0,'NOM_RD_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_RD_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 37,
		NAME   		= 'Дата платежного документа',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_RD_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_RD_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 37,'DATE_RD_PO','Дата платежного документа','DATE',0,0,0,0,'DATE_RD_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_OST_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 38,
		NAME   		= 'Сумма остатка платежа',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_OST_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_OST_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 38,'SUM_OST_PO','Сумма остатка платежа','NUMBER2',0,0,0,0,'SUM_OST_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OPER_PO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 39,
		NAME   		= 'Содержание опе-рации',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 16,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OPER_PO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OPER_PO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 39,'OPER_PO','Содержание опе-рации','STRING',16,0,0,0,'OPER_PO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_IN_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 40,
		NAME   		= 'Дата выписки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_IN_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_IN_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 40,'DATE_IN_TOFK','Дата выписки','DATE',0,0,0,0,'DATE_IN_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 41,
		NAME   		= 'Глобальный уни-кальный идентификатор',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 41,'GUID','Глобальный уни-кальный идентификатор','GUID',36,1,0,0,'GUID','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'BDPDST'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'BDPDST',6,2,'Строки платежного поручения по бюджетной классификации',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 6,
			ISONCE = 2,
			NAME   = 'Строки платежного поручения по бюджетной классификации',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код по КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KBK','Код по КБК','STRING',20,1,0,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'TYPE_KBK','Тип КБК','STRING',2,1,0,0,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код цели субсидии',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'ADD_KLASS','Код цели субсидии','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_BO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Номер бюджетного обязательства',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 16,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NUM_BO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_BO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NUM_BO','Номер бюджетного обязательства','STRING',16,1,0,0,'NUM_BO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ОКАТО')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'ОКТ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 = 'TXRN130101' AND CODE = 'RN'
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 'RN','Расшифровка сумм неиспользованных средств','TXRN130101',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_RN','','KOD_UBP','',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Расшифровка сумм неиспользованных средств',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_RN',
		PROC_DOP_PARAM   = '',
		PROG_SAVE   = '',
		DEP_NAME   = 'KOD_UBP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FK',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'сылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','сылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BUDG_LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'BUDG_LEVEL','Уровень бюджета','STRING',1,1,0,1,'BUDG_LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Код УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KOD_UBP','Код УБП','STRING',5,1,1,1,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Наименование УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'NAME_UBP','Наименование УБП','STRING',254,0,1,1,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,1,1,'NAME_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'RN'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'RN',4,2,'Общая инфор-мация',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 2,
			NAME   = 'Общая инфор-мация',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'GUID_FK','Глобальный уникальный идентификатор','STRING',36,0,0,0,'GUID_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_RN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Номер документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_RN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_RN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NOM_RN','Номер документа','STRING',15,0,1,1,'NOM_RN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_RN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Дата документа',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_RN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_RN'
else		
	INSERT INTO EXPORT_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_RN','Дата документа','DATE',0,1,1,1,'DATE_RN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Номер лицевого счета клиента.',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'LS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'LS_PAY','Номер лицевого счета клиента.','STRING',11,1,1,1,'LS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OPER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Вид операции',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'VID_OPER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OPER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'VID_OPER','Вид операции','STRING',1,1,1,1,'VID_OPER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Код ПБС по Сводному ре-естру',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'KOD_UBP','Код ПБС по Сводному ре-естру','STRING',5,1,0,0,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Наименование клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'NAME_UBP','Наименование клиента','STRING',2000,0,1,1,'NAME_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'ИНН',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'INN_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'INN_UBP','ИНН','STRING',10,1,0,1,'INN_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'КПП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KPP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'KPP','КПП','STRING',9,1,0,1,'KPP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		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, 10,'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 		= 11,
		NAME   		= 'Наименование органа ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'NAME_TOFK','Наименование органа ФК','STRING',2000,0,1,1,'NAME_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CARD_NUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Номер банков-ской карты',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'CARD_NUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CARD_NUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'CARD_NUM','Номер банков-ской карты','STRING',20,0,0,1,'CARD_NUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Должность руководителя (уполномоченного им лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DOL_RUK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'DOL_RUK','Должность руководителя (уполномоченного им лица)','STRING',100,0,0,1,'DOL_RUK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'ФИО руководителя (уполномоченного им лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_RUK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'NAME_RUK','ФИО руководителя (уполномоченного им лица)','STRING',50,0,0,1,'NAME_RUK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_BUH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Должность главного бухгалтера (уполномоченного руководителем лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_BUH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_BUH'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'DOL_BUH','Должность главного бухгалтера (уполномоченного руководителем лица)','STRING',100,0,0,0,'DOL_BUH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'ФИО главного бухгалтера (уполномоченного руководителем лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BUH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUH'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 16,'NAME_BUH','ФИО главного бухгалтера (уполномоченного руководителем лица)','STRING',50,0,0,0,'NAME_BUH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_POD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Дата подписания заявки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_POD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_POD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'DATE_POD','Дата подписания заявки','DATE',0,0,0,1,'DATE_POD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA_ITOG')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Сумма денежных средств',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUMMA_ITOG',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA_ITOG'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 18,'SUMMA_ITOG','Сумма денежных средств','NUMBER2',0,1,1,1,'SUMMA_ITOG','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA_R2')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Общая сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUMMA_R2',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA_R2'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 19,'SUMMA_R2','Общая сумма','NUMBER2',0,1,1,1,'SUMMA_R2','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'RNKBK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'RNKBK',5,2,'Расшифровка заявки',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Расшифровка заявки',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'POR_NUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Порядковый номер',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= 8,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'POR_NUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'POR_NUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'POR_NUM','Порядковый номер','NUMBER',8,0,0,1,'POR_NUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Код по БК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KBK','Код по БК','STRING',20,1,1,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'TYPE_KBK','Тип КБК','STRING',2,1,1,0,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код цели субсидии',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'ADD_KLASS','Код цели субсидии','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_V_SR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Вид средств',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_V_SR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_V_SR'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'NAME_V_SR','Вид средств','STRING',1,1,1,1,'NAME_V_SR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Сумма в рублях',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMMA',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMMA'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'SUMMA','Сумма в рублях','NUMBER2',0,1,1,0,'SUMMA','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Примечание',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOTE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'NOTE','Примечание','STRING',2000,0,0,0,'NOTE','',''
GO

GO
update EXPORT_MODELS set DATE_END   = '20121231' WHERE MODEL_VER = '2008.10' AND CODE = 'SPR'
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = '2012.11' AND CODE = 'SPR'
IF @varKSModelLink is null
begin
	INSERT INTO EXPORT_MODELS(CODE, NAME, MODEL_VER, ISONCE, NORM_DOC, FILE_NAME_MASK, FILE_NAME_PROC, PROC_EXP, PROC_DOP_PARAM, DEP_NAME, PROG_SAVE, DATE_END)
	SELECT 'SPR','Справочники','2012.11',0,'','','fb_file_name_spr','BB_EXPORT_SPR','cObjCode','','fb_save_spr()',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Справочники',
		NORM_DOC   = '',
		FILE_NAME_MASK   = '',
		FILE_NAME_PROC   = 'fb_file_name_spr',
		PROC_EXP   = 'BB_EXPORT_SPR',
		PROC_DOP_PARAM   = 'cObjCode',
		PROG_SAVE   = 'fb_save_spr()',
		DEP_NAME   = '',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'KS'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'KS',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,0,0,'NUM_VER','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TYPE'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TYPE',2,0,'Тип справочника',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Тип справочника',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_SPR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код справочника',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 25,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_SPR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_SPR'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_SPR','Код справочника','STRING',25,0,0,0,'KOD_SPR','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'BK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'BK',3,2,'Строки справочника',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 2,
			NAME   = 'Строки справочника',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CODE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код строки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'CODE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CODE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'CODE','Код строки','STRING',20,0,0,1,'CODE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SNAME')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Краткое наименование',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SNAME',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SNAME'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'SNAME','Краткое наименование','STRING',50,0,0,1,'SNAME','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Наименование',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'NAME','Наименование','STRING',2000,0,0,1,'NAME','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_BEGIN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Дата напчала',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_BEGIN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_BEGIN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'DATE_BEGIN','Дата напчала','DATE',NULL,0,0,0,'DATE_BEGIN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_END')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Дата анулирования',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_END',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_END'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'DATE_END','Дата анулирования','DATE',NULL,0,0,0,'DATE_END','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Уровень',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LEVEL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'LEVEL','Уровень','NUMBER',10,0,0,0,'LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDGET')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Наименование бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BUDGET',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDGET'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'BUDGET','Наименование бюджета','STRING',254,0,0,0,'BUDGET','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Порядок',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ORDER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'ORDER','Порядок','NUMBER',10,0,0,0,'ORDER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PARENT')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Вышестоящий код',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PARENT',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PARENT'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'PARENT','Вышестоящий код','STRING',20,0,0,0,'PARENT','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TOTAL'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TOTAL',4,0,'Контроль',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 0,
			NAME   = 'Контроль',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Количество строк',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'SUM','Количество строк','NUMBER',NULL,0,1,1,'SUM','',''
GO

GO
update EXPORT_MODELS set DATE_END   = '20131231' WHERE MODEL_VER = 'TXZR120701' AND CODE = 'ZR'
GO
delete from EXPORT_MODELS WHERE MODEL_VER = 'TXZR140101' AND CODE = 'ZR'
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXZR140101' AND CODE = 'ZR'
IF @varKSModelLink is null
begin
	INSERT INTO EXPORT_MODELS(CODE, NAME, MODEL_VER, ISONCE, NORM_DOC, FILE_NAME_MASK, FILE_NAME_PROC, PROC_EXP, PROC_DOP_PARAM, DEP_NAME, PROG_SAVE, DATE_END)
	SELECT 'ZR','Заявка на кассовый расход','TXZR140101',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_ZKR','cModelVer','KOD_UBP','bb_import_zkr()',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Заявка на кассовый расход',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_ZKR',
		PROC_DOP_PARAM   = 'cModelVer',
		PROG_SAVE   = 'bb_import_zkr()',
		DEP_NAME   = 'KOD_UBP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FK',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'сылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','сылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BUDG_LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'BUDG_LEVEL','Уровень бюджета','STRING',1,1,0,1,'BUDG_LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Код УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KOD_UBP','Код УБП','STRING',5,1,1,1,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Наименование УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'NAME_UBP','Наименование УБП','STRING',254,0,1,1,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,1,1,'NAME_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'ZR'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'ZR',4,2,'Общая информация',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 2,
			NAME   = 'Общая информация',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'GUID_FK','Глобальный уникальный идентификатор','STRING',36,0,0,0,'GUID_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Тип заявки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'TYPE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'TYPE','Тип заявки','STRING',1,1,1,1,'TYPE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Номер заявки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_ZR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZR'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'NOM_ZR','Номер заявки','STRING',15,0,1,1,'NOM_ZR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Дата заявки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_ZR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZR'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'DATE_ZR','Дата заявки','DATE',0,1,1,1,'DATE_ZR','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Код клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_UBP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'KOD_UBP_PAY','Код клиента','STRING',5,0,0,0,'KOD_UBP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Наименование клиентаклиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'NAME_UBP_PAY','Наименование клиентаклиента','STRING',2000,0,1,1,'NAME_UBP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Номер лицевого счета клиента.',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'LS_UBP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'LS_UBP_PAY','Номер лицевого счета клиента.','STRING',11,1,1,1,'LS_UBP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'ИНН клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INN_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'INN_UBP','ИНН клиента','STRING',10,1,0,0,'INN_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'КПП клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KPP_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'KPP_UBP','КПП клиента','STRING',9,1,0,0,'KPP_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA_GRS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Глава по БК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GLAVA_GRS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA_GRS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'GLAVA_GRS','Глава по БК','STRING',3,1,0,0,'GLAVA_GRS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_GRS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Наименование ГРБС (ГАИФДБ)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_UBP_GRS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_GRS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'NAME_UBP_GRS','Наименование ГРБС (ГАИФДБ)','STRING',2000,0,1,0,'NAME_UBP_GRS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Наименование бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BUD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'NAME_BUD','Наименование бюджета','STRING',512,0,0,0,'NAME_BUD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Наименование финансового органа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'NAME_FO','Наименование финансового органа','STRING',2000,0,1,0,'NAME_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKPO_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Код по ОКПО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 8,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKPO_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKPO_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'OKPO_FO','Код по ОКПО','STRING',8,1,0,0,'OKPO_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Код органа ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'KOD_TOFK','Код органа ФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Наименование органа ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 16,'NAME_TOFK','Наименование органа ФК','STRING',2000,0,1,1,'NAME_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Предельная дата исполнения',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'DATE_ISP','Предельная дата исполнения','DATE',0,1,1,0,'DATE_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_SV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Идентификатор документа "Све-дения о принятом бюджетном обя-зательстве", предоставленного в ОрФК',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID_SV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_SV'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 18,'GUID_SV','Идентификатор документа "Све-дения о принятом бюджетном обя-зательстве", предоставленного в ОрФК','GUID',0,0,0,0,'GUID_SV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_BO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Номер обязательства',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 16,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_BO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_BO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 19,'NOM_BO','Номер обязательства','STRING',16,1,0,0,'NOM_BO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'Код приоритета исполнения',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 20,'KOD_ISP','Код приоритета исполнения','STRING',1,1,0,0,'KOD_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PR_ISP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Приоритет исполнения',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PR_ISP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PR_ISP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 21,'PR_ISP','Приоритет исполнения','STRING',250,0,0,0,'PR_ISP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FAIP_CODE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Код объекта по ФАИП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 14,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'FAIP_CODE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FAIP_CODE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 22,'FAIP_CODE','Код объекта по ФАИП','STRING',14,1,0,0,'FAIP_CODE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_V')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Сумма документа в валюте выплаты',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_V',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_V'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 23,'SUM_V','Сумма документа в валюте выплаты','NUMBER2',0,1,0,1,'SUM_V','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_V')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Код валюты по ОКВ',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_V',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_V'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 24,'KOD_V','Код валюты по ОКВ','STRING',3,1,0,1,'KOD_V','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Сумма документа',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 25,'SUM_DOC','Сумма документа','NUMBER2',0,1,1,0,'SUM_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_AP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'Признак авансового платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'TYPE_AP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_AP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 26,'TYPE_AP','Признак авансового платежа','STRING',1,1,0,1,'TYPE_AP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'Очередность платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'ORDER_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 27,'ORDER_PL','Очередность платежа','STRING',1,1,1,1,'ORDER_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Вид платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'VID_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 28,'VID_PL','Вид платежа','STRING',1,1,1,1,'VID_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 29,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 29,'PURPOSE','Назначение платежа','STRING',210,0,1,1,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 30,
		NAME   		= 'Наименование / ФИО контрагента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 30,'NAME_RCP','Наименование / ФИО контрагента','STRING',160,0,1,1,'NAME_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 31,
		NAME   		= 'ИНН контрагента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 12,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'INN_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INN_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 31,'INN_RCP','ИНН контрагента','STRING',12,0,1,1,'INN_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'КПП контрагента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KPP_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KPP_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 32,'KPP_RCP','КПП контрагента','STRING',9,0,1,1,'KPP_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 33,
		NAME   		= 'Лицевой счет контрагента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LS_UBP_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_UBP_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 33,'LS_UBP_RCP','Лицевой счет контрагента','STRING',11,1,0,0,'LS_UBP_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 34,
		NAME   		= 'Банковский счет контрагента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 34,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 34,'BS_RCP','Банковский счет контрагента','STRING',34,0,0,0,'BS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 35,
		NAME   		= 'Наименование банка контрагента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 160,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 35,'NAME_BIC_RCP','Наименование банка контрагента','STRING',160,0,0,1,'NAME_BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 36,
		NAME   		= 'БИК банка контрагента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 9,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 36,'BIC_RCP','БИК банка контрагента','STRING',9,1,0,0,'BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KS_BIC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 37,
		NAME   		= 'Корсчет банка контрагента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 34,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KS_BIC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KS_BIC_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 37,'KS_BIC_RCP','Корсчет банка контрагента','STRING',34,0,0,0,'KS_BIC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 38,
		NAME   		= 'Статус налогоплательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PAYSTATUS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYSTATUS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 38,'PAYSTATUS','Статус налогоплательщика','STRING',2,1,0,0,'PAYSTATUS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KDOH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 39,
		NAME   		= 'Код бюджетной классификации',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KDOH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KDOH'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 39,'KDOH','Код бюджетной классификации','STRING',20,1,0,0,'KDOH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 40,
		NAME   		= 'Код ОКАТО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKATO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKATO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 40,'OKATO','Код ОКАТО','STRING',11,0,0,0,'OKATO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OSN_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 41,
		NAME   		= 'Показатель основания платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OSN_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OSN_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 41,'OSN_PL','Показатель основания платежа','STRING',2,0,0,0,'OSN_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAL_PER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 42,
		NAME   		= 'Показатель налогового периода',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAL_PER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAL_PER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 42,'NAL_PER','Показатель налогового периода','STRING',10,0,0,0,'NAL_PER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 43,
		NAME   		= 'Показатель номера документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_DOK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 43,'NOM_DOK','Показатель номера документа','STRING',15,0,0,0,'NOM_DOK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 44,
		NAME   		= 'Показатель даты документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_DOK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 44,'DATE_DOK','Показатель даты документа','STRING',10,0,0,0,'DATE_DOK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_PL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 45,
		NAME   		= 'Тип платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_PL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_PL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 45,'TYPE_PL','Тип платежа','STRING',2,0,0,0,'TYPE_PL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 46,
		NAME   		= 'Должность руководителя (уполномоченного им лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_RUK_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 46,'DOL_RUK_UBP','Должность руководителя (уполномоченного им лица)','STRING',100,0,0,0,'DOL_RUK_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 47,
		NAME   		= 'ФИО руководителя (уполномоченного им лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_RUK_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 47,'NAME_RUK_UBP','ФИО руководителя (уполномоченного им лица)','STRING',50,0,0,1,'NAME_RUK_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_BUH_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 48,
		NAME   		= 'Должность главного бухгалтера (уполномоченного руководителем лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_BUH_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_BUH_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 48,'DOL_BUH_UBP','Должность главного бухгалтера (уполномоченного руководителем лица)','STRING',100,0,0,0,'DOL_BUH_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUH_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 49,
		NAME   		= 'ФИО главного бухгалтера (уполномоченного руководителем лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BUH_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUH_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 49,'NAME_BUH_UBP','ФИО главного бухгалтера (уполномоченного руководителем лица)','STRING',50,0,0,0,'NAME_BUH_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_POD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 50,
		NAME   		= 'Дата подписания заявки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_POD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_POD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 50,'DATE_POD_UBP','Дата подписания заявки','DATE',0,0,0,1,'DATE_POD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZR_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 51,
		NAME   		= 'Отметка ОрФК о постановке на учет / Номер заявки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_ZR_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZR_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 51,'NOM_ZR_FK','Отметка ОрФК о постановке на учет / Номер заявки','STRING',15,0,0,0,'NOM_ZR_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 52,
		NAME   		= 'Отметка ОрФК о постановке на учет / Дата постановки на учет',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 52,'DATE_FK','Отметка ОрФК о постановке на учет / Дата постановки на учет','DATE',0,1,0,0,'DATE_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 53,
		NAME   		= 'Отметка ОрФК о постановке на учет / Должность ответственного исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_ISP_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 53,'DOL_ISP_FK','Отметка ОрФК о постановке на учет / Должность ответственного исполнителя','STRING',100,0,0,0,'DOL_ISP_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 54,
		NAME   		= 'Отметка ОрФК о постановке на учет / ФИО ответственного исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_ISP_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 54,'NAME_ISP_FK','Отметка ОрФК о постановке на учет / ФИО ответственного исполнителя','STRING',50,0,0,0,'NAME_ISP_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 55,
		NAME   		= 'Отметка ОрФК о постановке на учет / Телефон ответственного исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TEL_ISP_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 55,'TEL_ISP_FK','Отметка ОрФК о постановке на учет / Телефон ответственного исполнителя','STRING',50,0,0,0,'TEL_ISP_FK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'ZROSN'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'ZROSN',5,2,'Реквизиты документов-оснований',0
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Реквизиты документов-оснований',
			OBLIGATORY = 0
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OSN_PLAT')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Признак основания платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OSN_PLAT',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OSN_PLAT'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'OSN_PLAT','Признак основания платежа','STRING',1,0,0,0,'OSN_PLAT','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OSN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Вид документа-основания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'VID_OSN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_OSN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'VID_OSN','Вид документа-основания','STRING',50,0,0,1,'VID_OSN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_OSN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Номер документа-основания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 45,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_OSN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_OSN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'NOM_OSN','Номер документа-основания','STRING',45,0,0,1,'NOM_OSN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_OSN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Дата документа-основания',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_OSN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_OSN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'DATE_OSN','Дата документа-основания','DATE',NULL,0,0,0,'DATE_OSN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OSN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Предмет документа-основания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OSN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OSN'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'OSN','Предмет документа-основания','STRING',512,0,0,0,'OSN','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'ZRST'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'ZRST',6,2,'Строки заявки на кассовый расход по бюджетной классификации',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 6,
			ISONCE = 2,
			NAME   = 'Строки заявки на кассовый расход по бюджетной классификации',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_IST_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Источник средств',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_IST_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_IST_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_IST_KBK','Источник средств','STRING',1,1,0,1,'KOD_IST_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Тип КБК плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'TYPE_KBK_PAY','Тип КБК плательщика','STRING',2,1,1,0,'TYPE_KBK_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код по БК плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'KBK_PAY','Код по БК плательщика','STRING',20,1,1,0,'KBK_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Тип КБК получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'TYPE_KBK_RCP','Тип КБК получателя','STRING',2,1,0,0,'TYPE_KBK_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Код по БК получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'KBK_RCP','Код по БК получателя','STRING',20,1,0,0,'KBK_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Код цели субсидии / субвенции плательщика',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'ADD_KLASS_PAY','Код цели субсидии / субвенции плательщика','STRING',20,0,0,0,'ADD_KLASS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Код цели субсидии / субвенции получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS_RCP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'ADD_KLASS_RCP','Код цели субсидии / субвенции получателя','STRING',20,0,0,0,'ADD_KLASS_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_V_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Сумма в валюте заявки',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUM_V_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_V_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'SUM_V_KBK','Сумма в валюте заявки','NUMBER2',0,1,0,1,'SUM_V_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_R_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Сумма в рублях',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_R_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_R_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'SUM_R_KBK','Сумма в рублях','NUMBER2',0,1,1,0,'SUM_R_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PURPOSE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'PURPOSE_KBK','Назначение платежа','STRING',210,0,0,0,'PURPOSE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Примечание',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOTE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'NOTE_KBK','Примечание','STRING',254,0,0,0,'NOTE_KBK','',''
GO

GO
update EXPORT_MODELS set DATE_END   = '20131231' WHERE (MODEL_VER = 'TXZR100701' OR MODEL_VER = 'TXZR120101' OR MODEL_VER = 'TXZR130701') AND CODE = 'ZS'
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = 'TXZS140101' AND CODE = 'ZS'
IF @varKSModelLink is null
begin
	INSERT INTO EXPORT_MODELS(CODE, NAME, MODEL_VER, ISONCE, NORM_DOC, FILE_NAME_MASK, FILE_NAME_PROC, PROC_EXP, PROC_DOP_PARAM, DEP_NAME, PROG_SAVE, DATE_END)
	SELECT 'ZS','Заявка на получение наличных денег','TXZS140101',0,'','XXXXXDNN.TTM','fb_file_name_doc','BB_EXPORT_ZS','','KOD_UBP','',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Заявка на получение наличных денег',
		NORM_DOC   = '',
		FILE_NAME_MASK   = 'XXXXXDNN.TTM',
		FILE_NAME_PROC   = 'fb_file_name_doc',
		PROC_EXP   = 'BB_EXPORT_ZS',
		PROC_DOP_PARAM   = '',
		PROG_SAVE   = '',
		DEP_NAME   = 'KOD_UBP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FK',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'сылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','сылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Уровень бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'BUDG_LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDG_LEVEL'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'BUDG_LEVEL','Уровень бюджета','STRING',1,1,0,1,'BUDG_LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Код УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KOD_UBP','Код УБП','STRING',5,1,1,1,'KOD_UBP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Наименование УБП',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'NAME_UBP','Наименование УБП','STRING',254,0,1,1,'NAME_UBP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TO',3,0,'Почтовая информация о получателе файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 0,
			NAME   = 'Почтовая информация о получателе файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_TOFK','Код ОрФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NAME_TOFK','Наименование ОрФК','STRING',2000,0,1,1,'NAME_TOFK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'ZS'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'ZS',4,2,'Заявка',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 2,
			NAME   = 'Заявка',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Глобальный уникальный идентификатор',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'GUID_FK','Глобальный уникальный идентификатор','STRING',36,0,0,0,'GUID_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZVK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Номер заявки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_ZVK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZVK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'NOM_ZVK','Номер заявки','STRING',15,0,1,1,'NOM_ZVK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZVK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Дата заявки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_ZVK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_ZVK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'DATE_ZVK','Дата заявки','DATE',0,1,1,1,'DATE_ZVK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Наименование бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BUD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NAME_BUD','Наименование бюджета','STRING',512,0,1,0,'NAME_BUD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Наименование финансового органа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_UBP_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'NAME_UBP_FO','Наименование финансового органа','STRING',2000,0,1,0,'NAME_UBP_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OKPO_FO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Код по ОКПО',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 8,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'OKPO_FO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OKPO_FO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'OKPO_FO','Код по ОКПО','STRING',8,1,0,0,'OKPO_FO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_GRBS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Наименование ГРБС (ГАИФДБ)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_GRBS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_GRBS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'NAME_GRBS','Наименование ГРБС (ГАИФДБ)','STRING',2000,0,1,0,'NAME_GRBS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA_GRBS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Глава по БК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GLAVA_GRBS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GLAVA_GRBS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 8,'GLAVA_GRBS','Глава по БК','STRING',3,1,1,0,'GLAVA_GRBS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Наименование клиентаклиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_UBP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_UBP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'NAME_UBP_PAY','Наименование клиентаклиента','STRING',2000,0,1,1,'NAME_UBP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Код клиента',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_UBP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_UBP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 10,'KOD_UBP_PAY','Код клиента','STRING',5,1,0,0,'KOD_UBP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Номер лицевого счета клиента.',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 11,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'LS_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LS_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 11,'LS_PAY','Номер лицевого счета клиента.','STRING',11,1,1,1,'LS_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Наименование органа ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 12,'NAME_TOFK','Наименование органа ФК','STRING',2000,0,1,1,'NAME_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Код органа ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 4,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_TOFK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_TOFK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 13,'KOD_TOFK','Код органа ФК','STRING',4,1,1,1,'KOD_TOFK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_LIM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Предельная дата исполнения',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_LIM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_LIM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'DATE_LIM','Предельная дата исполнения','DATE',0,1,1,0,'DATE_LIM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_BO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Номер обязательства',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 16,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_BO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_BO'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 15,'NOM_BO','Номер обязательства','STRING',16,1,0,0,'NOM_BO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Должность руководителя (уполномоченного им лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_RUK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_RUK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 16,'DOL_RUK','Должность руководителя (уполномоченного им лица)','STRING',100,0,0,0,'DOL_RUK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'ФИО руководителя (уполномоченного им лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_RUK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RUK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 17,'NAME_RUK','ФИО руководителя (уполномоченного им лица)','STRING',50,0,0,1,'NAME_RUK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_BUH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Должность главного бухгалтера (уполномоченного руководителем лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_BUH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_BUH'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 18,'DOL_BUH','Должность главного бухгалтера (уполномоченного руководителем лица)','STRING',100,0,0,0,'DOL_BUH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUH')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'ФИО главного бухгалтера (уполномоченного руководителем лица)',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BUH',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUH'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 19,'NAME_BUH','ФИО главного бухгалтера (уполномоченного руководителем лица)','STRING',50,0,0,0,'NAME_BUH','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_POD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'Дата подписания заявки',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_POD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_POD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 20,'DATE_POD','Дата подписания заявки','DATE',0,0,0,1,'DATE_POD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP_DOV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Должность довененного лица',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DOL_ISP_DOV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP_DOV'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 21,'DOL_ISP_DOV','Должность довененного лица','STRING',100,0,0,1,'DOL_ISP_DOV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP_DOV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'ФИО довененного лица',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_ISP_DOV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP_DOV'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 22,'NAME_ISP_DOV','ФИО довененного лица','STRING',50,0,0,1,'NAME_ISP_DOV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_DOV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Наименование документа, удостоверяющего личность',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 255,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_DOV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_DOV'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 23,'NAME_DOV','Наименование документа, удостоверяющего личность','STRING',255,0,0,1,'NAME_DOV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Номер документа, удостоверяющего личность',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 45,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 24,'NOM_DOC','Номер документа, удостоверяющего личность','STRING',45,0,0,0,'NOM_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ORG_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Кем выдан документ, удостоверяющий личность',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ORG_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ORG_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 25,'ORG_DOC','Кем выдан документ, удостоверяющий личность','STRING',2000,0,0,0,'ORG_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'Дата документа, удостоверяющего личность',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 26,'DATE_DOC','Дата документа, удостоверяющего личность','DATE',0,1,0,0,'DATE_DOC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_ITOG')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'Сумма документа',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_ITOG',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_ITOG'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 27,'SUM_ITOG','Сумма документа','NUMBER2',0,1,1,0,'SUM_ITOG','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZS_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Номер заявки, присвоеный ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOM_ZS_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_ZS_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 28,'NOM_ZS_FK','Номер заявки, присвоеный ОрФК','STRING',15,0,0,0,'NOM_ZS_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 29,
		NAME   		= 'Дата регистрации заявки в ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 29,'DATE_FK','Дата регистрации заявки в ОрФК','STRING',10,0,0,0,'DATE_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 30,
		NAME   		= 'Должность ответственого исполнителя в ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOL_ISP_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOL_ISP_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 30,'DOL_ISP_FK','Должность ответственого исполнителя в ФК','STRING',100,0,0,0,'DOL_ISP_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 31,
		NAME   		= 'ФИО  ответственого исполнителя в ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_ISP_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_ISP_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 31,'NAME_ISP_FK','ФИО  ответственого исполнителя в ФК','STRING',50,0,0,0,'NAME_ISP_FK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP_FK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'Телефон  ответственого исполнителя в ФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TEL_ISP_FK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TEL_ISP_FK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 32,'TEL_ISP_FK','Телефон  ответственого исполнителя в ФК','STRING',10,0,0,0,'TEL_ISP_FK','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'ZSCH1'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'ZSCH1',5,2,'Реквизиты чека',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Реквизиты чека',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMR_ZVK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'сумма',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SUMR_ZVK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMR_ZVK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'SUMR_ZVK','сумма','NUMBER2',0,0,1,1,'SUMR_ZVK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CHEСK_NOM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Номер чека',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'CHECK_NOM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CHEСK_NOM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'CHEСK_NOM','Номер чека','STRING',15,0,0,1,'CHECK_NOM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CHECK_SER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Серия чека',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 30,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'CHECK_SER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CHECK_SER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'CHECK_SER','Серия чека','STRING',30,0,0,1,'CHECK_SER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_CHEСK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Дата оформления чека',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_CHECK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_CHEСK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'DATE_CHEСK','Дата оформления чека','DATE',0,1,0,1,'DATE_CHECK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_CHEСK_LIM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Срок действия чека',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_CHECK_LIM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_CHEСK_LIM'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'DATE_CHEСK_LIM','Срок действия чека','DATE',0,1,0,1,'DATE_CHECK_LIM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CHECK_KAS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Символ кассового плана',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'CHECK_KAS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CHECK_KAS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'CHECK_KAS','Символ кассового плана','STRING',2,1,1,1,'CHECK_KAS','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'ZSCH2'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'ZSCH2',6,2,'Расшифровка заявки',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 6,
			ISONCE = 2,
			NAME   = 'Расшифровка заявки',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_IST')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Источник средств',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_IST',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_IST'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'KOD_IST','Источник средств','STRING',1,1,0,1,'KOD_IST','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Код по БК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KBK','Код по БК','STRING',20,1,1,0,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'TYPE_KBK','Тип КБК','STRING',2,1,1,0,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Код цели субсидии',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ADD_KLASS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'ADD_KLASS','Код цели субсидии','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMR_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Сумма в рублях',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUMR_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUMR_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'SUMR_KBK','Сумма в рублях','NUMBER2',0,1,1,0,'SUMR_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Назначение платежа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 210,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 6,'PURPOSE','Назначение платежа','STRING',210,0,0,0,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Примечание',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NOTE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOTE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'NOTE','Примечание','STRING',254,0,0,0,'NOTE','',''
GO

GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_P_CREDIT_PLAT_DAY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_P_CREDIT_PLAT_DAY', 'Дней до платежа', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_P_CREDIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_P_CREDIT_PLAT_DAY', NAME = 'Дней до платежа', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_P_CREDIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_P_CREDIT_PLAT_DAY'
GO
EXEC X_SET_PROP 'BB_P_CREDIT_PLAT_DAY', 'TITLE', 'Дней до платежа'
GO
EXEC X_SET_PROP 'BB_P_CREDIT_PLAT_DAY', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_P_CREDIT_PLAT_DAY', 'CONTROLSOURCE', 'm.cAlias + ".PLAT_DAY"'
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 = 'KASSA_DOC')

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

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

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'BB_reestr_den_sr', 'Реестр перечисления денежных средств', @ORD, NULL, 1, @LINK_SELF, 'DOCUMENT', @OBJECT, @LINK_VAR, 3
GO


GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U', 'Уведомление об уточнении вида и принадлежности платежа', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOCUMENTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U', NAME = 'Уведомление об уточнении вида и принадлежности платежа', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOCUMENTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='BB_UVED_U'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_SOURCE_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_SOURCE_NAME', 'Наименование плательщика', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_SOURCE_NAME', NAME = 'Наименование плательщика', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_SOURCE_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC', 'Таблица документов', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC', NAME = 'Таблица документов', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_TABLE', 'Изменить на реквизиты', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_TABLE', NAME = 'Изменить на реквизиты', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_TABLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_NUM_REC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_NUM_REC', 'Номер', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_NUM_REC', NAME = 'Номер', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_NUM_REC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_DOC_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_DOC_NAME', 'Наименование документа', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_DOC_NAME', NAME = 'Наименование документа', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_DOC_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_DOC_NUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_DOC_NUM', 'Номер документа', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_DOC_NUM', NAME = 'Номер документа', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_DOC_NUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_DOC_DATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_DOC_DATE', 'Дата документа', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_DOC_DATE', NAME = 'Дата документа', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_DOC_DATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_DEP_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_DEP_CODE', 'Код получателя', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_DEP_CODE', NAME = 'Код получателя', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_DEP_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_DEP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_DEP_NAME', 'Наименование получателя', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_DEP_NAME', NAME = 'Наименование получателя', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_DEP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_DEP_INN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_DEP_INN', 'ИНН', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_DEP_INN', NAME = 'ИНН', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_DEP_INN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_DEP_KPP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_DEP_KPP', 'КПП', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_DEP_KPP', NAME = 'КПП', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_DEP_KPP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_DEP_OKATO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_DEP_OKATO', 'OKTМO', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_DEP_OKATO', NAME = 'OKTМO', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_DEP_OKATO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_KBK_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_KBK_CODE', 'КБК', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_KBK_CODE', NAME = 'КБК', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_KBK_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_SGU_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_SGU_CODE', 'ЭКР', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_SGU_CODE', NAME = 'ЭКР', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_SGU_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_DCL_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_DCL_CODE', 'Код цели', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_DCL_CODE', NAME = 'Код цели', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_DCL_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_SUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_SUMMA', 'Сумма', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_SUMMA', NAME = 'Сумма', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_SUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_TARGET')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_TARGET', 'Назначение платежа', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_TARGET', NAME = 'Назначение платежа', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_TARGET'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_TITLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_TITLE', 'Примечание', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_TITLE', NAME = 'Примечание', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_TITLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE _CHECKED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_TABLE _CHECKED', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_TABLE _CHECKED', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_TABLE _CHECKED'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE_NUM_REC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_TABLE_NUM_REC', 'Номер', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_TABLE_NUM_REC', NAME = 'Номер', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_TABLE_NUM_REC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE_DEP_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_TABLE_DEP_CODE', 'Код получателя', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_TABLE_DEP_CODE', NAME = 'Код получателя', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_TABLE_DEP_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE_DEP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_TABLE_DEP_NAME', 'Наименование получателя', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_TABLE_DEP_NAME', NAME = 'Наименование получателя', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_TABLE_DEP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE_DEP_INN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_TABLE_DEP_INN', 'ИНН', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_TABLE_DEP_INN', NAME = 'ИНН', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_TABLE_DEP_INN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE_DEP_KPP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_TABLE_DEP_KPP', 'КПП', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_TABLE_DEP_KPP', NAME = 'КПП', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_TABLE_DEP_KPP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_DOC_DEP_OKATO_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_DOC_DEP_OKATO_1', 'OKTМO', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_DOC_DEP_OKATO_1', NAME = 'OKTМO', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_DOC_DEP_OKATO_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE_KBK_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_TABLE_KBK_CODE', 'КБК', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_TABLE_KBK_CODE', NAME = 'КБК', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_TABLE_KBK_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE_SGU_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_TABLE_SGU_CODE', 'ЭКР', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_TABLE_SGU_CODE', NAME = 'ЭКР', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_TABLE_SGU_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE_DCL_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_TABLE_DCL_CODE', 'Код цели', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_TABLE_DCL_CODE', NAME = 'Код цели', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_TABLE_DCL_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE_SUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_TABLE_SUMMA', 'Сумма', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_TABLE_SUMMA', NAME = 'Сумма', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_TABLE_SUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE_TARGET')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_UVED_U_TABLE_TARGET', 'Назначение платежа', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_UVED_U_TABLE_TARGET', NAME = 'Назначение платежа', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_UVED_U_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_UVED_U_TABLE_TARGET'
GO
EXEC X_SET_PROP 'BB_UVED_U', 'TITLE', 'Уведомление об уточнении вида и принадлежности платежа'
GO
EXEC X_SET_PROP 'BB_UVED_U', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "BB_UVED_U", "BV_DELETE_DOCUMENTS", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'BB_UVED_U', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_BB_UVED_U'', m.cAlias,"NUMBER, SQLNULL(DATE), SQLNULL(DATE_PROV), SUMMA, COMMENT, SQLNULL (DEP_LINK), SQLNULL (ACC_LINK)","BB_UVED_U")
'
GO
EXEC X_SET_PROP 'BB_UVED_U', 'PRINT_OBJECT_METHOD', 'bb_print_uved_utochn(oForm.Alias,oForm.Pages.Page1.bChildSpisok1.bGrid1.RecordSource,oForm.Pages.Page1.bChildSpisok2.bGrid1.RecordSource)'
GO
EXEC X_SET_PROP 'BB_UVED_U', 'EDIT_OBJECT_METHOD', 'xdoc_brow(''BB_UVED_UTOCHN'')'
GO
EXEC X_SET_PROP 'BB_UVED_U', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_LIST_ZB(m.Obj_code)'
GO
EXEC X_SET_PROP 'BB_UVED_U', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST(m.Obj_code)'
GO
EXEC X_SET_PROP 'BB_UVED_U', 'SNAME', 'Уведомление об уточнении'
GO
EXEC X_SET_PROP 'BB_UVED_U', 'QUERY_REPMAKER', 'KirRepMakerMultiSheet.xls'
GO
EXEC X_SET_PROP 'BB_UVED_U', 'QUERY_REPORT', 'BB_UVED_U.XLT'
GO
EXEC X_SET_PROP 'BB_UVED_U', 'HELP_TOPIC', '48'
GO
EXEC X_SET_PROP 'BB_UVED_U', 'QUERY_ADD_MODULE', 'bb_print_uved_utochn.bas'
GO
EXEC X_SET_PROP 'BB_UVED_U', 'EXCH_MODEL_CODE', 'UF'
GO
EXEC X_SET_PROP 'BB_UVED_U', 'EXCHANGE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_SOURCE_NAME', 'TITLE', 'Плательщик'
GO
EXEC X_SET_PROP 'BB_UVED_U_SOURCE_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_SOURCE_NAME', 'CONTROLSOURCE', 'm.cAlias+".DEP_NAME"'
GO
EXEC X_SET_PROP 'BB_UVED_U_SOURCE_NAME', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'BB_UVED_U_SOURCE_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'BB_UVED_U_SOURCE_NAME', 'REFERENCE_TO_DICT', 'COLUMN_DOC_PAY_SOURCE_LINK'
GO
EXEC X_SET_PROP 'BB_UVED_U_SOURCE_NAME', 'TYPE_FIELD_DICT', 'varchar(254)'
GO
EXEC X_SET_PROP 'BB_UVED_U_SOURCE_NAME', 'SHORT_CODE_OBJ', 'DEP_NAME'
GO
EXEC X_SET_PROP 'BB_UVED_U_SOURCE_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DEP_NAME"'
GO
EXEC X_SET_PROP 'BB_UVED_U_SOURCE_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC', 'SAVE_OBJECT_METHOD', 'x_save(''BB_SAVE_UVED_U_DOC'', m.cAlias, ''LINK_UP, SQLNULL(DOC_LINK), DEP_LINK, KBK_LINK, SGU_LINK, SQLNULL(DCL_LINK), SUMMA,NUM_REC,TARGET,TITLE'', ''BB_UVED_U_DOC'')'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC', 'SELECT_RECORDS_METHOD', 'SQL.EXEC(''SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * FROM dbo.BB_UVED_U_DOC WHERE LINK_UP = '' + STR(m.nLink), m.cAlias) > 0'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC', 'SERVER_TABLE_NAME', 'UVED_U_DOC'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE', 'SAVE_OBJECT_METHOD', 'x_save(''BB_SAVE_UVED_U_TABLE'', m.cAlias, ''LINK_UP, LINK_DOC, NUM_REC,SQLNULL(DEP_LINK),SQLNULL(KBK_LINK), SQLNULL(SGU_LINK), SQLNULL(DCL_LINK), SUMMA,TARGET'', ''BB_UVED_U_TABLE'')'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE', 'SELECT_RECORDS_METHOD', 'SQL.EXEC(''SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * FROM dbo.BB_UVED_U_TABLE WHERE LINK_DOC = '' + STR(m.nLink), m.cAlias) > 0'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE', 'SERVER_TABLE_NAME', 'UVED_U_TABLE'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_CHECKED', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_CHECKED', 'CONTROLSOURCE', 'm.cAlias+''.CHECKED'''
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_NUM_REC', 'TITLE', 'Номер'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_NUM_REC', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_NUM_REC', 'CONTROLSOURCE', 'm.cAlias + ".NUM_REC"'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_NUM_REC', 'SHORT_CODE_OBJ', 'RECORD_NO'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_NUM_REC', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NUM_REC"'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_NUM_REC', 'INPUT_MASK', '999999999'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DOC_NAME', 'TITLE', 'Документ'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DOC_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DOC_NAME', 'CONTROLSOURCE', 'm.cAlias+''.DOC_TYPE'''
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DOC_NUM', 'TITLE', '№ документа'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DOC_NUM', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DOC_NUM', 'CONTROLSOURCE', 'm.cAlias+''.DOC_NUM'''
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DOC_DATE', 'TITLE', 'Дата документа'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DOC_DATE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DOC_DATE', 'CONTROLSOURCE', 'm.cAlias+".DOC_DATE"'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_CODE', 'TITLE', 'Код получателя'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_CODE', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oObj.Parent.Parent.RECORDSOURCE, "LINK,NAME,INN,KPP,CODE,OKTMO", "DEP_LINK,DEP_NAME,DEP_INN,DEP_KPP,DEP_CODE,DEP_OKATO", "", "", "", .T., 1, oForm, oObj,"",.T.,"DEPARTMENT_GROUPS")'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_CODE', 'CONTROLSOURCE', 'm.cAlias+''.DEP_CODE'''
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_NAME', 'TITLE', 'Получатель'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_NAME', 'CONTROLSOURCE', 'm.cAlias+".DEP_NAME"'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_INN', 'TITLE', 'ИНН'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_INN', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_INN', 'CONTROLSOURCE', 'm.cAlias+".DEP_INN"'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_KPP', 'TITLE', 'КПП'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_KPP', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_KPP', 'CONTROLSOURCE', 'm.cAlias+".DEP_KPP"'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_OKATO', 'TITLE', 'OKTМO'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_OKATO', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_OKATO', 'CONTROLSOURCE', 'm.cAlias+".DEP_OKATO"'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_KBK_CODE', 'TITLE', 'КБК'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_KBK_CODE', 'EDIT_OBJECT_METHOD', 'n_vibor_01 ("BI_DICTION_KBK", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE", "KBK_LINK, KBK_CODE", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_KBK_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_KBK_CODE', 'CONTROLSOURCE', 'm.cAlias+''.KBK_CODE'''
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_KBK_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_SGU_CODE', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_SGU_CODE', 'EDIT_OBJECT_METHOD', 'n_vibor_01 ("DICTIONARY_ITEM", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE", "SGU_LINK, SGU_CODE", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_SGU_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_SGU_CODE', 'CONTROLSOURCE', 'm.cAlias+".SGU_CODE"'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_SGU_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DCL_CODE', 'TITLE', 'Код цели'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DCL_CODE', 'EDIT_OBJECT_METHOD', 'n_vibor_01 ("BD_DOP_CLASSIF", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE", "DCL_LINK, DCL_CODE", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DCL_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DCL_CODE', 'CONTROLSOURCE', 'm.cAlias+".DCL_Code"'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_SUMMA', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_SUMMA', 'EDIT_OBJECT_METHOD', 'bb_calc_summ_doc(oForm.Alias,oObj.Parent.parent.RecordSource)'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_SUMMA', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_SUMMA', 'CONTROLSOURCE', 'm.cAlias+''.SUMMA'''
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_SUMMA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_SUMMA', 'SHORT_CODE_OBJ', 'SUMMA'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_SUMMA', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.SUMMA'''
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_SUMMA', 'INPUT_MASK', '99999999999.99'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_TARGET', 'TITLE', 'Назначение платежа'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_TARGET', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_TARGET', 'CONTROLSOURCE', 'm.cAlias+".TARGET"'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_TARGET', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_TITLE', 'TITLE', 'Примечание'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_TITLE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_TITLE', 'CONTROLSOURCE', 'm.cAlias+".TITLE"'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_TITLE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE _CHECKED', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE _CHECKED', 'CONTROLSOURCE', 'm.cAlias+''.CHECKED'''
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_NUM_REC', 'TITLE', 'Номер'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_NUM_REC', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_NUM_REC', 'CONTROLSOURCE', 'm.cAlias + ".NUM_REC"'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_NUM_REC', 'SHORT_CODE_OBJ', 'NUM_REC'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_NUM_REC', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NUM_REC"'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_NUM_REC', 'INPUT_MASK', '999999999'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DEP_CODE', 'TITLE', 'Код получателя'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DEP_CODE', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oObj.Parent.Parent.RECORDSOURCE, "LINK,NAME,INN,KPP,CODE,OKTMO", "DEP_LINK,DEP_NAME,DEP_INN,DEP_KPP,DEP_CODE,DEP_OKATO", "", "", "", .T., 1, oForm, oObj,"",.T.,"DEPARTMENT_GROUPS")'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DEP_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DEP_CODE', 'CONTROLSOURCE', 'm.cAlias+''.DEP_CODE'''
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DEP_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DEP_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.DEP_CODE'''
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DEP_NAME', 'TITLE', 'Получатель'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DEP_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DEP_NAME', 'CONTROLSOURCE', 'm.cAlias+".DEP_NAME"'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DEP_INN', 'TITLE', 'ИНН'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DEP_INN', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DEP_INN', 'CONTROLSOURCE', 'm.cAlias+".DEP_INN"'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DEP_KPP', 'TITLE', 'КПП'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DEP_KPP', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DEP_KPP', 'CONTROLSOURCE', 'm.cAlias+".DEP_KPP"'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_OKATO_1', 'TITLE', 'OKTМO'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_OKATO_1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_DOC_DEP_OKATO_1', 'CONTROLSOURCE', 'm.cAlias+".DEP_OKATO"'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_KBK_CODE', 'TITLE', 'КБК'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_KBK_CODE', 'EDIT_OBJECT_METHOD', 'n_vibor_01 ("BI_DICTION_KBK", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE", "KBK_LINK, KBK_CODE", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_KBK_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_KBK_CODE', 'CONTROLSOURCE', 'm.cAlias+''.KBK_CODE'''
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_KBK_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_KBK_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.KBK_CODE'''
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_SGU_CODE', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_SGU_CODE', 'EDIT_OBJECT_METHOD', 'n_vibor_01 ("DICTIONARY_ITEM", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE", "SGU_LINK, SGU_CODE", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_SGU_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_SGU_CODE', 'CONTROLSOURCE', 'm.cAlias+".SGU_CODE"'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_SGU_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_SGU_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".SGU_CODE"'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DCL_CODE', 'TITLE', 'Код цели'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DCL_CODE', 'EDIT_OBJECT_METHOD', 'n_vibor_01 ("BD_DOP_CLASSIF", oObj.Parent.Parent.RECORDSOURCE, "LINK,CODE", "DCL_LINK, DCL_CODE", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DCL_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DCL_CODE', 'CONTROLSOURCE', 'm.cAlias+".DCL_CODE"'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DCL_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_DCL_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DCL_CODE"'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_SUMMA', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_SUMMA', 'EDIT_OBJECT_METHOD', 'bb_calc_summ_doc(oForm.Alias,oObj.Parent.parent.RecordSource)
'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_SUMMA', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_SUMMA', 'CONTROLSOURCE', 'm.cAlias+''.SUMMA'''
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_SUMMA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_SUMMA', 'SHORT_CODE_OBJ', 'SUMMA'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_SUMMA', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.SUMMA'''
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_SUMMA', 'INPUT_MASK', '99999999999.99'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_TARGET', 'TITLE', 'Назначение платежа'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_TARGET', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_TARGET', 'CONTROLSOURCE', 'm.cAlias+".TARGET"'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_TARGET', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_UVED_U_TABLE_TARGET', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TARGET"'
GO

GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR', 'CREATE_PROV_SQL', 'BB_CREATE_PROV_ZAYAVKA_KR#Реестр перечисления денежных средств!bb_ZKR_create_restr_den_sr(oForm)'
GO

GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR_OKATO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BB_ZAYAVKA_KR_OKATO', 'Код ОКТМО', 28, (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BB_ZAYAVKA_KR_OKATO', NAME = 'Код ОКТМО', ORDERS = '28', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BB_ZAYAVKA_KR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BB_ZAYAVKA_KR_OKATO'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OKATO', 'TITLE', '105. Код ОКТМО'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OKATO', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTION_PAY_OKTMO",oForm.ALIAS, " CODE", "OKATO", "", "", "", .T., 0, oForm, oObj)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OKATO', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OKATO', 'CONTROLSOURCE', 'm.cAlias+''.OKATO'''
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OKATO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OKATO', 'TYPE_FIELD_DICT', 'varchar(11)'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OKATO', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OKATO', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.OKATO'''
GO
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_OKATO', 'CONTROL_NAME_EDIT', 'parent.page3.ASel_Spr1'
GO

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

GO
/****** Объект: К.Индекс.******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_SUMMA_T0_KOEF_IDX')
	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_SUMMA_T0_KOEF_IDX')
	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_SUMMA_T0_KOEF_IDX')
	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_SUMMA_T0_KOEF_IDX')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_SUMMA_T0_KOEF_IDX'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_SUMMA_T0_KOEF_IDX')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_SUMMA_T0_KOEF_IDX')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_SUMMA_T0_KOEF_IDX', 'К.Индекс.', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_FURLOUGH_TABLE0'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_SUMMA_T0_KOEF_IDX', NAME = 'К.Индекс.', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_FURLOUGH_TABLE0'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_SUMMA_T0_KOEF_IDX'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_T0_KOEF_IDX', 'TITLE', 'К.Индекс.'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_T0_KOEF_IDX', 'ORDER_NUMBER', '4'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_T0_KOEF_IDX', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_T0_KOEF_IDX', 'CONTROLSOURCE', 'm.cAlias + ".KOEF_IDX"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_T0_KOEF_IDX', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_T0_KOEF_IDX', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_T0_KOEF_IDX', 'TYPE_FIELD_DICT', 'NUMERIC(15,4)'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_T0_KOEF_IDX', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".KOEF_IDX"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_T0_KOEF_IDX', 'INPUT_MASK', '999 999.9999'
GO

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


GO
--- Заполнение таблицы Departments кодами ОКТМО , по кодам ОКАТО
IF exists(select * from sysobjects where id = object_id('[dbo].[OKATO_OKTMO_U]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	UPDATE  d 
		 SET OKTMO = ISNULL((SELECT TOP 1 OKTMO_BP FROM OKATO_OKTMO_U WHERE ltrim(rtrim(okato_used)) =  replace(ltrim(rtrim(d.okato)),' ', '') ),'')
	from DEPARTMENTS d where isnull(d.okato,'') <> ''  and isnull(d.OKTMO,'') = ''  
END

GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICTIONARY_ACCOUNTS', 'Расчетные и лицевые счета', 45, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_DEPARTMENT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICTIONARY_ACCOUNTS', NAME = 'Расчетные и лицевые счета', ORDERS = '45', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_DEPARTMENT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICTIONARY_ACCOUNTS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DICT_ACCOUNTS_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DICT_ACCOUNTS_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DICT_ACCOUNTS_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DICT_ACCOUNTS_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DICT_ACCOUNTS_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DICT_ACCOUNTS_CODE', 'Номер счета', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DICT_ACCOUNTS_CODE', NAME = 'Номер счета', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DICT_ACCOUNTS_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DICT_ACC_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DICT_ACC_TYPE', 'Вид счета', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DICT_ACC_TYPE', NAME = 'Вид счета', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DICT_ACC_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DICT_ACC_TYPE_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DICT_ACC_TYPE_1', 'Наименование вида счета', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DICT_ACC_TYPE_1', NAME = 'Наименование вида счета', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DICT_ACC_TYPE_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REF_LINK_DICT_ACC_BANK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REF_LINK_DICT_ACC_BANK', 'Ссылка на банк', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REF_LINK_DICT_ACC_BANK', NAME = 'Ссылка на банк', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REF_LINK_DICT_ACC_BANK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DICT_ACC_BANK_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DICT_ACC_BANK_CODE', 'Код банка (БИК)', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DICT_ACC_BANK_CODE', NAME = 'Код банка (БИК)', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DICT_ACC_BANK_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DICT_ACC_BANK_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DICT_ACC_BANK_NAME', 'Наименование банка', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DICT_ACC_BANK_NAME', NAME = 'Наименование банка', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DICT_ACC_BANK_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REF_LINK_DICT_ACC_KAZN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REF_LINK_DICT_ACC_KAZN', 'Ссылка на казначество', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REF_LINK_DICT_ACC_KAZN', NAME = 'Ссылка на казначество', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REF_LINK_DICT_ACC_KAZN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DICT_ACC_KAZN_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DICT_ACC_KAZN_CODE', 'Код казначейства', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DICT_ACC_KAZN_CODE', NAME = 'Код казначейства', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DICT_ACC_KAZN_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DICT_ACC_KAZN_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DICT_ACC_KAZN_NAME', 'Наименование казначества', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DICT_ACC_KAZN_NAME', NAME = 'Наименование казначества', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DICT_ACC_KAZN_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REF_LINK_DICT_ACC_KAZN_ACC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REF_LINK_DICT_ACC_KAZN_ACC', 'Ссылка на р/с казначества', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REF_LINK_DICT_ACC_KAZN_ACC', NAME = 'Ссылка на р/с казначества', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REF_LINK_DICT_ACC_KAZN_ACC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DICT_ACC_KAZN_ACC_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DICT_ACC_KAZN_ACC_CODE', 'Код р/с казначества', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DICT_ACC_KAZN_ACC_CODE', NAME = 'Код р/с казначества', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DICT_ACC_KAZN_ACC_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REF_LINK_DICT_ACC_DEPART')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REF_LINK_DICT_ACC_DEPART', 'Ссылка на владельца', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'REF_LINK_DICT_ACC_DEPART', NAME = 'Ссылка на владельца', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='REF_LINK_DICT_ACC_DEPART'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_ACC_DEPART_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_ACC_DEPART_CODE', 'Код владельца', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_ACC_DEPART_CODE', NAME = 'Код владельца', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICT_ACC_DEPART_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_ACC_DEPART_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_ACC_DEPART_NAME', 'Наименование владельца', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_ACC_DEPART_NAME', NAME = 'Наименование владельца', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICT_ACC_DEPART_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='OWNER_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'OWNER_NAME', 'Где открыт', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'OWNER_NAME', NAME = 'Где открыт', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='OWNER_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_ACCOUNTS_ANAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_ACCOUNTS_ANAME', 'Информация', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_ACCOUNTS_ANAME', NAME = 'Информация', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_ACCOUNTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_ACCOUNTS_ANAME'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'TITLE', 'Справочник расчетных счетов'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'INIT_OBJECT_METHOD', 'x_spisok("DICTIONARY_ACCOUNTS")'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "DICTIONARY_ACCOUNTS", "X_DELETE_DICTIONARY_ACCOUNTS", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_DICTIONARY_ACCOUNTS'', m.cAlias," CODE, TYPE, SQLNULL(REF_LINK_B), SQLNULL(K_ACC_LINK), SQLNULL(REF_LINK_D)","DICTIONARY_ACCOUNTS")'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'EDIT_OBJECT_METHOD', 'bdic_brow(''x_BROW_ACCOUNTS'')'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''DICTIONARY_ACCOUNTS'')'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'ANALIT_PROP', '1'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(''DICTIONARY_ACCOUNTS'')'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'OPEN_CODE', 'CODE'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'CODE_AP', 'DEP_ACC'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'TYPE_COLUMN_LENGTH', '20'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'S_TITLE_COLUMN_PROP', 'Счет'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'MSG_SEL_ONE', 'IIF(ISNULL(CODE),'''', CODE)'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'ANALIT_ORDER', '130'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'SERVER_TABLE_NAME', 'DEPARTMENT_ACCOUNTS'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'OPERATION_MASK', '8'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'EXCH_MODEL_CODE', 'ACC#SPR'
GO
EXEC X_SET_PROP 'DICTIONARY_ACCOUNTS', 'EXCHANGE', '3'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACCOUNTS_MARKER', 'VISIBLE', '25'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACCOUNTS_MARKER', 'CONTROLSOURCE', 'm.cAlias+".Checked"'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACCOUNTS_CODE', 'TITLE', 'Счет №'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACCOUNTS_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACCOUNTS_CODE', 'CONTROLSOURCE', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACCOUNTS_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACCOUNTS_CODE', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACCOUNTS_CODE', 'TYPE_FIELD_DICT', 'char(20)'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACCOUNTS_CODE', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACCOUNTS_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACCOUNTS_CODE', 'CONTROL_NAME_EDIT', 'ATXT1'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACCOUNTS_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACCOUNTS_CODE', 'FIELD_ALIAS', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACCOUNTS_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE', 'TITLE', 'Тип счета'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE', 'CONTROLSOURCE', 'm.cAlias+".TYPE"'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE', 'TYPE_FIELD_DICT', 'varchar(20)'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE', 'SHORT_CODE_OBJ', 'TYPE'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TYPE"'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE', 'CONTROL_NAME_EDIT', 'CmbT'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE', 'FIELD_ALIAS', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE', 'FIELD_DATA', 'TYPE'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE_1', 'TITLE', 'Тип счета'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE_1', 'VISIBLE', '5'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE_1', 'CONTROLSOURCE', 'm.cAlias+".TYPE_NAME"'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE_1', 'TYPE_FIELD_DICT', 'varchar(20)'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE_1', 'SHORT_CODE_OBJ', 'TYPE_NAME'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TYPE_NAME"'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE_1', 'FIELD_ALIAS', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_TYPE_1', 'FIELD_DATA', 'TYPE_NAME'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_BANK', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_BANK', 'REFERENCE_TO_DICT', 'DICTIONARY_BANK'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_BANK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_BANK', 'SHORT_CODE_OBJ', 'REF_LINK_B'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_BANK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_BANK', 'FIELD_ALIAS', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_BANK', 'FIELD_DATA', 'REF_LINK_B'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_BANK",oForm.ALIAS,"LINK, BIK, NAME, OBJECT", "REF_LINK_B, BANK_CODE, BANK_NAME, BANK_OBJECT", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_CODE', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_CODE', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_CODE', 'REFERENCE_TO_DICT', 'REF_LINK_DICT_ACC_BANK'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_CODE', 'TYPE_FIELD_DICT', 'varchar(9)'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_CODE', 'SHORT_CODE_OBJ', 'BANK_CODE'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".BANK_CODE"'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_CODE', 'CONTROL_NAME_EDIT', 'ASEL_SPR3'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_CODE', 'REFERENCE_TO_FIELD', 'BIK'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_CODE', 'FIELD_ALIAS', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_CODE', 'FIELD_DATA', 'BANK_CODE'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_NAME', 'TITLE', 'Банк'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_NAME', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_NAME', 'REFERENCE_TO_DICT', 'REF_LINK_DICT_ACC_BANK'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_NAME', 'TYPE_FIELD_DICT', 'varchar(40)'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_NAME', 'SHORT_CODE_OBJ', 'BANK_NAME'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".BANK_NAME"'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_NAME', 'CONTROL_NAME_EDIT', 'ATXTN3'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_NAME', 'FIELD_ALIAS', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_BANK_NAME', 'FIELD_DATA', 'BANK_NAME'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_KAZN', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_KAZN', 'REFERENCE_TO_DICT', 'DICTIONARY_TREASURY'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_KAZN', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_KAZN', 'SHORT_CODE_OBJ', 'REF_LINK_K'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_KAZN', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_KAZN', 'FIELD_ALIAS', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_KAZN', 'FIELD_DATA', 'REF_LINK_K'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_TREASURY",oForm.ALIAS,"LINK, CODE, NAME, OBJECT", "REF_LINK_K, KAZN_CODE, KAZN_NAME, KAZN_OBJECT", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_CODE', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_CODE', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_CODE', 'REFERENCE_TO_DICT', 'REF_LINK_DICT_ACC_KAZN'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_CODE', 'TYPE_FIELD_DICT', 'CHAR(4)'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_CODE', 'SHORT_CODE_OBJ', 'KAZN_CODE'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".KAZN_CODE"'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_CODE', 'CONTROL_NAME_EDIT', 'ASEL_SPR4'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_CODE', 'FIELD_ALIAS', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_CODE', 'FIELD_DATA', 'KAZN_CODE'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_NAME', 'TITLE', 'Казначейство'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_NAME', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_NAME', 'REFERENCE_TO_DICT', 'REF_LINK_DICT_ACC_KAZN'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_NAME', 'TYPE_FIELD_DICT', 'varchar(40)'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_NAME', 'SHORT_CODE_OBJ', 'KAZN_NAME'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".KAZN_NAME"'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_NAME', 'CONTROL_NAME_EDIT', 'ATXTN4'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_NAME', 'FIELD_ALIAS', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_NAME', 'FIELD_DATA', 'KAZN_NAME'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_KAZN_ACC', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_KAZN_ACC', 'REFERENCE_TO_DICT', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_KAZN_ACC', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_KAZN_ACC', 'SHORT_CODE_OBJ', 'K_ACC_LINK'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_KAZN_ACC', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_KAZN_ACC', 'FIELD_ALIAS', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_KAZN_ACC', 'FIELD_DATA', 'K_ACC_LINK'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_ACC_CODE', 'TITLE', 'Р/с казначейства'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_ACC_CODE', 'EDIT_OBJECT_METHOD', 'v_select_kazn_acc(oForm, oObj)'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_ACC_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_ACC_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_ACC_CODE', 'STORAGE', 'DICTION_REF'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_ACC_CODE', 'REFERENCE_TO_DICT', 'REF_LINK_DICT_ACC_KAZN_ACC'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_ACC_CODE', 'TYPE_FIELD_DICT', 'char(20)'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_ACC_CODE', 'SHORT_CODE_OBJ', 'K_ACC_CODE'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_ACC_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".K_ACC_CODE"'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_ACC_CODE', 'CONTROL_NAME_EDIT', 'ASEL_SPR5'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_ACC_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_ACC_CODE', 'FIELD_ALIAS', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'COLUMN_DICT_ACC_KAZN_ACC_CODE', 'FIELD_DATA', 'K_ACC_CODE'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_DEPART', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_DEPART', 'STORAGE', 'DICTION_DEP'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_DEPART', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_DEPART', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_DEPART', 'SHORT_CODE_OBJ', 'REF_LINK_D'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_DEPART', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_DEPART', 'FIELD_ALIAS', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'REF_LINK_DICT_ACC_DEPART', 'FIELD_DATA', 'REF_LINK_D'
GO
EXEC X_SET_PROP 'DICT_ACC_DEPART_CODE', 'STORAGE', 'DICTION_DEP'
GO
EXEC X_SET_PROP 'DICT_ACC_DEPART_CODE', 'REFERENCE_TO_DICT', 'REF_LINK_DICT_ACC_DEPART'
GO
EXEC X_SET_PROP 'DICT_ACC_DEPART_CODE', 'TYPE_FIELD_DICT', 'char(4)'
GO
EXEC X_SET_PROP 'DICT_ACC_DEPART_CODE', 'SHORT_CODE_OBJ', 'DEP_CODE'
GO
EXEC X_SET_PROP 'DICT_ACC_DEPART_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DICT_ACC_DEPART_CODE', 'FIELD_ALIAS', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'DICT_ACC_DEPART_CODE', 'FIELD_DATA', 'DEP_CODE'
GO
EXEC X_SET_PROP 'DICT_ACC_DEPART_NAME', 'VISIBLE', '14'
GO
EXEC X_SET_PROP 'DICT_ACC_DEPART_NAME', 'CONTROLSOURCE', 'm.cAlias+".DEP_NAME"'
GO
EXEC X_SET_PROP 'DICT_ACC_DEPART_NAME', 'STORAGE', 'DICTION_DEP'
GO
EXEC X_SET_PROP 'DICT_ACC_DEPART_NAME', 'REFERENCE_TO_DICT', 'REF_LINK_DICT_ACC_DEPART'
GO
EXEC X_SET_PROP 'DICT_ACC_DEPART_NAME', 'TYPE_FIELD_DICT', 'char(254)'
GO
EXEC X_SET_PROP 'DICT_ACC_DEPART_NAME', 'SHORT_CODE_OBJ', 'DEP_NAME'
GO
EXEC X_SET_PROP 'DICT_ACC_DEPART_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DICT_ACC_DEPART_NAME', 'FIELD_ALIAS', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'DICT_ACC_DEPART_NAME', 'FIELD_DATA', 'DEP_NAME'
GO
EXEC X_SET_PROP 'OWNER_NAME', 'TITLE', 'Банк/Казначейство'
GO
EXEC X_SET_PROP 'OWNER_NAME', 'VISIBLE', '17'
GO
EXEC X_SET_PROP 'OWNER_NAME', 'CONTROLSOURCE', 'm.cAlias+".Owner_Name"'
GO
EXEC X_SET_PROP 'OWNER_NAME', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'OWNER_NAME', 'FIELD_ALIAS', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'OWNER_NAME', 'FIELD_DATA', 'OWNER_NAME'
GO
EXEC X_SET_PROP 'COLUMN_ACCOUNTS_ANAME', 'TITLE', 'Информация'
GO
EXEC X_SET_PROP 'COLUMN_ACCOUNTS_ANAME', 'VISIBLE', '12'
GO
EXEC X_SET_PROP 'COLUMN_ACCOUNTS_ANAME', 'CONTROLSOURCE', 'm.cAlias+".ANAME"'
GO
EXEC X_SET_PROP 'COLUMN_ACCOUNTS_ANAME', 'FIELD_ALIAS', 'DICTIONARY_ACCOUNTS'
GO
EXEC X_SET_PROP 'COLUMN_ACCOUNTS_ANAME', 'FIELD_DATA', 'ANAME'
GO

GO
/****** Объект: Код по ОКАТО******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'DSA_O_OKATO')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'DSA_O_OKATO')
	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 = 'DSA_O_OKATO')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'DSA_O_OKATO')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DSA_O_OKATO'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DSA_O_OKATO')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DSA_O_OKATO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DSA_O_OKATO', 'Код по ОКАТО/ОКТМО', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_SUBDIVISION_ALL'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DSA_O_OKATO', NAME = 'Код по ОКАТО/ОКТМО', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_SUBDIVISION_ALL'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DSA_O_OKATO'
GO
EXEC X_SET_PROP 'DSA_O_OKATO', 'TITLE', 'Код по ОКАТО/ОКТМО'
GO
EXEC X_SET_PROP 'DSA_O_OKATO', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'DSA_O_OKATO', 'CONTROLSOURCE', 'm.cAlias + ".O_OKATO"'
GO
EXEC X_SET_PROP 'DSA_O_OKATO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DSA_O_OKATO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".O_OKATO"'
GO
EXEC X_SET_PROP 'DSA_O_OKATO', 'INPUT_MASK', '## ### ### ###'
GO
EXEC X_SET_PROP 'DSA_O_OKATO', 'COMMENTARY', 'Для обособленного подразделения код по ОКАТО/ОКТМО.'
GO

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


GO
/****** Объект: Использовать ОКАТО или ОКТМО******/


DECLARE @T TABLE (LINK INT, CODE VARCHAR(30), FLAG TINYINT)

/******--Запомнить настройки на базе пользователя ******/
INSERT @T (LINK, CODE, FLAG)
SELECT LINK, CODE, 1
FROM  dbo.S_OBJECTS SO WHERE CODE='NASTR_USE_OKATO_OKTMO'

WHILE EXISTS(SELECT * FROM dbo.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM @T WHERE FLAG=1))
BEGIN
	INSERT @T (LINK, CODE,FLAG)
	SELECT LINK, CODE, 0 
	FROM dbo.S_OBJECTS SO WHERE LINK_SELF IN (SELECT LINK FROM @T WHERE FLAG=1)
	UPDATE @T SET FLAG=2 WHERE FLAG=1
	UPDATE @T SET FLAG=1 WHERE FLAG=0
END

IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_NASTR_USE_OKATO_OKTMO]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_NASTR_USE_OKATO_OKTMO]

CREATE TABLE  dbo._UPD_OPT_NASTR_USE_OKATO_OKTMO (CODE VARCHAR(30), [SID] varbinary(85), VALUE VARCHAR(1000))

INSERT INTO _UPD_OPT_NASTR_USE_OKATO_OKTMO (CODE, [SID], VALUE)
SELECT T.CODE, so.[sid], so.VALUE
FROM 
	@T T INNER JOIN dbo.S_OPTIONS so ON so.[OBJECT] = T.LINK

GO

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'NASTR_USE_OKATO_OKTMO')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'NASTR_USE_OKATO_OKTMO')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'NASTR_USE_OKATO_OKTMO')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'NASTR_USE_OKATO_OKTMO')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'NASTR_USE_OKATO_OKTMO'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'NASTR_USE_OKATO_OKTMO')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='NASTR_USE_OKATO_OKTMO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'NASTR_USE_OKATO_OKTMO', 'Использовать ОКАТО или ОКТМО', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='ALL_OPT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'NASTR_USE_OKATO_OKTMO', NAME = 'Использовать ОКАТО или ОКТМО', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='ALL_OPT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='NASTR_USE_OKATO_OKTMO'
GO
EXEC X_SET_PROP 'NASTR_USE_OKATO_OKTMO', 'TITLE', 'Использовать ОКАТО или ОКТМО'
GO
EXEC X_SET_PROP 'NASTR_USE_OKATO_OKTMO', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'NASTR_USE_OKATO_OKTMO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'NASTR_USE_OKATO_OKTMO', 'ROWSOURCE', 'ОКАТО,ОКТМО'
GO
EXEC X_SET_PROP 'NASTR_USE_OKATO_OKTMO', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'NASTR_USE_OKATO_OKTMO', 'TYPE_FIELD_DICT', 'varchar(5)'
GO
EXEC X_SET_PROP 'NASTR_USE_OKATO_OKTMO', 'CONTROL_NAME_EDIT', 'aComboBox3'
GO
EXEC X_SET_PROP 'NASTR_USE_OKATO_OKTMO', 'COMMENTARY', 'Использовать ОКАТО или ОКТМО'
GO
/******--Восстановить, либо установить настройки на базе пользователя ******/
DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'NASTR_USE_OKATO_OKTMO' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_NASTR_USE_OKATO_OKTMO] WHERE CODE = 'NASTR_USE_OKATO_OKTMO')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'NASTR_USE_OKATO_OKTMO'), SID, VALUE = 2 FROM [dbo].[_UPD_OPT_NASTR_USE_OKATO_OKTMO] WHERE CODE = 'NASTR_USE_OKATO_OKTMO'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, 2 FROM  dbo.S_OBJECTS WHERE CODE = 'NASTR_USE_OKATO_OKTMO'

GO


IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_NASTR_USE_OKATO_OKTMO]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_NASTR_USE_OKATO_OKTMO]

GO


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


GO
EXEC X_SET_PROP 'SALARY_OPTIONS', 'OPTIONS_OBJECT_CODE', 'SALARY_OPTIONS_OPTIONS,SALARY_OPTIONS_OPTIONS2,SALARY_OPTIONS_OPTIONS3,SALARY_OPTIONS_OPTIONS5,SALARY_OPTIONS_OPTIONS6,SALARY_OPTIONS_OPTIONS7,SALARY_OPTIONS_OPTIONS8'
GO
GO
/****** Объект: Настройки расчёта формы П-4******/


DECLARE @T TABLE (LINK INT, CODE VARCHAR(30), FLAG TINYINT)

/******--Запомнить настройки на базе пользователя ******/
INSERT @T (LINK, CODE, FLAG)
SELECT LINK, CODE, 1
FROM  dbo.S_OBJECTS SO WHERE CODE='SALARY_OPTIONS_OPTIONS7'

WHILE EXISTS(SELECT * FROM dbo.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM @T WHERE FLAG=1))
BEGIN
	INSERT @T (LINK, CODE,FLAG)
	SELECT LINK, CODE, 0 
	FROM dbo.S_OBJECTS SO WHERE LINK_SELF IN (SELECT LINK FROM @T WHERE FLAG=1)
	UPDATE @T SET FLAG=2 WHERE FLAG=1
	UPDATE @T SET FLAG=1 WHERE FLAG=0
END

IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS7]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS7]

CREATE TABLE  dbo._UPD_OPT_SALARY_OPTIONS_OPTIONS7 (CODE VARCHAR(30), [SID] varbinary(85), VALUE VARCHAR(1000))

INSERT INTO _UPD_OPT_SALARY_OPTIONS_OPTIONS7 (CODE, [SID], VALUE)
SELECT T.CODE, so.[sid], so.VALUE
FROM 
	@T T INNER JOIN dbo.S_OPTIONS so ON so.[OBJECT] = T.LINK

GO

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPTIONS7')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'SALARY_OPTIONS_OPTIONS7')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'SALARY_OPTIONS_OPTIONS7')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'SALARY_OPTIONS_OPTIONS7')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPTIONS7'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPTIONS7')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS7')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SALARY_OPTIONS_OPTIONS7', 'Настройки расчёта формы П-4', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SALARY_OPTIONS_OPTIONS7', NAME = 'Настройки расчёта формы П-4', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SALARY_OPTIONS_OPTIONS7'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPT7_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SALARY_OPTIONS_OPT7_1', 'Способ заполнения средней численности', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS7'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SALARY_OPTIONS_OPT7_1', NAME = 'Способ заполнения средней численности', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS7'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SALARY_OPTIONS_OPT7_1'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPTIONS7', 'TITLE', 'Настройки расчёта формы П-4'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPTIONS7', 'EDIT_OBJECT_METHOD', 'sa_open_task_options("SALARY_OPTIONS_OPTIONS7", "Настройки расчёта формы П-4")'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPTIONS7', 'COMMENTARY', 'Прочие общие настройки'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT7_1', 'TITLE', 'Способ заполнения средней численности'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT7_1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT7_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT7_1', 'ROWSOURCE', '1.По формулам расчета П-4,2.Округлять среднюю численность работников,3.Не округлять среднюю численность работников'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT7_1', 'STORAGE', 'SK'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT7_1', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT7_1', 'CONTROL_NAME_EDIT', 'AComboBox1'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT7_1', 'COMMENTARY', 'Вариант №1. средняя численность по организации рассчитывается  по формулам расчёта для П-4. Вариант №2. Округляется средняя численность по организации в соответствующих ячейках (до единиц, десятичный знак - 0). Вариант №3. Средняя численность не округляется(в форме отражается с десятичным знаком).'
GO
/******--Восстановить, либо установить настройки на базе пользователя ******/
DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'SALARY_OPTIONS_OPT7_1' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS7] WHERE CODE = 'SALARY_OPTIONS_OPT7_1')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT7_1'), SID, VALUE FROM [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS7] WHERE CODE = 'SALARY_OPTIONS_OPT7_1'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '1' FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT7_1'

GO


IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS7]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS7]

GO


/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPTIONS7', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPTIONS7', 'Свод-КС', 5,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPTIONS7', 'Смета-КС', 4,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPTIONS7', 'Главный бухгалтер', 63,0
GO

/**************** УСТАНОВКА ДОСТУПА К НАСТРОЙКАМ *************/
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPT7_1', 'Зарплата-КС', 63,0
GO


GO
/****** Объект: Настройки расчёта форм N-ЗП******/


DECLARE @T TABLE (LINK INT, CODE VARCHAR(30), FLAG TINYINT)

/******--Запомнить настройки на базе пользователя ******/
INSERT @T (LINK, CODE, FLAG)
SELECT LINK, CODE, 1
FROM  dbo.S_OBJECTS SO WHERE CODE='SALARY_OPTIONS_OPTIONS8'

WHILE EXISTS(SELECT * FROM dbo.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM @T WHERE FLAG=1))
BEGIN
	INSERT @T (LINK, CODE,FLAG)
	SELECT LINK, CODE, 0 
	FROM dbo.S_OBJECTS SO WHERE LINK_SELF IN (SELECT LINK FROM @T WHERE FLAG=1)
	UPDATE @T SET FLAG=2 WHERE FLAG=1
	UPDATE @T SET FLAG=1 WHERE FLAG=0
END

IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS8]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS8]

CREATE TABLE  dbo._UPD_OPT_SALARY_OPTIONS_OPTIONS8 (CODE VARCHAR(30), [SID] varbinary(85), VALUE VARCHAR(1000))

INSERT INTO _UPD_OPT_SALARY_OPTIONS_OPTIONS8 (CODE, [SID], VALUE)
SELECT T.CODE, so.[sid], so.VALUE
FROM 
	@T T INNER JOIN dbo.S_OPTIONS so ON so.[OBJECT] = T.LINK

GO

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPTIONS8')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'SALARY_OPTIONS_OPTIONS8')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'SALARY_OPTIONS_OPTIONS8')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'SALARY_OPTIONS_OPTIONS8')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPTIONS8'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPTIONS8')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS8')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SALARY_OPTIONS_OPTIONS8', 'Настройки расчёта форм N-ЗП', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SALARY_OPTIONS_OPTIONS8', NAME = 'Настройки расчёта форм N-ЗП', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SALARY_OPTIONS_OPTIONS8'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPT8_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SALARY_OPTIONS_OPT8_1', 'Способ заполнения средней численности', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS8'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SALARY_OPTIONS_OPT8_1', NAME = 'Способ заполнения средней численности', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS8'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SALARY_OPTIONS_OPT8_1'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPTIONS8', 'TITLE', 'Настройки расчёта форм N-ЗП'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPTIONS8', 'EDIT_OBJECT_METHOD', 'sa_open_task_options("SALARY_OPTIONS_OPTIONS8", "Настройки расчёта форм N-ЗП")'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPTIONS8', 'COMMENTARY', 'Прочие общие настройки'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT8_1', 'TITLE', 'Способ заполнения средней численности'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT8_1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT8_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT8_1', 'ROWSOURCE', '1.По формулам расчета N-ЗП,2.Округлять среднюю численность работников,3.Не округлять среднюю численность работников'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT8_1', 'STORAGE', 'SK'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT8_1', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT8_1', 'CONTROL_NAME_EDIT', 'AComboBox1'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT8_1', 'COMMENTARY', 'Вариант №1. средняя численность по организации рассчитывается по формулам расчёта для N-ЗП. Вариант №2. Округляется средняя численность по организации в соответствующих ячейках (до единиц , десятичный знак - 0). Вариант №3. Средняя численность не округляется(в форме отражается с десятичным знаком).'
GO
/******--Восстановить, либо установить настройки на базе пользователя ******/
DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'SALARY_OPTIONS_OPT8_1' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS8] WHERE CODE = 'SALARY_OPTIONS_OPT8_1')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT8_1'), SID, VALUE FROM [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS8] WHERE CODE = 'SALARY_OPTIONS_OPT8_1'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '1' FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT8_1'

GO


IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS8]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS8]

GO


/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPTIONS8', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPTIONS8', 'Свод-КС', 5,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPTIONS8', 'Смета-КС', 4,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPTIONS8', 'Главный бухгалтер', 63,0
GO

/**************** УСТАНОВКА ДОСТУПА К НАСТРОЙКАМ *************/
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPT8_1', 'Зарплата-КС', 63,0
GO


GO
--- Вычеты и МРОТ
declare @PERIOD datetime

SET @PERIOD = coalesce((select Max(PERIOD) from minrot),'20000101')
IF @PERIOD < '20140101'
BEGIN
	declare @P1 int, @LINK_DED INT
				
	DECLARE @Object int, @LinkDep int
	SELECT @Object = LINK FROM dbo.S_OBJECTS WHERE CODE = 'COLUMN_REF_PAY_MROT_T1'
	SELECT @LinkDep = LINK FROM dbo.DICTIONARY_DEPARTMENT WHERE TYPE = 4
	
	Declare @nRKoef numeric(18,2), @KOEF_BL numeric(18,2), @TARIF numeric(18,2), @MROT1 numeric(18,2)
	/*прежние значения*/
	select top 1 @MROT1 =MROT1, @TARIF = TARIF, @nRKoef = KOEF, @KOEF_BL = KOEF_BL from dbo.MINROT order by PERIOD desc

	Select @MROT1 = COALESCE(@MROT1,100), @TARIF = COALESCE(@TARIF,2300), @nRKoef = COALESCE(@nRKoef,1), @KOEF_BL = COALESCE(@KOEF_BL,1)

	set @P1 = 0
	exec SALARY_SAVE_DICTIONARY_MROT @P1 output, 
			/*начало периода*/'20140101', 
			/*МРОТ общий*/@MROT1, 
			/*МРОТ для зарплаты*/5554, 
			/*Ставка первого разряда*/@TARIF, 
			/*Районный коэффициент*/@nRKoef, 
			/*Районный коэффициент для Б/Л*/@KOEF_BL, 
					@LinkDep

	IF COALESCE(@Object,0) > 0 AND COALESCE(@P1,0) > 0 BEGIN
		-- Заполняем первую вкладку
		
		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '104'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,0,500)

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '105'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,0,3000)
	--
		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '114'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,280000,1400)

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '115'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,280000,1400)
			
		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '116'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,280000,3000)

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '117'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,280000,3000)
	--
		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '118'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,280000,2800)
		
		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '119'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,280000,2800)
			
		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '120'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,280000,6000)

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '121'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,280000,6000)			
	--
		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '122'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,280000,2800)

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '123'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,280000,2800)

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '124'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,280000,6000)

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '125'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,280000,6000)									

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '313'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,0,2000000)				

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '501'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,0,4000)				

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '502'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,0,4000)				

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '503'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,0,4000)				
	
		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '602'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,12000,0)	


	END

	-- Заполняем вторую вкладку
	SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '503'
	IF COALESCE(@P1,0) > 0 AND COALESCE(@LINK_DED,0) > 0 
		EXEC SALARY_SAVE_DICTIONARY_MROT_TABLE2 @P1, @LINK_DED, 4000


	
	-- Заполняем третью вкладку
	
	DECLARE @FSS12 int

	SELECT TOP 1 @FSS12 = LINK FROM PAYS WHERE OBJECT = 3 AND WAY_CALC = 5

	IF COALESCE(@P1,0) > 0 BEGIN
		IF COALESCE(@FSS12,0) > 0
			exec SALARY_SAVE_DICTIONARY_MROT_TABLE3 @P1, @FSS12, 0, 0.12
	END


END   

IF @PERIOD = '20140101'
BEGIN

	declare @P2 int, @LINK_DED1 INT
	DECLARE @Object1 int
	SELECT @Object1 = LINK FROM dbo.S_OBJECTS WHERE CODE = 'COLUMN_REF_PAY_MROT_T1'


	SET @P2 = (select TOP 1 link from minrot where period = @PERIOD)
	
	IF COALESCE(@Object1,0) > 0 AND COALESCE(@P2,0) > 0 BEGIN
		-- Заполняем первую вкладку

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '104'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 500 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '105'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 3000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

	--
		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '114'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 1400 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '115'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 1400 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1
			
		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '116'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 3000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '117'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 3000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

	--
		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '118'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 2800 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

		
		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '119'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 2800 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1
			
		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '120'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 6000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '121'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 6000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1
	
	--
		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '122'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 2800 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '123'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 2800 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '124'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 6000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1		

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '125'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 6000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1		

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '313'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 2000000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1		

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '501'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 4000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1		

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '502'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 4000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1		

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '503'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 4000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1		

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '602'
		IF COALESCE(@LINK_DED1,0) > 0 
		BEGIN 
			IF exists (select * from MINROT_DICTION where LINK_DICTION = @LINK_DED1 and LINK_MINROT = @p2)
			DELETE FROM MINROT_DICTION WHERE LINK_DICTION = @LINK_DED1 and LINK_MINROT = @p2

			SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '602'
			IF COALESCE(@LINK_DED1,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P2,@LINK_DED1,@Object1,12000,0)	
		END
	END

	-- Заполняем вторую вкладку
	SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '503'
	IF COALESCE(@P2,0) > 0 AND COALESCE(@LINK_DED1,0) > 0 
		EXEC SALARY_SAVE_DICTIONARY_MROT_TABLE2 @P2, @LINK_DED1, 4000
	-- Заполняем третью вкладку
	
	DECLARE @FSS12_1 int

	SELECT TOP 1 @FSS12_1 = LINK FROM PAYS WHERE OBJECT = 3 AND WAY_CALC = 5

	IF COALESCE(@P2,0) > 0 BEGIN
		IF COALESCE(@FSS12_1,0) > 0
			exec SALARY_SAVE_DICTIONARY_MROT_TABLE3 @P2, @FSS12_1, 0, 0.12
	END

END

GO
GO

---- Установка видов страховых взносов
DECLARE @LINK_OBJ INT
SET @LINK_OBJ = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS SO WHERE SO.CODE = 'COLUMN_REF_PAY_MROT_T4')

DELETE MP
FROM dbo.MINROT_PAYS MP INNER JOIN dbo.MINROT M ON MP.LINK_MINROT = M.LINK
WHERE MP.[OBJECT] = @LINK_OBJ AND M.PERIOD BETWEEN '20120101' AND '20990101'

INSERT INTO dbo.MINROT_PAYS (LINK_MINROT, LINK_PAYS, OBJECT)
SELECT M.LINK, P.LINK, @LINK_OBJ
FROM dbo.MINROT M INNER JOIN dbo.PAYS P ON 1=1
WHERE 
	M.PERIOD >= '20120101'
	AND
	M.PERIOD < '20990101'
	AND
	P.[OBJECT] = 3 
	AND 
	(	P.WAY_CALC IN (2,3,7,6) 
		OR 
		P.WAY_CALC IN (10, 11) AND EXISTS (SELECT * FROM S_J_C_SHORT WHERE YEAR(PERIOD_BEGIN) = '2013' AND (WAY_CALC = 10 OR WAY_CALC = 11))
	)
ORDER BY
	M.LINK, P.LINK
GO



GO


---- Установка видов страховых взносов
DECLARE @LINK_OBJ INT
SET @LINK_OBJ = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS SO WHERE SO.CODE = 'COLUMN_REF_PAY_MROT_T4')

DELETE MP
FROM dbo.MINROT_PAYS MP INNER JOIN dbo.MINROT M ON MP.LINK_MINROT = M.LINK
WHERE MP.[OBJECT] = @LINK_OBJ AND M.PERIOD BETWEEN '20140101' AND '20990101'

INSERT INTO dbo.MINROT_PAYS (LINK_MINROT, LINK_PAYS, OBJECT)
SELECT M.LINK, P.LINK, @LINK_OBJ
FROM dbo.MINROT M INNER JOIN dbo.PAYS P ON 1=1
WHERE 
	M.PERIOD >= '20140101'
	AND
	M.PERIOD < '20990101'
	AND
	P.[OBJECT] = 3 
	AND 
	(	P.WAY_CALC IN (2,3,6) 
		OR 
		P.WAY_CALC IN (10, 11) AND EXISTS (SELECT * FROM S_J_C_SHORT WHERE YEAR(PERIOD_BEGIN) = '2014' AND (WAY_CALC = 10 OR WAY_CALC = 11))
	)
ORDER BY
	M.LINK, P.LINK
GO

GO





--Обновление настроек 2014 года
exec dbo.SA_SET_STATIC_NASTR '2014'
GO


/*Формирование всех используемых графиков на 2014 год*/
DECLARE @Cur1 CURSOR, @LinkGrophik int, @VID_LINK int, @NAME_GR varchar(254)
DECLARE @Cur2 CURSOR, @DAY tinyint, @HOUR numeric(18,2), @TD_LINK int

DECLARE @MONTH INT, @YEAR INT
DECLARE @LINK INT, @LINK2 INT, @gDayNorm INT, @gHourNorm numeric(18,2)

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

SET @Cur1 = CURSOR FORWARD_ONLY

FOR select LINK, VID_LINK, [NAME] from GRAPH order by link
OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @LinkGrophik, @VID_LINK, @NAME_GR
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN

		SELECT @YEAR = 2014, @MONTH = 1
		WHILE @MONTH <= 12
		BEGIN

			IF NOT EXISTS(SELECT @LinkGrophik FROM dbo.KD_GRAPH_TABLE WHERE [YEAR] = @YEAR AND [MONTH] = @MONTH AND LINK_GR = @LinkGrophik)
			BEGIN
				IF object_id('tempdb..#sa_tmp_graph') is not null
				drop table #sa_tmp_graph
				
				CREATE TABLE #sa_tmp_graph(CHECKED tinyint, UPD tinyint, DEL tinyint, [DAY] tinyint, [HOUR] numeric(18,2), TD_LINK int, TD_CODE varchar(10),
						TD_NAME varchar(254), PRIORITET tinyint )
				
				INSERT INTO #sa_tmp_graph(CHECKED, UPD, DEL, [DAY], [HOUR], TD_LINK, TD_CODE, TD_NAME, PRIORITET)
				exec dbo.KD_GRAPH_FILL @VID_LINK, @MONTH, @YEAR
				
				Select @gHourNorm = DBO.MINUTES_TO_NUM(SUM(DBO.NUM_TO_MINUTES([HOUR],@ISMINUTES)),@ISMINUTES) from #sa_tmp_graph where [HOUR] > 0
				Select @gDayNorm = COUNT(DISTINCT [DAY]) from #sa_tmp_graph where [HOUR] > 0
				
				IF COALESCE(@gHourNorm,0) > 0 AND coalesce(@gDayNorm,0) > 0
				BEGIN
				
					EXEC dbo.KD_GRAPH_SAVE @LinkGrophik OUT, @LINK2 OUT, @NAME_GR, @MONTH, @YEAR, @VID_LINK, @gDayNorm, @gHourNorm
		
					SET @Cur2 = CURSOR FORWARD_ONLY
					
					FOR select [DAY], [HOUR], [TD_LINK] from #sa_tmp_graph order by [DAY]
					OPEN @Cur2
					FETCH NEXT FROM @Cur2 INTO @DAY, @HOUR, @TD_LINK
					WHILE (@@fetch_status <> -1)
					BEGIN
						IF (@@fetch_status <> -2)
						BEGIN
							exec dbo.KD_GRAPH_TABLE_SAVE @LINK2, @DAY, @HOUR, @TD_LINK
						END
					
						FETCH NEXT FROM @Cur2 INTO @DAY, @HOUR, @TD_LINK
					END
					
					CLOSE @Cur2
					DEALLOCATE @Cur2
				END
			END

			Set @MONTH = @MONTH + 1
		END
		
	END
	FETCH NEXT FROM @Cur1 INTO @LinkGrophik, @VID_LINK, @NAME_GR
END

CLOSE @Cur1
DEALLOCATE @Cur1
GO




/*НАСТРОЙКИ ТАРИФОВ  2014 ГОДА*/


--Общий (НР)
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 2 --Фонд Социального Страхования
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 1),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20140101','ФСС РФ',624000, 2.9, 1

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20140101','ФСС РФ',999999999, 0, 1
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 3 --Федеральный фонд медицинского страхования
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 1),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20140101','ФФОМС',624000, 5.1, 1

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20140101','ФФОМС',999999999, 0, 1
GO


--- ПФ Страховая часть  для лиц моложе 1967 года накопительная страховая 22 %
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 6 --ПФ Страховая часть
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 1),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20140101','ПФ Страховая часть',624000, 22, 22, 22, 1

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20140101','ПФ Страховая часть',999999999, 10, 10, 10, 1
GO

--- накопительную часть убераем
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 7  --ПФ Накопительная часть
IF EXISTS (select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 1)
DELETE  FROM dbo.stavki_pf WHERE link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 1

IF EXISTS (select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1)
DELETE  FROM dbo.stavki_pf WHERE link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1
GO



--- солидарную часть убераем
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 8 --ПФ Солидарная часть
IF EXISTS (select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 1)
DELETE  FROM dbo.stavki_pf WHERE link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 1

IF EXISTS (select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1)
DELETE  FROM dbo.stavki_pf WHERE link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1
GO

--- Индивидуальную часть убераем
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 9 --ПФ Индивидуальная часть
IF exists(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 1)
DELETE  FROM dbo.stavki_pf WHERE link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 1

IF exists(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1)
DELETE  FROM dbo.stavki_pf WHERE link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1
GO


DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1 
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20140101','ПФ Доп.тариф №1',999999999,  6, 6, 6, 1
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 1),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20140101','ПФ Доп.тариф №2',999999999, 4, 4, 4, 1
GO

--Инвалиды (ОЗОИ)
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 2 --Фонд Социального Страхования
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 3),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20140101','ФСС РФ',624000, 2.4, 3

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20140101','ФСС РФ',999999999, 0, 3
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 3 --Федеральный фонд медицинского страхования
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 3),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20140101','ФФОМС',624000, 3.7, 3

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20140101','ФФОМС',999999999, 0, 3
GO

--ПФ Страховая часть
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 6 --ПФ Страховая часть
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 3),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20140101','ПФ Страховая часть',624000, 21, 21, 21, 3

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20140101','ПФ Страховая часть',999999999, 0, 0, 0, 3
GO

--ПФ Накопительная часть УБИРАЕМ
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 7 --ПФ Накопительная часть
IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 3)							/* 415000  */
delete from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 3

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3)
delete from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3
GO

--ПФ Солидарная часть УБИРАЕМ
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 8 --ПФ Солидарная часть
IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 3)							/* 415000  */
delete from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 3

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3)
delete from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3
GO

--ПФ Индивидуальная часть УБИРАЕМ
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 9 --ПФ Индивидуальная часть
IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 3)								/* 415000  */
delete from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 3

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3)
delete from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1 
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20140101','ПФ Доп.тариф №1',999999999,  6, 6, 6, 3
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 3),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20140101','ПФ Доп.тариф №2',999999999, 4, 4, 4, 3
GO




--СМИ(СМИ)
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 2 --Фонд Социального Страхования
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 4),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20140101','ФСС РФ',624000, 2.9, 4

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20140101','ФСС РФ',999999999, 0, 4
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 3 --Федеральный фонд медицинского страхования
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 4),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20140101','ФФОМС',624000, 3.9, 4

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20140101','ФФОМС',999999999, 0, 4
GO

--ПФ Страховая часть
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 6 --ПФ Страховая часть
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 4),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20140101','ПФ Страховая часть',624000, 23.2, 23.2, 23.2, 4

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20140101','ПФ Страховая часть',999999999, 0, 0, 0, 4
GO


-- --ПФ Накопительная часть УБИРАЕМ
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 7 --ПФ Накопительная часть
IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 4)								/* 415000  */
DELETE FROM dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 4

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4)
DELETE FROM dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4
GO


DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1 
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20140101','ПФ Доп.тариф №1',999999999,  6, 6, 6, 4
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 4),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20140101','ПФ Доп.тариф №2',999999999, 4, 4, 4, 4
GO


--Упрощён. (ПНЭД)
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 2 --Фонд Социального Страхования
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 2),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20140101','ФСС РФ',624000, 0, 2

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20140101','ФСС РФ',999999999, 0, 2
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 3 --Федеральный фонд медицинского страхования
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 2),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20140101','ФФОМС',624000, 0, 2

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20140101','ФФОМС',999999999, 0, 2
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 6 --ПФ Страховая часть
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 2),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20140101','ПФ Страховая часть',624000, 20, 20, 20, 2

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20140101','ПФ Страховая часть',999999999, 0, 0, 0, 2
GO


-- --ПФ Накопительная часть УБИРАЕМ
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 7 --ПФ Накопительная часть
IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 2)								/* 415000  */
DELETE FROM dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 2

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2)
DELETE FROM dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2
GO


-- --ПФ Солидарная часть УБИРАЕМ
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 8 --ПФ Солидарная часть
IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 2)								/* 415000  */
DELETE FROM dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF = 2

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2)
DELETE FROM dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2
GO


--ПФ Индивидуальная часть УБИРАЕМ
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 9 --ПФ Индивидуальная часть
IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF =2)								/* 415000  */
DELETE from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 624000 AND TARIF =2

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2)
delete from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1 
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20140101','ПФ Доп.тариф №1',999999999,  6, 6, 6, 2
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20140101' and predel = 999999999 AND TARIF = 2),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20140101','ПФ Доп.тариф №2',999999999, 4, 4, 4, 2
GO


EXEC X_SET_PROP 'DSTA_POST_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_POST",oobj.parent.parent.recordsource,"LINK, CODE,NAME", "POST_LINK,POST_CODE, POST_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DSTA_POST_NAME', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_POST",oobj.parent.parent.recordsource,"LINK, CODE,NAME", "POST_LINK,POST_CODE, POST_NAME", "", "", "", .T., 1, oForm, oObj)'
GO

GO
IF NOT EXISTS (SELECT * FROM dbo.S_BANK_FORMAT_BASE WHERE CODE = 'FULLNAME')
	INSERT INTO dbo.S_BANK_FORMAT_BASE (CODE, NAME, FTYPE, FVALUE, DATATYPE)
	VALUES ('FULLNAME','Полное наименование организации',1,'','C')
GO


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




GO
-- 'EOD_EXPORT_INV1', 'Выгрузка данных об ОС' --
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='EOD_EXPORT_INV1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'EOD_EXPORT_INV1', 'Выгрузка данных об ОС', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='EOD_CATALOG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'EOD_EXPORT_INV1', NAME = 'Выгрузка данных об ОС', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='EOD_CATALOG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='EOD_EXPORT_INV1'
GO
EXEC X_SET_PROP 'EOD_EXPORT_INV1', 'TITLE', 'Выгрузка данных об ОС'
GO
EXEC X_SET_PROP 'EOD_EXPORT_INV1', 'INIT_OBJECT_METHOD', 'export_files ("dbo.BK_VIEW_EXPORT_FORMAT_NALOG_FN (default) WHERE FORM_CODE = ''EOD_EXPORT_INV1''", oForm.alter_exec_param)'
GO
EXEC X_SET_PROP 'EOD_EXPORT_INV1', 'ACTIVATE_METHOD', ''
GO
EXEC X_SET_PROP 'EOD_EXPORT_INV1', 'HELP_TOPIC', 'Выгрузка данных об ОС'
GO


GO
/****** Объект: Код по ОКАТО******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SUBDIVISION_O_OKATO')
	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_O_OKATO')
	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_O_OKATO')
	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_O_OKATO')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SUBDIVISION_O_OKATO'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SUBDIVISION_O_OKATO')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SUBDIVISION_O_OKATO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SUBDIVISION_O_OKATO', 'Код по ОКАТО/ОКТМО', 10, (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_O_OKATO', NAME = 'Код по ОКАТО/ОКТМО', ORDERS = '10', 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_O_OKATO'
GO
EXEC X_SET_PROP 'SUBDIVISION_O_OKATO', 'TITLE', 'Код по ОКАТО/ОКТМО'
GO
EXEC X_SET_PROP 'SUBDIVISION_O_OKATO', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'SUBDIVISION_O_OKATO', 'CONTROLSOURCE', 'm.cAlias + ".O_OKATO"'
GO
EXEC X_SET_PROP 'SUBDIVISION_O_OKATO', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SUBDIVISION_O_OKATO', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".O_OKATO"'
GO
EXEC X_SET_PROP 'SUBDIVISION_O_OKATO', 'CONTROL_NAME_EDIT', 'Atxt8'
GO
EXEC X_SET_PROP 'SUBDIVISION_O_OKATO', 'INPUT_MASK', '## ### ### ###'
GO
EXEC X_SET_PROP 'SUBDIVISION_O_OKATO', 'COMMENTARY', 'Для обособленного подразделения код по ОКАТО/ОКТМО.'
GO

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


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (фев 10 2014  4:55:33:770PM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0606010 (П-4.(мес) Сведения о численности и заработной плате работников)
-- Дата ввода : 20130101
-- Дата окончания действия :
-- Версия : 2014-02-10 16:55:33.730
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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] = '0606010' AND [START_DATE] = '20130101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-02-10 16:55:33.730',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_' + '0606010',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 = '0606010'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20130101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SALARY'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'П-4.(мес) Сведения о численности и заработной плате работников',@vcNEW_FORM_CODE,@dNEW_START_DATE,6,1,1,1,2291,'i_report_export_nalog',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, '','Svod_F_P42013.bas','print_P42010_add_data()','KirRepMakerMultiSheet.xls','svod_P42013.XLT','',NULL,'i_report_export_nalog',0,NULL,NULL,NULL,'          ','REPORTS_FILTER_SUBDIV',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,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'№ строки',@iLINK_TABLE,1,1,1,0,250,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Код по ОКВЭД',@iLINK_TABLE,1,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, 4,'Ср.числ.за отч.м-ц. Всего',@iLINK_TABLE,1,0,4,8,1,1,NULL,NULL,NULL,'999 999 999 999 999.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, 5,'Ср.числ.за отч.м-ц. Списоч.состав',@iLINK_TABLE,1,0,5,1,1,1,NULL,NULL,NULL,'999 999 999 999 999.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, 6,'Ср.числ.за отч.м-ц. Внеш.совместителей',@iLINK_TABLE,1,0,6,2,1,1,NULL,NULL,NULL,'999 999 999 999 999.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, 7,'Ср.числ.за отч.м-ц. По договорам',@iLINK_TABLE,1,0,7,3,1,1,NULL,NULL,NULL,'999 999 999 999 999.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, 8,'Кол-во ч/часов. Списоч состав',@iLINK_TABLE,1,0,8,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, 9,'Кол-во ч/часов. Внеш. совместителей',@iLINK_TABLE,1,0,9,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, 10,'Фонд з/пл.за отч.м-ц. Всего',@iLINK_TABLE,1,0,10,14,1,1,NULL,NULL,NULL,'999 999 999 999 999.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, 11,'Фонд з/пл.за отч.м-ц. Списоч. состав',@iLINK_TABLE,1,0,11,7,1,1,NULL,NULL,NULL,'999 999 999 999 999.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, 12,'Фонд з/пл.за отч.м-ц. Внеш.совместителей',@iLINK_TABLE,1,0,12,8,1,1,NULL,NULL,NULL,'999 999 999 999 999.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, 13,'Фонд з/пл.за отч.м-ц. По договорам',@iLINK_TABLE,1,0,13,9,1,1,NULL,NULL,NULL,'999 999 999 999 999.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, 14,'Выплаты соц. характера',@iLINK_TABLE,1,0,14,11,1,1,NULL,NULL,NULL,'999 999 999 999 999.9',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Численность и начисленная заработная плата работни', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (1,1,12,1)
INSERT #R VALUES (2,1,1,1)
INSERT #R VALUES (3,1,2,1)
INSERT #R VALUES (4,1,3,1)
INSERT #R VALUES (5,1,4,1)
INSERT #R VALUES (6,1,5,1)
INSERT #R VALUES (7,1,7,1)
INSERT #R VALUES (8,1,8,1)
INSERT #R VALUES (9,1,9,1)
INSERT #R VALUES (10,1,10,1)
INSERT #R VALUES (11,1,11,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 11
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,1,1,'Всего (сумма строк с 02 по 11)                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,2,1,'в том числе по видам деятельности:                                                                                                                                                                                                                        ')
INSERT #F VALUES (1,1,2,'01                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (1,2,2,'02                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (1,3,2,'03                                                                                                                                                                                                                                                        ')
INSERT #F VALUES (1,4,2,'04')
INSERT #F VALUES (1,5,2,'05')
INSERT #F VALUES (1,6,2,'06')
INSERT #F VALUES (1,7,2,'07')
INSERT #F VALUES (1,8,2,'08')
INSERT #F VALUES (1,9,2,'09')
INSERT #F VALUES (1,10,2,'10')
INSERT #F VALUES (1,11,2,'11')
INSERT #F VALUES (1,1,3,'П4_ЗНАЧЕНИЕ2(1)')
INSERT #F VALUES (1,2,3,'П4_УСТАНОВКА()  + П4_ЗНАЧЕНИЕ2(1)')
INSERT #F VALUES (1,1,4,'ИТОГ("02^11")')
INSERT #F VALUES (1,2,4,'ГР(5)+ГР(6)+ГР(7)')
INSERT #F VALUES (1,3,4,'ГР(5)+ГР(6)+ГР(7)')
INSERT #F VALUES (1,4,4,'ГР(5)+ГР(6)+ГР(7)                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,5,4,'ГР(5)+ГР(6)+ГР(7)                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,6,4,'ГР(5)+ГР(6)+ГР(7)                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,7,4,'ГР(5)+ГР(6)+ГР(7)                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,8,4,'ГР(5)+ГР(6)+ГР(7)                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,9,4,'ГР(5)+ГР(6)+ГР(7)                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,10,4,'ГР(5)+ГР(6)+ГР(7)                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,11,4,'ГР(5)+ГР(6)+ГР(7)                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,1,5,'ИТОГ("02^11")')
INSERT #F VALUES (1,2,5,'П4_ЗНАЧЕНИЕ(2)')
INSERT #F VALUES (1,3,5,'0')
INSERT #F VALUES (1,4,5,'0                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,5,5,'0                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,6,5,'0                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,7,5,'0                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,8,5,'0                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,9,5,'0                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,10,5,'0                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,11,5,'0                                                                                                                                                                                                                                                         ')
INSERT #F VALUES (1,1,6,'ИТОГ("02^11")')
INSERT #F VALUES (1,2,6,'П4_ЗНАЧЕНИЕ(3)')
INSERT #F VALUES (1,1,7,'ИТОГ("02^11")')
INSERT #F VALUES (1,2,7,'П4_ЗНАЧЕНИЕ(4)')
INSERT #F VALUES (1,1,8,'ИТОГ("02^11")')
INSERT #F VALUES (1,2,8,'П4_ЗНАЧЕНИЕ(5)')
INSERT #F VALUES (1,1,9,'ИТОГ("02^11")')
INSERT #F VALUES (1,2,9,'П4_ЗНАЧЕНИЕ(6)')
INSERT #F VALUES (1,1,10,'ИТОГ("02^11")')
INSERT #F VALUES (1,2,10,'ГР(11)+ГР(12)+ГР(13)')
INSERT #F VALUES (1,3,10,'ГР(11)+ГР(12)+ГР(13)')
INSERT #F VALUES (1,4,10,'ГР(11)+ГР(12)+ГР(13)                                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,5,10,'ГР(11)+ГР(12)+ГР(13)                                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,6,10,'ГР(11)+ГР(12)+ГР(13)                                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,7,10,'ГР(11)+ГР(12)+ГР(13)                                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,8,10,'ГР(11)+ГР(12)+ГР(13)                                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,9,10,'ГР(11)+ГР(12)+ГР(13)                                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,10,10,'ГР(11)+ГР(12)+ГР(13)                                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,11,10,'ГР(11)+ГР(12)+ГР(13)                                                                                                                                                                                                                                      ')
INSERT #F VALUES (1,1,11,'ИТОГ("02^11")')
INSERT #F VALUES (1,2,11,'П4_ЗНАЧЕНИЕ(8)')
INSERT #F VALUES (1,1,12,'ИТОГ("02^11")')
INSERT #F VALUES (1,2,12,'П4_ЗНАЧЕНИЕ(9)')
INSERT #F VALUES (1,1,13,'ИТОГ("02^11")')
INSERT #F VALUES (1,2,13,'П4_ЗНАЧЕНИЕ(10)')
INSERT #F VALUES (1,1,14,'ИТОГ("02^11")')
INSERT #F VALUES (1,2,14,'П4_ЗНАЧЕНИЕ(11)')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 64
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'т.1стр.01 =  т.1стр.02 +  т.1стр.11',0,0,1,'20130315','','','','0606010','20130101','','=',0,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 1
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','01','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','02','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'^',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','11','1',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 3
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-02-10 16:55:33.730',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-02-10 16:55:33.730'
	BEGIN
		SELECT @vcMessage = 'Форма 0606010 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0606010 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-02-10 16:55:33.730. Обновление отклонено.'
	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(163,'УКАЗАНИЯ ПО ЗАПОЛНЕНИЮ ФОРМЫ ФЕДЕРАЛЬНОГО СТАТИСТИЧЕСКОГО НАБЛЮДЕНИЯ3519.MHT', 'D:\TEMP', convert(datetime, '2013-08-22 11:17:00.000', 121), 44841)
insert #F2 (File_ID, Orders, Body) values(163,1, 'MIME-Version: 1.0
Content-Type: multipart/related; boundary="----=_NextPart_01CE0AC0.C28A86A0"

Данный документ является веб-страницей в одном файле, также называемой файлом веб-архива. Если вы видите это сообщение, значит, данный браузер или редактор не поддерживает файлы веб-архива. Загрузите браузер, поддерживающий веб-архивы, например Windows® Internet Explorer®.

------=_NextPart_01CE0AC0.C28A86A0
Content-Location: file:///C:/A16BFF4F/file9487.htm
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset="windows-1251"

<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=3Dwindows-125=
1">
<meta name=3DProgId content=3DWord.Document>
<meta name=3DGenerator content=3D"Microsoft Word 14">
<meta name=3DOriginator content=3D"Microsoft Word 14">
<link rel=3DFile-List href=3D"file9487.files/filelist.xml">
<!--[if gte mso 9]><xml>
 <o:DocumentProperties>
  <o:Author>Игнатьев Алексей Николаевич</o:Author>
  <o:Template>Normal</o:Template>
  <o:LastAuthor>Игнатьев Алексей Николаевич</o:LastAuthor>
  <o:Revision>1</o:Revision>
  <o:TotalTime>2</o:TotalTime>
  <o:Created>2013-02-14T10:35:00Z</o:Created>
  <o:LastSaved>2013-02-14T10:37:00Z</o:LastSaved>
  <o:Pages>2</o:Pages>
  <o:Words>728</o:Words>
  <o:Characters>4155</o:Characters>
  <o:Lines>34</o:Lines>
  <o:Paragraphs>9</o:Paragraphs>
  <o:CharactersWithSpaces>4874</o:CharactersWithSpaces>
  <o:Version>14.00</o:Version>
 </o:DocumentProperties>
 <o:OfficeDocumentSettings>
  <o:AllowPNG/>
 </o:OfficeDocumentSettings>
</xml><![endif]-->
<link rel=3DthemeData href=3D"file9487.files/themedata.thmx">
<link rel=3DcolorSchemeMapping href=3D"file9487.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:EnableOpenTypeKerning/>
   <w:DontFlipMirrorIndents/>
   <w:OverrideTableStyleHps/>
  </w:Compatibility>
  <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" SemiHidden=3D"false" UnhideWhenUsed=3D"f=
alse"
   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"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=')

insert #F2 (File_ID, Orders, Body) values(163,2, '
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:LsdException 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 Li')

insert #F2 (File_ID, Orders, Body) values(163,3, 'st
 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:Calibri;
	panose-1:2 15 5 2 2 2 4 3 2 4;
	mso-font-charset:204;
	mso-generic-font-family:swiss;
	mso-font-pitch:variable;
	mso-font-signature:-536870145 1073786111 1 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:11.0pt;
	font-family:"Calibri","sans-serif";
	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;}
h1
	{mso-style-priority:99;
	mso-style-unhide:no;
	mso-style-qformat:yes;
	mso-style-link:"Заголовок 1 Знак";
	mso-style-next:Обычный;
	margin-top:5.4pt;
	margin-right:0cm;
	margin-bottom:5.4pt;
	margin-left:0cm;
	text-align:center;
	mso-pagination:widow-orphan;
	mso-outline-level:1;
	mso-layout-grid-align:none;
	text-autospace:none;
	font-size:12.0pt;
	font-family:"Arial","sans-serif";
	color:#26282F;
	mso-font-kerning:0pt;
	mso-fareast-language:EN-US;}
p.ConsPlusNormal, li.ConsPlusNormal, div.ConsPlusNormal
	{mso-style-name:ConsPlusNormal;
	mso-style-unhide:no;
	mso-style-parent:"";
	margin:0cm;
	margin-bottom:.0001pt;
	text-indent:36.0pt;
	mso-pagination:none;
	mso-layout-grid-align:none;
	text-autospace:none;
	font-size:10.0pt;
	font-family:"Arial","sans-serif";
	m')

insert #F2 (File_ID, Orders, Body) values(163,4, 'so-f
areast-font-family:"Times New Roman";
	mso-fareast-theme-font:minor-fareast;}
p.ConsPlusNonformat, li.ConsPlusNonformat, div.ConsPlusNonformat
	{mso-style-name:ConsPlusNonformat;
	mso-style-priority:99;
	mso-style-unhide:no;
	mso-style-parent:"";
	margin:0cm;
	margin-bottom:.0001pt;
	mso-pagination:none;
	mso-layout-grid-align:none;
	text-autospace:none;
	font-size:10.0pt;
	font-family:"Courier New";
	mso-fareast-font-family:"Times New Roman";
	mso-fareast-theme-font:minor-fareast;}
span.1
	{mso-style-name:"Заголовок 1 Знак";
	mso-style-priority:99;
	mso-style-unhide:no;
	mso-style-locked:yes;
	mso-style-link:"Заголовок 1";
	mso-ansi-font-size:12.0pt;
	mso-bidi-font-size:12.0pt;
	font-family:"Arial","sans-serif";
	mso-ascii-font-family:Arial;
	mso-hansi-font-family:Arial;
	mso-bidi-font-family:Arial;
	color:#26282F;
	font-weight:bold;}
span.a
	{mso-style-name:"Гипертекстовая ссылка";
	mso-style-priority:99;
	mso-style-unhide:no;
	color:#106BBE;}
span.GramE
	{mso-style-name:"";
	mso-gram-e:yes;}
.MsoChpDefault
	{mso-style-type:export-only;
	mso-default-props:yes;
	font-family:"Calibri","sans-serif";
	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;}
@page WordSection1
	{size:595.0pt 840.0pt;
	margin:72.0pt 40.0pt 72.0pt 55.0pt;
	mso-header-margin:36.0pt;
	mso-footer-margin:36.0pt;
	mso-paper-source:0;}
div.WordSection1
	{page:WordSection1;}
-->
</style>
<!--[if gte mso 10]>
<style>
 /* Style Definitions */
 table.MsoNormalTable
	{mso-style-name:"Обычная таблица";
	mso-tstyle-rowband-size:0;
	mso-tstyle-colband-size:0;
	mso-style-noshow:yes;
	mso-style-priority:99;
	mso-style-parent:"";
	mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
	mso-para-margin:0cm;
	mso-para-margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size: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-fareast-language:EN-US;}
</style>
<![endif]--><!--[if gte mso 9]><xml>
 <o:shapedefaults v:ext=3D"edit" spidmax=3D"1026"/>
</xml><![endif]--><!--[if gte mso 9]><xml>
 <o:shapelayout v:ext=3D"edit">
  <o:idmap v:ext=3D"edit" data=3D"1"/>
 </o:shapelayout></xml><![endif]-->
</head>

<body lang=3DRU style=3D''tab-interval:35.4pt''>

<div class=3DWordSection1>

<p class=3DMsoNormal align=3Dcenter style=3D''margin-top:5.4pt;margin-right:=
0cm;
margin-bottom:5.4pt;margin-left:0cm;text-align:center;mso-outline-level:1;
mso-layout-grid-align:none;text-autospace:none''><a name=3D"sub_50000"><b><s=
pan
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif";color:#26282F''>У=
казания
по заполнению формы федерального статистического наблюдения<o:p></o:p></spa=
n></b></a></p>

<span style=3D''mso-bookmark:sub_50000''></span>

<p class=3DMsoNormal style=3D''text-align:justify;text-indent:36.0pt;mso-lay=
out-grid-align:
none;text-autospace:none''><span style=3D''font-size:13.0pt;font-family:"Aria=
l","sans-serif"''><o:p>&nbsp;</o:p></span></p>

<p class=3DMsoNormal style=3D''text-align:justify;text-indent:36.0pt;mso-lay=
out-grid-align:
none;text-autospace:none''><a name=3D"sub_50001"><span style=3D''font-size:13=
.0pt;
font-family:"Arial","sans-serif"''>1. Форму федерального статистического
наблюдения </span></a><a href=3D"#sub_5000"><span style=3D''mso-bookmark:sub=
_50001''><span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif";color:#106BBE;
text-decoration:none;text-underline:none''>N&nbsp;П-4</span></span><span
style=3D''mso-bookmark:sub_50001''></span></a><span style=3D''mso-bookmark:sub=
_50001''><span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif"''> заполняют
юридические лица - коммерческие и некоммерческие организации (кроме субъект=
ов
малого предпринимательства) всех видов экономической деятельности и форм
собственности и предоставляют в территориальный орган Росстата по месту сво=
его
нахождения в сроки и адреса, указанные на бланке формы.<o:p></o:p></span></=
span></p>

<span style=3D''mso-bookmark:sub_50001''></span>

<p class=3DMsoNormal style=3D''text-align:justify;text-indent:36.0pt;mso-lay=
out-grid-align:
none;text-autospace:none''><span style=3D''font-size:13.0pt;font-family:"Aria=
l","sans-serif"''>Для
юридических лиц, средняя численность работников которых не превышает 15
человек, общественных организаций, дачных, садоводческих, гаражных,
жилищно-строительных кооперативов и т.п. по указанию территориального органа
Росстата в субъекте Российской Федерации может устанавливаться периодичност=
ь предоставления
сведений один раз в год по форме N&nbsp;1-Т &quot;Сведения о численности и
заработной плате работников&quot;.<o:p></o:p></span></p>

<p class=3DMsoNormal style=3D''text-align:justify;text-indent:36.0pt;mso-lay=
out-grid-align:
none;text-autospace:none''><a name=3D"sub_50002"><span style=3D''font-size:13=
.0pt;
font-family:"Arial","sans-serif"''>2. При налич</span></a><span class=3DGram=
E><span
style=3D''mso-bookmark:sub_50002''><span style=3D''font-size:13.0pt;font-famil=
y:"Arial","sans-serif"''>ии
у ю</span></span></span><span style=3D''mso-bookmark:sub_50002''><span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif"''>ридического лица
обособленных подразделений настоящая форма заполняется как по каждому
обособленному подразделению, так и по юридическому лицу без этих обособленн=
ых
подразделений.<o:p></o:p></span></span></p>

<span style=3D''mso-bookmark:sub_50002''></span>

<p class=3DMsoNormal style=3D''text-align:justify;text-indent:36.0pt;mso-lay=
out-grid-align:
none;text-autospace:none''><a name=3D"sub_50003"><span style=3D''font-size:13=
.0pt;
font-family:"Arial","sans-serif"''>3. Организации-банкроты, на которых введе=
но </span></a><span
class=3DGramE><span style=3D''mso-bookmark:sub_50003''><span style=3D''font-si=
ze:13.0pt;
font-family:"Arial","sans-serif"''>конкурсное</span></span></span><span
style=3D''mso-bookmark:sub_50003''><span style=3D''font-size:13.0pt;font-famil=
y:"Arial","sans-serif"''>
управление, не освобождаются от предоставления сведений по указанной форме.
Только после вынесения определения арбитражного суда о завершении в отношен=
ии
организации конкурсного производства и внесения в единый государственный ре=
естр
юридических лиц записи о его ликвидации (</span></span><a
href=3D"garantf1://85181.1493/"><span style=3D''mso-bookmark:sub_50003''><span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif";color:#106BBE;
text-decoration:none;text-underline:none''>п. 3 ст. 149</span></span><span
style=3D''mso-bookmark:sub_50003''></span></a><span style=3D''mso-bookmark:sub=
_50003''><span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif"''> Федерального з=
акона
от 26.10.2002 N&nbsp;127-ФЗ &quot;О несостоятельности (банкротстве)&quot;)
организация-должник считается ликвидированной и освобождается от предоставл=
ения
сведений по форме N&nbsp;П-4.<o:p></o:p></span></span></p>

<span style=3D''mso-bookmark:sub_50003''></span>

<p class=3DMsoNormal style=3D''text-align:justify;text-indent:36.0pt;mso-lay=
out-grid-align:
none;text-autospace:none''><a name=3D"sub_50004"><span style=3D''font-size:13=
')

insert #F2 (File_ID, Orders, Body) values(163,5, '.0pt;


font-family:"Arial","sans-serif"''>4. Заполненные </span></a><a href=3D"#sub=
_5000"><span
style=3D''mso-bookmark:sub_50004''><span style=3D''font-size:13.0pt;font-famil=
y:"Arial","sans-serif";
color:#106BBE;text-decoration:none;text-underline:none''>формы</span></span>=
<span
style=3D''mso-bookmark:sub_50004''></span></a><span style=3D''mso-bookmark:sub=
_50004''><span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif"''> предоставляются
юридическим лицом в территориальные органы Росстата по месту нахождения
соответствующего обособленного подразделения (по обособленному подразделени=
ю) и
по месту нахождения юридического лица (без обособленных подразделений). В
случае, когда юридическое лицо (его обособленное подразделение) не осуществ=
ляет
деятельность по месту своего нахождения, форма предоставляется по месту
фактического осуществления ими деятельности.<o:p></o:p></span></span></p>

<span style=3D''mso-bookmark:sub_50004''></span>

<p class=3DMsoNormal style=3D''text-align:justify;text-indent:36.0pt;mso-lay=
out-grid-align:
none;text-autospace:none''><a name=3D"sub_50005"><span style=3D''font-size:13=
.0pt;
font-family:"Arial","sans-serif"''>5. Руководитель юридического лица назнача=
ет
должностных лиц, уполномоченных предоставлять статистическую информацию от
имени юридического лица.<o:p></o:p></span></a></p>

<span style=3D''mso-bookmark:sub_50005''></span>

<p class=3DMsoNormal style=3D''text-align:justify;text-indent:36.0pt;mso-lay=
out-grid-align:
none;text-autospace:none''><a name=3D"sub_50006"><span style=3D''font-size:13=
.0pt;
font-family:"Arial","sans-serif"''>6. В </span></a><a href=3D"#sub_50100"><s=
pan
style=3D''mso-bookmark:sub_50006''><span style=3D''font-size:13.0pt;font-famil=
y:"Arial","sans-serif";
color:#106BBE;text-decoration:none;text-underline:none''>адресной части</spa=
n></span><span
style=3D''mso-bookmark:sub_50006''></span></a><span style=3D''mso-bookmark:sub=
_50006''><span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif"''> формы указывае=
тся
полное наименование отчитывающейся организации в соответствии с учредительн=
ыми
документами, зарегистрированными в установленном порядке, а затем в скобках=
 -
краткое наименование. На бланке формы, содержащей сведения по обособленному
подразделению юридического лица, указывается наименование обособленного
подразделения и юридического лица, к которому оно относится.<o:p></o:p></sp=
an></span></p>

<span style=3D''mso-bookmark:sub_50006''></span>

<p class=3DMsoNormal style=3D''text-align:justify;text-indent:36.0pt;mso-lay=
out-grid-align:
none;text-autospace:none''><span class=3DGramE><span style=3D''font-size:13.0=
pt;
font-family:"Arial","sans-serif"''>По <a href=3D"#sub_50200"><span
style=3D''color:#106BBE;text-decoration:none;text-underline:none''>строке</sp=
an></a>
&quot;Почтовый адрес&quot; указывается наименование субъекта Российской
Федерации, юридический адрес с почтовым индексом; если фактический адрес не
совпадает с юридическим, то указывается также фактический почтовый адрес.</=
span></span><span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif"''> Для обособленн=
ых
подразделений, не имеющих юридического адреса, указывается почтовый адрес с
почтовым индексом.<o:p></o:p></span></p>

<p class=3DMsoNormal style=3D''text-align:justify;text-indent:36.0pt;mso-lay=
out-grid-align:
none;text-autospace:none''><span style=3D''font-size:13.0pt;font-family:"Aria=
l","sans-serif"''>Юридическое
лицо проставляет в <a href=3D"#sub_50300"><span style=3D''color:#106BBE;text=
-decoration:
none;text-underline:none''>кодовой части</span></a> формы код Общероссийского
классификатора предприятий и организаций (ОКПО) на основании Уведомления о =
присвоении
кода ОКПО, направляемого (выдаваемого) организациям территориальными органа=
ми
Росстата.<o:p></o:p></span></p>

<p class=3DMsoNormal style=3D''text-align:justify;text-indent:36.0pt;mso-lay=
out-grid-align:
none;text-autospace:none''><span style=3D''font-size:13.0pt;font-family:"Aria=
l","sans-serif"''>По
территориально-обособленным подразделениям юридического лица указывается
идентификационный номер, который устанавливается территориальным органом
Росстата по месту расположения территориально-обособленного подразделения.<=
o:p></o:p></span></p>

<p class=3DMsoNormal style=3D''text-align:justify;text-indent:36.0pt;mso-lay=
out-grid-align:
none;text-autospace:none''><span style=3D''font-size:13.0pt;font-family:"Aria=
l","sans-serif"''>При
предоставлении нескольких отчетов органами управления образованием,
здравоохранением, культурой субъектов Российской Федерации, муниципальных
районов, городских округов и внутригородских территорий городов федерального
значения в кодовой части формы указывается идентификационный номер, который
устанавливается территориальным органом Росстата по месту расположения орга=
нов
управления.<o:p></o:p></span></p>

<p class=3DMsoNormal style=3D''text-align:justify;text-indent:36.0pt;mso-lay=
out-grid-align:
none;text-autospace:none''><a name=3D"sub_50007"><span style=3D''font-size:13=
.0pt;
font-family:"Arial","sans-serif"''>7. Сведения приводятся в целом по организ=
ации
и по фактическим видам экономической деятельности о численности работников и
начисленной заработной плате за отчетный месяц или за период с начала года;=
 о
количестве отработанных человеко-часов и выплатах социального характера -
ежеквартально, за период с начала года.<o:p></o:p></span></a></p>

<span style=3D''mso-bookmark:sub_50007''></span>

<p class=3DMsoNormal style=3D''text-align:justify;text-indent:36.0pt;mso-lay=
out-grid-align:
none;text-autospace:none''><a name=3D"sub_50008"><span style=3D''font-size:13=
.0pt;
font-family:"Arial","sans-serif"''>8. Если организации в отчетном месяце не
начисляли заработную плату и другие выплаты, то сведения по </span></a><a
href=3D"#sub_5000"><span style=3D''mso-bookmark:sub_50008''><span style=3D''fo=
nt-size:
13.0pt;font-family:"Arial","sans-serif";color:#106BBE;text-decoration:none;
text-underline:none''>форме N&nbsp;П-4</span></span><span style=3D''mso-bookm=
ark:
sub_50008''></span></a><span style=3D''mso-bookmark:sub_50008''><span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif"''> предоставляютс=
я без
заполнения этих данных.<o:p></o:p></span></span></p>

<span style=3D''mso-bookmark:sub_50008''></span>

<p class=3DMsoNormal style=3D''text-align:justify;text-indent:36.0pt;mso-lay=
out-grid-align:
none;text-autospace:none''><a name=3D"sub_50009"><span style=3D''font-size:13=
.0pt;
font-family:"Arial","sans-serif"''>9. Более подробные методологические указа=
ния
по заполнению и контроль правильности заполнения формы приведены в </span><=
/a><a
href=3D"garantf1://12063886.12400/"><span style=3D''mso-bookmark:sub_50009''>=
<span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif";color:#106BBE;
text-decoration:none;text-underline:none''>Указаниях</span></span><span
style=3D''mso-bookmark:sub_50009''></span></a><span style=3D''mso-bookmark:sub=
_50009''><span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif"''> по заполнению =
форм
федерального статистического наблюдения </span></span><a
href=3D"garantf1://12070841.5000/"><span style=3D''mso-bookmark:sub_50009''><=
span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif";color:#106BBE;
text-decoration:none;text-underline:none''>NN&nbsp;П-1</span></span><span
style=3D''mso-bookmark:sub_50009''></span></a><span style=3')

insert #F2 (File_ID, Orders, Body) values(163,6, 'D''mso-book
mark:sub=
_50009''><span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif"''>, </span></span=
><a
href=3D"garantf1://1869668.5000/"><span style=3D''mso-bookmark:sub_50009''><s=
pan
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif";color:#106BBE;
text-decoration:none;text-underline:none''>П-2</span></span><span
style=3D''mso-bookmark:sub_50009''></span></a><span style=3D''mso-bookmark:sub=
_50009''><span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif"''>, </span></span=
><a
href=3D"garantf1://1869665.8000/"><span style=3D''mso-bookmark:sub_50009''><s=
pan
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif";color:#106BBE;
text-decoration:none;text-underline:none''>П-3</span></span><span
style=3D''mso-bookmark:sub_50009''></span></a><span style=3D''mso-bookmark:sub=
_50009''><span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif"''>, </span></span=
><a
href=3D"garantf1://12089520.6000/"><span style=3D''mso-bookmark:sub_50009''><=
span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif";color:#106BBE;
text-decoration:none;text-underline:none''>П-4</span></span><span
style=3D''mso-bookmark:sub_50009''></span></a><span style=3D''mso-bookmark:sub=
_50009''><span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif"''>, </span></span=
><a
href=3D"garantf1://12069078.12000/"><span style=3D''mso-bookmark:sub_50009''>=
<span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif";color:#106BBE;
text-decoration:none;text-underline:none''>П-5(м)</span></span><span
style=3D''mso-bookmark:sub_50009''></span></a><span style=3D''mso-bookmark:sub=
_50009''><span
style=3D''font-size:13.0pt;font-family:"Arial","sans-serif"''>.<o:p></o:p></s=
pan></span></p>

<span style=3D''mso-bookmark:sub_50009''></span>

<p class=3DMsoNormal><o:p>&nbsp;</o:p></p>

</div>

</body>

</html>

------=_NextPart_01CE0AC0.C28A86A0
Content-Location: file:///C:/A16BFF4F/file9487.files/themedata.thmx
Content-Transfer-Encoding: base64
Content-Type: application/vnd.ms-officetheme

[encoded data, 4180 characters]

------=_NextPart_01CE0AC0.C28A86A0
Content-Location: file:///C:/A16BFF4F/file9487.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_01CE0AC0.C28A86A0
Content-Location: file:///C:/A16BFF4F/file9487.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"../file9487.htm"/>
 <o:File HRef=3D"themedata.thmx"/>
 <o:File HRef=3D"colorschememapping.xml"/>
 <o:File HRef=3D"filelist.xml"/>
</xml>
------=_NextPart_01CE0AC0.C28A86A0--
')

IF (SELECT COUNT(*) FROM #F2) <> 6
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F2',0)
END
ELSE
	exec dbo.RO_IMPORT_FORM_HINT @iLINK_FORM
drop table #F1
drop table #F2


GO

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL DROP TABLE #tabInfo
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog
DROP TABLE #tabStop

COMMIT TRANSACTION -- Фиксация транзакции.
GO


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (фев  7 2014  9:17:06:870AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0606045 (Сведения о численности и оплате труда работников сферы здравоохранения по категориям персонала)
-- Дата ввода : 20130601
-- Дата окончания действия :
-- Версия : 2014-02-07 09:17:06.860
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = '0606045' AND [START_DATE] = '20130601'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-02-07 09:17:06.860',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '0606045',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '0606045'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20130601')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SALARY'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Сведения о численности и оплате труда работников сферы здравоохранения по категориям персонала',@vcNEW_FORM_CODE,@dNEW_START_DATE,6,1,1,1,2291,'RA_EXPORT_FORM',0,0,'19000101',NULL,''
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, '','sv_0606049_20130101.bas','','KirRepMakerMultiSheet.xls','sv_0606045_20130101.xlt','',NULL,'RA_EXPORT_FORM',0,NULL,NULL,NULL,'          ','REPORTS_ATR_TYPE_ORG,REPORTS_FILTER_SUBDIV',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Таблица', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Категория персонала',@iLINK_TABLE,0,1,1,0,2000,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код категории персонала',@iLINK_TABLE,1,1,2,0,3,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'№ строки',@iLINK_TABLE,1,1,3,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Средняя численность работников, человек: списочного состава',@iLINK_TABLE,1,0,4,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Средняя численность работников, человек:внешних совместителей',@iLINK_TABLE,1,0,5,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Фонд начисленной ЗП работников за отчетный период списочного состава:всего',@iLINK_TABLE,1,0,6,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Фонд начисленной ЗП работников за отчетный период списочного состава:в том числе по внутреннему совместительству',@iLINK_TABLE,1,0,7,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Фонд начисленной ЗП работников за отчетный период списочного состава: внешних совместителей',@iLINK_TABLE,1,0,8,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Фонд начисленной ЗП работников по источникам финансирования(из гр.3) за счет средств бюджетов всех уровней',@iLINK_TABLE,1,0,9,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Фонд начисленной ЗП работников по источникам финансирования(из гр. 3) ОМС',@iLINK_TABLE,1,0,10,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Фонд начисленной ЗП работников по источникам финансирования(из гр.3) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,11,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) за счет средств бюджетов всех уровней',@iLINK_TABLE,1,0,12,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ОМС',@iLINK_TABLE,1,0,13,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,14,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Таблица', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (1,1,1,1)
INSERT #R VALUES (2,1,4,1)
INSERT #R VALUES (3,1,5,1)
INSERT #R VALUES (4,1,6,1)
INSERT #R VALUES (5,1,7,1)
INSERT #R VALUES (6,1,8,1)
INSERT #R VALUES (7,1,9,1)
INSERT #R VALUES (8,1,10,1)
INSERT #R VALUES (9,1,11,1)
INSERT #R VALUES (10,1,12,1)
INSERT #R VALUES (11,1,13,1)
INSERT #R VALUES (12,1,14,1)
INSERT #R VALUES (13,1,14,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 13
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,1,1,'Всего работников (сумма строк 02 - 04, 06 - 08, 10 - 13)')
INSERT #F VALUES (1,2,1,'в том числе: руководитель организации')
INSERT #F VALUES (1,3,1,'заместители руководителя и руководители структурных подразделений (кроме врачей - руководителей структурных подразделений), иные руководители')
INSERT #F VALUES (1,4,1,'педагогические работники')
INSERT #F VALUES (1,5,1,'из них преподаватели')
INSERT #F VALUES (1,6,1,'врачи (кроме зубных), включая врачей - руководителей структурных подразделений')
INSERT #F VALUES (1,7,1,'социальные работники')
INSERT #F VALUES (1,8,1,'научные работники')
INSERT #F VALUES (1,9,1,'из них научные сотрудники')
INSERT #F VALUES (1,10,1,'средний медицинский (фармацевтический) персонал (персонал, обеспечивающий предоставление медицинских услуг)')
INSERT #F VALUES (1,11,1,'младший медицинский (фармацевтический) персонал (персонал, обеспечивающий предоставление медицинских услуг)')
INSERT #F VALUES (1,12,1,'работники, имеющие высшее фармацевтическое или иное высшее образование, предоставляющие медицинские услуги (обеспечивающие предоставление медицинских услуг)')
INSERT #F VALUES (1,13,1,'прочий персонал')
INSERT #F VALUES (1,1,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,2,2,'101                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,3,2,'102                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,4,2,'281                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,5,2,'282                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,6,2,'401                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,7,2,'501                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,8,2,'301                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,9,2,'311                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,10,2,'411                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,11,2,'421                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,12,2,'431                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,13,2,'103                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,1,3,'01                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,2,3,'02                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,3,3,'03                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,4,3,'04                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,5,3,'05                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,6,3,'06                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,7,3,'07                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,8,3,'08                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,9,3,'09                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,10,3,'10                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,11,3,'11                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,12,3,'12                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,13,3,'13                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,1,4,'НЗП_УСТАНОВКА() + НЗП_ЗНАЧЕНИЕ(''100'',4)')
INSERT #F VALUES (1,2,4,'НЗП_ЗНАЧЕНИЕ(''101'',4)')
INSERT #F VALUES (1,3,4,'НЗП_ЗНАЧЕНИЕ(''102'',4)')
INSERT #F VALUES (1,4,4,'НЗП_ЗНАЧЕНИЕ(''281'',4)')
INSERT #F VALUES (1,5,4,'НЗП_ЗНАЧЕНИЕ(''282'',4)')
INSERT #F VALUES (1,6,4,'НЗП_ЗНАЧЕНИЕ(''401'',4)')
INSERT #F VALUES (1,7,4,'НЗП_ЗНАЧЕНИЕ(''501'',4)')
INSERT #F VALUES (1,8,4,'НЗП_ЗНАЧЕНИЕ(''3013'',4)')
INSERT #F VALUES (1,9,4,'НЗП_ЗНАЧЕНИЕ(''3113'',4)')
INSERT #F VALUES (1,10,4,'НЗП_ЗНАЧЕНИЕ(''411'',4)')
INSERT #F VALUES (1,11,4,'НЗП_ЗНАЧЕНИЕ(''421'',4)')
INSERT #F VALUES (1,12,4,'НЗП_ЗНАЧЕНИЕ(''431'',4)')
INSERT #F VALUES (1,13,4,'НЗП_ЗНАЧЕНИЕ(''103'',4)')
INSERT #F VALUES (1,2,5,'НЗП_ЗНАЧЕНИЕ(''101'',5)')
INSERT #F VALUES (1,3,5,'НЗП_ЗНАЧЕНИЕ(''102'',5)')
INSERT #F VALUES (1,4,5,'НЗП_ЗНАЧЕНИЕ(''281'',5)')
INSERT #F VALUES (1,5,5,'НЗП_ЗНАЧЕНИЕ(''282'',5)')
INSERT #F VALUES (1,6,5,'НЗП_ЗНАЧЕНИЕ(''401'',5)')
INSERT #F VALUES (1,7,5,'НЗП_ЗНАЧЕНИЕ(''501'',5)')
INSERT #F VALUES (1,8,5,'НЗП_ЗНАЧЕНИЕ(''3013'',5)')
INSERT #F VALUES (1,9,5,'НЗП_ЗНАЧЕНИЕ(''3113'',5)')
INSERT #F VALUES (1,10,5,'НЗП_ЗНАЧЕНИЕ(''411'',5)')
INSERT #F VALUES (1,11,5,'НЗП_ЗНАЧЕНИЕ(''421'',5)')
INSERT #F VALUES (1,12,5,'НЗП_ЗНАЧЕНИЕ(''431'',5)')
INSERT #F VALUES (1,13,5,'НЗП_ЗНАЧЕНИЕ(''103'',5)')
INSERT #F VALUES (1,2,6,'НЗП_ЗНАЧЕНИЕ(''101'',6)')
INSERT #F VALUES (1,3,6,'НЗП_ЗНАЧЕНИЕ(''102'',6)')
INSERT #F VALUES (1,4,6,'НЗП_ЗНАЧЕНИЕ(''281'',6)')
INSERT #F VALUES (1,5,6,'НЗП_ЗНАЧЕНИЕ(''282'',6)')
INSERT #F VALUES (1,6,6,'НЗП_ЗНАЧЕНИЕ(''401'',6)')
INSERT #F VALUES (1,7,6,'НЗП_ЗНАЧЕНИЕ(''501'',6)')
INSERT #F VALUES (1,8,6,'НЗП_ЗНАЧЕНИЕ(''3013'',6)')
INSERT #F VALUES (1,9,6,'НЗП_ЗНАЧЕНИЕ(''3113'',6)')
INSERT #F VALUES (1,10,6,'НЗП_ЗНАЧЕНИЕ(''411'',6)')
INSERT #F VALUES (1,11,6,'НЗП_ЗНАЧЕНИЕ(''421'',6)')
INSERT #F VALUES (1,12,6,'НЗП_ЗНАЧЕНИЕ(''431'',6)')
INSERT #F VALUES (1,13,6,'НЗП_ЗНАЧЕНИЕ(''103'',6)')
INSERT #F VALUES (1,2,7,'НЗП_ЗНАЧЕНИЕ(''101'',7)')
INSERT #F VALUES (1,3,7,'НЗП_ЗНАЧЕНИЕ(''102'',7)')
INSERT #F VALUES (1,4,7,'НЗП_ЗНАЧЕНИЕ(''281'',7)')
INSERT #F VALUES (1,5,7,'НЗП_ЗНАЧЕНИЕ(''282'',7)')
INSERT #F VALUES (1,6,7,'НЗП_ЗНАЧЕНИЕ(''401'',7)')
INSERT #F VALUES (1,7,7,'НЗП_ЗНАЧЕНИЕ(''501'',7)')
INSERT #F VALUES (1,8,7,'НЗП_ЗНАЧЕНИЕ(''3013'',7)')
INSERT #F VALUES (1,9,7,'НЗП_ЗНАЧЕНИЕ(''3113'',7)')
INSERT #F VALUES (1,10,7,'НЗП_ЗНАЧЕНИЕ(''411'',7)')
INSERT #F VALUES (1,11,7,'НЗП_ЗНАЧЕНИЕ(''421'',7)')
INSERT #F VALUES (1,12,7,'НЗП_ЗНАЧЕНИЕ(''431'',7)')
INSERT #F VALUES (1,13,7,'НЗП_ЗНАЧЕНИЕ(''103'',7)')
INSERT #F VALUES (1,2,8,'НЗП_ЗНАЧЕНИЕ(''101'',8)')
INSERT #F VALUES (1,3,8,'НЗП_ЗНАЧЕНИЕ(''102'',8)')
INSERT #F VALUES (1,4,8,'НЗП_ЗНАЧЕНИЕ(''281'',8)')
INSERT #F VALUES (1,5,8,'НЗП_ЗНАЧЕНИЕ(''282'',8)')
INSERT #F VALUES (1,6,8,'НЗП_ЗНАЧЕНИЕ(''401'',8)')
INSERT #F VALUES (1,7,8,'НЗП_ЗНАЧЕНИЕ(''501'',8)')
INSERT #F VALUES (1,8,8,'НЗП_ЗНАЧЕНИЕ(''3013'',8)')
INSERT #F VALUES (1,9,8,'НЗП_ЗНАЧЕНИЕ(''3113'',8)')
INSERT #F VALUES (1,10,8,'НЗП_ЗНАЧЕНИЕ(''411'',8)')
INSERT #F VALUES (1,11,8,'НЗП_ЗНАЧЕНИЕ(''421'',8)')
INSERT #F VALUES (1,12,8,'НЗП_ЗНАЧЕНИЕ(''431'',8)')
INSERT #F VALUES (1,13,8,'НЗП_ЗНАЧЕНИЕ(''103'',8)')
INSERT #F VALUES (1,2,9,'НЗП_ЗНАЧЕНИЕ(''101'',9)')
INSERT #F VALUES (1,3,9,'НЗП_ЗНАЧЕНИЕ(''102'',9)')
INSERT #F VALUES (1,4,9,'НЗП_ЗНАЧЕНИЕ(''281'',9)')
INSERT #F VALUES (1,5,9,'НЗП_ЗНАЧЕНИЕ(''282'',9)')
INSERT #F VALUES (1,6,9,'НЗП_ЗНАЧЕНИЕ(''401'',9)')
INSERT #F VALUES (1,7,9,'НЗП_ЗНАЧЕНИЕ(''501'',9)')
INSERT #F VALUES (1,8,9,'НЗП_ЗНАЧЕНИЕ(''3013'',9)')
INSERT #F VALUES (1,9,9,'НЗП_ЗНАЧЕНИЕ(''3113'',9)')
INSERT #F VALUES (1,10,9,'НЗП_ЗНАЧЕНИЕ(''411'',9)')
INSERT #F VALUES (1,11,9,'НЗП_ЗНАЧЕНИЕ(''421'',9)')
INSERT #F VALUES (1,12,9,'НЗП_ЗНАЧЕНИЕ(''431'',9)')
INSERT #F VALUES (1,13,9,'НЗП_ЗНАЧЕНИЕ(''103'',9)')
INSERT #F VALUES (1,2,10,'НЗП_ЗНАЧЕНИЕ(''101'',10)')
INSERT #F VALUES (1,3,10,'НЗП_ЗНАЧЕНИЕ(''102'',10)')
INSERT #F VALUES (1,4,10,'НЗП_ЗНАЧЕНИЕ(''281'',10)')
INSERT #F VALUES (1,5,10,'НЗП_ЗНАЧЕНИЕ(''282'',10)')
INSERT #F VALUES (1,6,10,'НЗП_ЗНАЧЕНИЕ(''401'',10)')
INSERT #F VALUES (1,7,10,'НЗП_ЗНАЧЕНИЕ(''501'',10)')
INSERT #F VALUES (1,8,10,'НЗП_ЗНАЧЕНИЕ(''3013'',10)')
INSERT #F VALUES (1,9,10,'НЗП_ЗНАЧЕНИЕ(''3113'',10)')
INSERT #F VALUES (1,10,10,'НЗП_ЗНАЧЕНИЕ(''411'',10)')
INSERT #F VALUES (1,11,10,'НЗП_ЗНАЧЕНИЕ(''421'',10)')
INSERT #F VALUES (1,12,10,'НЗП_ЗНАЧЕНИЕ(''431'',10)')
INSERT #F VALUES (1,13,10,'НЗП_ЗНАЧЕНИЕ(''103'',10)')
INSERT #F VALUES (1,2,11,'НЗП_ЗНАЧЕНИЕ(''101'',11)')
INSERT #F VALUES (1,3,11,'НЗП_ЗНАЧЕНИЕ(''102'',11)')
INSERT #F VALUES (1,4,11,'НЗП_ЗНАЧЕНИЕ(''281'',11)')
INSERT #F VALUES (1,5,11,'НЗП_ЗНАЧЕНИЕ(''282'',11)')
INSERT #F VALUES (1,6,11,'НЗП_ЗНАЧЕНИЕ(''401'',11)')
INSERT #F VALUES (1,7,11,'НЗП_ЗНАЧЕНИЕ(''501'',11)')
INSERT #F VALUES (1,8,11,'НЗП_ЗНАЧЕНИЕ(''3013'',11)')
INSERT #F VALUES (1,9,11,'НЗП_ЗНАЧЕНИЕ(''3113'',11)')
INSERT #F VALUES (1,10,11,'НЗП_ЗНАЧЕНИЕ(''411'',11)')
INSERT #F VALUES (1,11,11,'НЗП_ЗНАЧЕНИЕ(''421'',11)')
INSERT #F VALUES (1,12,11,'НЗП_ЗНАЧЕНИЕ(''431'',11)')
INSERT #F VALUES (1,13,11,'НЗП_ЗНАЧЕНИЕ(''103'',11)')
INSERT #F VALUES (1,2,12,'НЗП_ЗНАЧЕНИЕ(''101'',12)')
INSERT #F VALUES (1,3,12,'НЗП_ЗНАЧЕНИЕ(''102'',12)')
INSERT #F VALUES (1,4,12,'НЗП_ЗНАЧЕНИЕ(''281'',12)')
INSERT #F VALUES (1,5,12,'НЗП_ЗНАЧЕНИЕ(''282'',12)')
INSERT #F VALUES (1,6,12,'НЗП_ЗНАЧЕНИЕ(''401'',12)')
INSERT #F VALUES (1,7,12,'НЗП_ЗНАЧЕНИЕ(''501'',12)')
INSERT #F VALUES (1,8,12,'НЗП_ЗНАЧЕНИЕ(''3013'',12)')
INSERT #F VALUES (1,9,12,'НЗП_ЗНАЧЕНИЕ(''3113'',12)')
INSERT #F VALUES (1,10,12,'НЗП_ЗНАЧЕНИЕ(''411'',12)')
INSERT #F VALUES (1,11,12,'НЗП_ЗНАЧЕНИЕ(''421'',12)')
INSERT #F VALUES (1,12,12,'НЗП_ЗНАЧЕНИЕ(''431'',12)')
INSERT #F VALUES (1,13,12,'НЗП_ЗНАЧЕНИЕ(''103'',12)')
INSERT #F VALUES (1,2,13,'НЗП_ЗНАЧЕНИЕ(''101'',13)')
INSERT #F VALUES (1,3,13,'НЗП_ЗНАЧЕНИЕ(''102'',13)')
INSERT #F VALUES (1,4,13,'НЗП_ЗНАЧЕНИЕ(''281'',13)')
INSERT #F VALUES (1,5,13,'НЗП_ЗНАЧЕНИЕ(''282'',13)')
INSERT #F VALUES (1,6,13,'НЗП_ЗНАЧЕНИЕ(''401'',13)')
INSERT #F VALUES (1,7,13,'НЗП_ЗНАЧЕНИЕ(''501'',13)')
INSERT #F VALUES (1,8,13,'НЗП_ЗНАЧЕНИЕ(''3013'',13)')
INSERT #F VALUES (1,9,13,'НЗП_ЗНАЧЕНИЕ(''3113'',13)')
INSERT #F VALUES (1,10,13,'НЗП_ЗНАЧЕНИЕ(''411'',13)')
INSERT #F VALUES (1,11,13,'НЗП_ЗНАЧЕНИЕ(''421'',13)')
INSERT #F VALUES (1,12,13,'НЗП_ЗНАЧЕНИЕ(''431'',13)')
INSERT #F VALUES (1,13,13,'НЗП_ЗНАЧЕНИЕ(''103'',13)')
INSERT #F VALUES (1,2,14,'НЗП_ЗНАЧЕНИЕ(''101'',14)')
INSERT #F VALUES (1,3,14,'НЗП_ЗНАЧЕНИЕ(''102'',14)')
INSERT #F VALUES (1,4,14,'НЗП_ЗНАЧЕНИЕ(''281'',14)')
INSERT #F VALUES (1,5,14,'НЗП_ЗНАЧЕНИЕ(''282'',14)')
INSERT #F VALUES (1,6,14,'НЗП_ЗНАЧЕНИЕ(''401'',14)')
INSERT #F VALUES (1,7,14,'НЗП_ЗНАЧЕНИЕ(''501'',14)')
INSERT #F VALUES (1,8,14,'НЗП_ЗНАЧЕНИЕ(''3013'',14)')
INSERT #F VALUES (1,9,14,'НЗП_ЗНАЧЕНИЕ(''3113'',14)')
INSERT #F VALUES (1,10,14,'НЗП_ЗНАЧЕНИЕ(''411'',14)')
INSERT #F VALUES (1,11,14,'НЗП_ЗНАЧЕНИЕ(''421'',14)')
INSERT #F VALUES (1,12,14,'НЗП_ЗНАЧЕНИЕ(''431'',14)')
INSERT #F VALUES (1,13,14,'НЗП_ЗНАЧЕНИЕ(''103'',14)')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 172
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'т.1стр.01 =  т.1стр.02 +  т.1стр.03 +  т.1стр.04 +  т.1стр.06 +  т.1стр.07 +  т.1стр.08 +  т.1стр.10 +  т.1стр.11 +  т.1стр.12 +  т.1стр.13',1,5,1,'20130912','','','','0606045','20130601','','=',2,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 1
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','01','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','02','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','03','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','04','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','06','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','07','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','08','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','10','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,9,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','11','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,10,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','12','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,11,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','13','1',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 11
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '451       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'451','Республика Коми',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '606       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'606','Заработная плата',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-02-07 09:17:06.860',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-02-07 09:17:06.860'
	BEGIN
		SELECT @vcMessage = 'Форма 0606045 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0606045 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-02-07 09:17:06.860. Обновление отклонено.'
	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. (фев  7 2014  9:17:15:403AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0606046 (Сведения о численности и оплате труда работников сферы культуры по категориям персонала)
-- Дата ввода : 20130601
-- Дата окончания действия :
-- Версия : 2014-02-07 09:17:15.393
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = '0606046' AND [START_DATE] = '20130601'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-02-07 09:17:15.393',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '0606046',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '0606046'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20130601')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SALARY'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Сведения о численности и оплате труда работников сферы культуры по категориям персонала',@vcNEW_FORM_CODE,@dNEW_START_DATE,6,1,1,1,2291,'RA_EXPORT_FORM',0,0,'19000101',NULL,''
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, '','sv_0606049_20130101.bas','','KirRepMakerMultiSheet.xls','sv_0606046_20130101.xlt','',NULL,'RA_EXPORT_FORM',0,NULL,NULL,NULL,'          ','REPORTS_ATR_TYPE_ORG,REPORTS_FILTER_SUBDIV',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Таблица', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Категория персонала',@iLINK_TABLE,0,1,1,0,2000,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код категории персонала',@iLINK_TABLE,1,1,2,0,3,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'№ строки',@iLINK_TABLE,1,1,3,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Средняя численность работников, человек: списочного состава',@iLINK_TABLE,1,0,4,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Средняя численность работников, человек:внешних совместителей',@iLINK_TABLE,1,0,5,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Фонд начисленной ЗП работников за отчетный период списочного состава:всего',@iLINK_TABLE,1,0,6,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Фонд начисленной ЗП работников за отчетный период списочного состава:в том числе по внутреннему совместительству',@iLINK_TABLE,1,0,7,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Фонд начисленной ЗП работников за отчетный период списочного состава: внешних совместителей',@iLINK_TABLE,1,0,8,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Фонд начисленной ЗП работников по источникам финансирования(из гр.3) за счет средств бюджетов всех уровней',@iLINK_TABLE,1,0,9,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Фонд начисленной ЗП работников по источникам финансирования(из гр. 3) ОМС',@iLINK_TABLE,1,0,10,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Фонд начисленной ЗП работников по источникам финансирования(из гр.3) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,11,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) за счет средств бюджетов всех уровней',@iLINK_TABLE,1,0,12,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ОМС',@iLINK_TABLE,1,0,13,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,14,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Таблица', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (1,1,1,1)
INSERT #R VALUES (2,1,4,1)
INSERT #R VALUES (3,1,15,1)
INSERT #R VALUES (4,1,19,1)
INSERT #R VALUES (5,1,5,1)
INSERT #R VALUES (6,1,6,1)
INSERT #R VALUES (7,1,17,1)
INSERT #R VALUES (8,1,8,1)
INSERT #R VALUES (9,1,9,1)
INSERT #R VALUES (10,1,10,1)
INSERT #R VALUES (11,1,11,1)
INSERT #R VALUES (12,1,12,1)
INSERT #R VALUES (13,1,13,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 13
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,1,1,'Всего работников (сумма строк 02-06 ,11-13)')
INSERT #F VALUES (1,2,1,'в том числе: руководитель организации')
INSERT #F VALUES (1,3,1,'заместители руководителя и руководители структурных подразделений и их заместители')
INSERT #F VALUES (1,4,1,'артистический персонал')
INSERT #F VALUES (1,5,1,'художественный персонал')
INSERT #F VALUES (1,6,1,'специалисты')
INSERT #F VALUES (1,7,1,'из них: научные работники')
INSERT #F VALUES (1,8,1,'из них научные сотрудники')
INSERT #F VALUES (1,9,1,'педагоги')
INSERT #F VALUES (1,10,1,'врачи')
INSERT #F VALUES (1,11,1,'средний медицинский персонал (персонал,обеспечивающий условия для предоставления медицинских услуг)')
INSERT #F VALUES (1,12,1,'младший медицинский персонал (персонал,обеспечивающий условия для предоставления медицинских услуг)')
INSERT #F VALUES (1,13,1,'прочий персонал')
INSERT #F VALUES (1,1,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,2,2,'101                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,3,2,'102                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,4,2,'601                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,5,2,'611                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,6,2,'621                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,7,2,'301                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,8,2,'311                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,9,2,'291                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,10,2,'401                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,11,2,'411                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,12,2,'421                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,13,2,'103                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,1,3,'01                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,2,3,'02                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,3,3,'03                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,4,3,'04                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,5,3,'05                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,6,3,'06                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,7,3,'07                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,8,3,'08                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,9,3,'09                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,10,3,'10                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,11,3,'11                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,12,3,'12                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,13,3,'13                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,1,4,'НЗП_УСТАНОВКА() + НЗП_ЗНАЧЕНИЕ(''100'',4)')
INSERT #F VALUES (1,2,4,'НЗП_ЗНАЧЕНИЕ(''101'',4)')
INSERT #F VALUES (1,3,4,'НЗП_ЗНАЧЕНИЕ(''102'',4)')
INSERT #F VALUES (1,4,4,'НЗП_ЗНАЧЕНИЕ(''601'',4)')
INSERT #F VALUES (1,5,4,'НЗП_ЗНАЧЕНИЕ(''611'',4)')
INSERT #F VALUES (1,6,4,'НЗП_ЗНАЧЕНИЕ(''621'',4)')
INSERT #F VALUES (1,7,4,'НЗП_ЗНАЧЕНИЕ(''3013'',4)')
INSERT #F VALUES (1,8,4,'НЗП_ЗНАЧЕНИЕ(''3113'',4)')
INSERT #F VALUES (1,9,4,'НЗП_ЗНАЧЕНИЕ(''291'',4)')
INSERT #F VALUES (1,10,4,'НЗП_ЗНАЧЕНИЕ(''401'',4)')
INSERT #F VALUES (1,11,4,'НЗП_ЗНАЧЕНИЕ(''411'',4)')
INSERT #F VALUES (1,12,4,'НЗП_ЗНАЧЕНИЕ(''421'',4)')
INSERT #F VALUES (1,13,4,'НЗП_ЗНАЧЕНИЕ(''103'',4)')
INSERT #F VALUES (1,2,5,'НЗП_ЗНАЧЕНИЕ(''101'',5)')
INSERT #F VALUES (1,3,5,'НЗП_ЗНАЧЕНИЕ(''102'',5)')
INSERT #F VALUES (1,4,5,'НЗП_ЗНАЧЕНИЕ(''601'',5)')
INSERT #F VALUES (1,5,5,'НЗП_ЗНАЧЕНИЕ(''611'',5)')
INSERT #F VALUES (1,6,5,'НЗП_ЗНАЧЕНИЕ(''621'',5)')
INSERT #F VALUES (1,7,5,'НЗП_ЗНАЧЕНИЕ(''3013'',5)')
INSERT #F VALUES (1,8,5,'НЗП_ЗНАЧЕНИЕ(''3113'',5)')
INSERT #F VALUES (1,9,5,'НЗП_ЗНАЧЕНИЕ(''291'',5)')
INSERT #F VALUES (1,10,5,'НЗП_ЗНАЧЕНИЕ(''401'',4)')
INSERT #F VALUES (1,11,5,'НЗП_ЗНАЧЕНИЕ(''411'',5)')
INSERT #F VALUES (1,12,5,'НЗП_ЗНАЧЕНИЕ(''421'',5)')
INSERT #F VALUES (1,13,5,'НЗП_ЗНАЧЕНИЕ(''103'',5)')
INSERT #F VALUES (1,2,6,'НЗП_ЗНАЧЕНИЕ(''101'',6)')
INSERT #F VALUES (1,3,6,'НЗП_ЗНАЧЕНИЕ(''102'',6)')
INSERT #F VALUES (1,4,6,'НЗП_ЗНАЧЕНИЕ(''601'',6)')
INSERT #F VALUES (1,5,6,'НЗП_ЗНАЧЕНИЕ(''611'',6)')
INSERT #F VALUES (1,6,6,'НЗП_ЗНАЧЕНИЕ(''621'',6)')
INSERT #F VALUES (1,7,6,'НЗП_ЗНАЧЕНИЕ(''3013'',6)')
INSERT #F VALUES (1,8,6,'НЗП_ЗНАЧЕНИЕ(''3113'',6)')
INSERT #F VALUES (1,9,6,'НЗП_ЗНАЧЕНИЕ(''291'',6)')
INSERT #F VALUES (1,10,6,'НЗП_ЗНАЧЕНИЕ(''401'',6)')
INSERT #F VALUES (1,11,6,'НЗП_ЗНАЧЕНИЕ(''411'',6)')
INSERT #F VALUES (1,12,6,'НЗП_ЗНАЧЕНИЕ(''421'',6)')
INSERT #F VALUES (1,13,6,'НЗП_ЗНАЧЕНИЕ(''103'',6)')
INSERT #F VALUES (1,2,7,'НЗП_ЗНАЧЕНИЕ(''101'',7)')
INSERT #F VALUES (1,3,7,'НЗП_ЗНАЧЕНИЕ(''102'',7)')
INSERT #F VALUES (1,4,7,'НЗП_ЗНАЧЕНИЕ(''601'',7)')
INSERT #F VALUES (1,5,7,'НЗП_ЗНАЧЕНИЕ(''611'',7)')
INSERT #F VALUES (1,6,7,'НЗП_ЗНАЧЕНИЕ(''621'',7)')
INSERT #F VALUES (1,7,7,'НЗП_ЗНАЧЕНИЕ(''3013'',7)')
INSERT #F VALUES (1,8,7,'НЗП_ЗНАЧЕНИЕ(''3113'',7)')
INSERT #F VALUES (1,9,7,'НЗП_ЗНАЧЕНИЕ(''291'',7)')
INSERT #F VALUES (1,10,7,'НЗП_ЗНАЧЕНИЕ(''401'',7)')
INSERT #F VALUES (1,11,7,'НЗП_ЗНАЧЕНИЕ(''411'',7)')
INSERT #F VALUES (1,12,7,'НЗП_ЗНАЧЕНИЕ(''421'',7)')
INSERT #F VALUES (1,13,7,'НЗП_ЗНАЧЕНИЕ(''103'',7)')
INSERT #F VALUES (1,2,8,'НЗП_ЗНАЧЕНИЕ(''101'',8)')
INSERT #F VALUES (1,3,8,'НЗП_ЗНАЧЕНИЕ(''102'',8)')
INSERT #F VALUES (1,4,8,'НЗП_ЗНАЧЕНИЕ(''601'',8)')
INSERT #F VALUES (1,5,8,'НЗП_ЗНАЧЕНИЕ(''611'',8)')
INSERT #F VALUES (1,6,8,'НЗП_ЗНАЧЕНИЕ(''621'',8)')
INSERT #F VALUES (1,7,8,'НЗП_ЗНАЧЕНИЕ(''3013'',8)')
INSERT #F VALUES (1,8,8,'НЗП_ЗНАЧЕНИЕ(''3113'',8)')
INSERT #F VALUES (1,9,8,'НЗП_ЗНАЧЕНИЕ(''291'',8)')
INSERT #F VALUES (1,10,8,'НЗП_ЗНАЧЕНИЕ(''401'',8)')
INSERT #F VALUES (1,11,8,'НЗП_ЗНАЧЕНИЕ(''411'',8)')
INSERT #F VALUES (1,12,8,'НЗП_ЗНАЧЕНИЕ(''421'',8)')
INSERT #F VALUES (1,13,8,'НЗП_ЗНАЧЕНИЕ(''103'',8)')
INSERT #F VALUES (1,2,9,'НЗП_ЗНАЧЕНИЕ(''101'',9)')
INSERT #F VALUES (1,3,9,'НЗП_ЗНАЧЕНИЕ(''102'',9)')
INSERT #F VALUES (1,4,9,'НЗП_ЗНАЧЕНИЕ(''601'',9)')
INSERT #F VALUES (1,5,9,'НЗП_ЗНАЧЕНИЕ(''611'',9)')
INSERT #F VALUES (1,6,9,'НЗП_ЗНАЧЕНИЕ(''621'',9)')
INSERT #F VALUES (1,7,9,'НЗП_ЗНАЧЕНИЕ(''3013'',9)')
INSERT #F VALUES (1,8,9,'НЗП_ЗНАЧЕНИЕ(''3113'',9)')
INSERT #F VALUES (1,9,9,'НЗП_ЗНАЧЕНИЕ(''291'',9)')
INSERT #F VALUES (1,10,9,'НЗП_ЗНАЧЕНИЕ(''401'',9)')
INSERT #F VALUES (1,11,9,'НЗП_ЗНАЧЕНИЕ(''411'',9)')
INSERT #F VALUES (1,12,9,'НЗП_ЗНАЧЕНИЕ(''421'',9)')
INSERT #F VALUES (1,13,9,'НЗП_ЗНАЧЕНИЕ(''103'',9)')
INSERT #F VALUES (1,2,10,'НЗП_ЗНАЧЕНИЕ(''101'',10)')
INSERT #F VALUES (1,3,10,'НЗП_ЗНАЧЕНИЕ(''102'',10)')
INSERT #F VALUES (1,4,10,'НЗП_ЗНАЧЕНИЕ(''601'',10)')
INSERT #F VALUES (1,5,10,'НЗП_ЗНАЧЕНИЕ(''611'',10)')
INSERT #F VALUES (1,6,10,'НЗП_ЗНАЧЕНИЕ(''621'',10)')
INSERT #F VALUES (1,7,10,'НЗП_ЗНАЧЕНИЕ(''3013'',10)')
INSERT #F VALUES (1,8,10,'НЗП_ЗНАЧЕНИЕ(''3113'',10)')
INSERT #F VALUES (1,9,10,'НЗП_ЗНАЧЕНИЕ(''291'',10)')
INSERT #F VALUES (1,10,10,'НЗП_ЗНАЧЕНИЕ(''401'',10)')
INSERT #F VALUES (1,11,10,'НЗП_ЗНАЧЕНИЕ(''411'',10)')
INSERT #F VALUES (1,12,10,'НЗП_ЗНАЧЕНИЕ(''421'',10)')
INSERT #F VALUES (1,13,10,'НЗП_ЗНАЧЕНИЕ(''103'',10)')
INSERT #F VALUES (1,2,11,'НЗП_ЗНАЧЕНИЕ(''101'',11)')
INSERT #F VALUES (1,3,11,'НЗП_ЗНАЧЕНИЕ(''102'',11)')
INSERT #F VALUES (1,4,11,'НЗП_ЗНАЧЕНИЕ(''601'',11)')
INSERT #F VALUES (1,5,11,'НЗП_ЗНАЧЕНИЕ(''611'',11)')
INSERT #F VALUES (1,6,11,'НЗП_ЗНАЧЕНИЕ(''621'',11)')
INSERT #F VALUES (1,7,11,'НЗП_ЗНАЧЕНИЕ(''3013'',11)')
INSERT #F VALUES (1,8,11,'НЗП_ЗНАЧЕНИЕ(''3113'',11)')
INSERT #F VALUES (1,9,11,'НЗП_ЗНАЧЕНИЕ(''291'',11)')
INSERT #F VALUES (1,10,11,'НЗП_ЗНАЧЕНИЕ(''401'',11)')
INSERT #F VALUES (1,11,11,'НЗП_ЗНАЧЕНИЕ(''411'',11)')
INSERT #F VALUES (1,12,11,'НЗП_ЗНАЧЕНИЕ(''421'',11)')
INSERT #F VALUES (1,13,11,'НЗП_ЗНАЧЕНИЕ(''103'',11)')
INSERT #F VALUES (1,2,12,'НЗП_ЗНАЧЕНИЕ(''101'',12)')
INSERT #F VALUES (1,3,12,'НЗП_ЗНАЧЕНИЕ(''102'',12)')
INSERT #F VALUES (1,4,12,'НЗП_ЗНАЧЕНИЕ(''601'',12)')
INSERT #F VALUES (1,5,12,'НЗП_ЗНАЧЕНИЕ(''611'',12)')
INSERT #F VALUES (1,6,12,'НЗП_ЗНАЧЕНИЕ(''621'',12)')
INSERT #F VALUES (1,7,12,'НЗП_ЗНАЧЕНИЕ(''3013'',12)')
INSERT #F VALUES (1,8,12,'НЗП_ЗНАЧЕНИЕ(''3113'',12)')
INSERT #F VALUES (1,9,12,'НЗП_ЗНАЧЕНИЕ(''291'',12)')
INSERT #F VALUES (1,10,12,'НЗП_ЗНАЧЕНИЕ(''401'',12)')
INSERT #F VALUES (1,11,12,'НЗП_ЗНАЧЕНИЕ(''411'',12)')
INSERT #F VALUES (1,12,12,'НЗП_ЗНАЧЕНИЕ(''421'',12)')
INSERT #F VALUES (1,13,12,'НЗП_ЗНАЧЕНИЕ(''103'',12)')
INSERT #F VALUES (1,2,13,'НЗП_ЗНАЧЕНИЕ(''101'',13)')
INSERT #F VALUES (1,3,13,'НЗП_ЗНАЧЕНИЕ(''102'',13)')
INSERT #F VALUES (1,4,13,'НЗП_ЗНАЧЕНИЕ(''601'',13)')
INSERT #F VALUES (1,5,13,'НЗП_ЗНАЧЕНИЕ(''611'',13)')
INSERT #F VALUES (1,6,13,'НЗП_ЗНАЧЕНИЕ(''621'',13)')
INSERT #F VALUES (1,7,13,'НЗП_ЗНАЧЕНИЕ(''3013'',13)')
INSERT #F VALUES (1,8,13,'НЗП_ЗНАЧЕНИЕ(''3113'',13)')
INSERT #F VALUES (1,9,13,'НЗП_ЗНАЧЕНИЕ(''291'',13)')
INSERT #F VALUES (1,10,13,'НЗП_ЗНАЧЕНИЕ(''401'',13)')
INSERT #F VALUES (1,11,13,'НЗП_ЗНАЧЕНИЕ(''411'',13)')
INSERT #F VALUES (1,12,13,'НЗП_ЗНАЧЕНИЕ(''421'',13)')
INSERT #F VALUES (1,13,13,'НЗП_ЗНАЧЕНИЕ(''103'',13)')
INSERT #F VALUES (1,2,14,'НЗП_ЗНАЧЕНИЕ(''101'',14)')
INSERT #F VALUES (1,3,14,'НЗП_ЗНАЧЕНИЕ(''102'',14)')
INSERT #F VALUES (1,4,14,'НЗП_ЗНАЧЕНИЕ(''601'',14)')
INSERT #F VALUES (1,5,14,'НЗП_ЗНАЧЕНИЕ(''611'',14)')
INSERT #F VALUES (1,6,14,'НЗП_ЗНАЧЕНИЕ(''621'',14)')
INSERT #F VALUES (1,7,14,'НЗП_ЗНАЧЕНИЕ(''3013'',14)')
INSERT #F VALUES (1,8,14,'НЗП_ЗНАЧЕНИЕ(''3113'',14)')
INSERT #F VALUES (1,9,14,'НЗП_ЗНАЧЕНИЕ(''291'',14)')
INSERT #F VALUES (1,10,14,'НЗП_ЗНАЧЕНИЕ(''401'',14)')
INSERT #F VALUES (1,11,14,'НЗП_ЗНАЧЕНИЕ(''411'',14)')
INSERT #F VALUES (1,12,14,'НЗП_ЗНАЧЕНИЕ(''421'',14)')
INSERT #F VALUES (1,13,14,'НЗП_ЗНАЧЕНИЕ(''103'',14)')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 172
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'т.1стр.01 =  т.1стр.02 +  т.1стр.03 +  т.1стр.12 +  т.1стр.13 +  т.1стр.04 +  т.1стр.05 +  т.1стр.11 +  т.1стр.06',1,3,1,'20130912','','','','0606046','20130601','','=',2,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 1
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','01','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','02','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','03','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','12','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','13','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','04','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','05','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','11','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,9,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','06','1',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 9
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '451       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'451','Республика Коми',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '606       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'606','Заработная плата',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-02-07 09:17:15.393',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-02-07 09:17:15.393'
	BEGIN
		SELECT @vcMessage = 'Форма 0606046 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0606046 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-02-07 09:17:15.393. Обновление отклонено.'
	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. (фев  7 2014  9:17:22:500AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0606047 (Сведения о численности и оплате труда работников организаций, осуществляющих научные исследования и разработки,по категориям персонала)
-- Дата ввода : 20130601
-- Дата окончания действия :
-- Версия : 2014-02-07 09:17:22.490
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = '0606047' AND [START_DATE] = '20130601'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-02-07 09:17:22.490',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '0606047',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '0606047'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20130601')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SALARY'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Сведения о численности и оплате труда работников организаций, осуществляющих научные исследования и разработки,по категориям персонала',@vcNEW_FORM_CODE,@dNEW_START_DATE,6,1,1,1,2291,'RA_EXPORT_FORM',0,0,'19000101',NULL,''
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, '','sv_0606049_20130101.bas','','KirRepMakerMultiSheet.xls','sv_0606047_20130101.xlt','',NULL,'RA_EXPORT_FORM',0,NULL,NULL,NULL,'          ','REPORTS_ATR_TYPE_ORG,REPORTS_FILTER_SUBDIV',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Таблица', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Категория персонала',@iLINK_TABLE,0,1,1,0,2000,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код категории персонала',@iLINK_TABLE,1,1,2,0,3,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'№ строки',@iLINK_TABLE,1,1,3,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Средняя численность работников, человек: списочного состава',@iLINK_TABLE,1,0,4,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Средняя численность работников, человек:внешних совместителей',@iLINK_TABLE,1,0,5,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Фонд начисленной ЗП работников за отчетный период списочного состава:всего',@iLINK_TABLE,1,0,6,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Фонд начисленной ЗП работников за отчетный период списочного состава:в том числе по внутреннему совместительству',@iLINK_TABLE,1,0,7,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Фонд начисленной ЗП работников за отчетный период списочного состава: внешних совместителей',@iLINK_TABLE,1,0,8,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Фонд начисленной ЗП работников по источникам финансирования(из гр.3) за счет средств бюджетов всех уровней',@iLINK_TABLE,1,0,9,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Фонд начисленной ЗП работников по источникам финансирования(из гр. 3) ОМС',@iLINK_TABLE,1,0,10,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Фонд начисленной ЗП работников по источникам финансирования(из гр.3) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,11,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) за счет средств бюджетов всех уровней',@iLINK_TABLE,1,0,12,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ОМС',@iLINK_TABLE,1,0,13,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,14,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Таблица', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (1,1,1,1)
INSERT #R VALUES (2,1,4,1)
INSERT #R VALUES (3,1,19,1)
INSERT #R VALUES (4,1,5,1)
INSERT #R VALUES (5,1,6,1)
INSERT #R VALUES (6,1,17,1)
INSERT #R VALUES (7,1,8,1)
INSERT #R VALUES (8,1,9,1)
INSERT #R VALUES (9,1,10,1)
INSERT #R VALUES (10,1,11,1)
INSERT #R VALUES (11,1,12,1)
INSERT #R VALUES (12,1,13,1)
INSERT #R VALUES (13,1,14,1)
INSERT #R VALUES (14,1,20,1)
INSERT #R VALUES (15,1,18,1)
INSERT #R VALUES (16,1,20,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 16
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,1,1,'Всего работников (сумма строк 02 ,09-14)')
INSERT #F VALUES (1,2,1,'в том числе: научные работники (исследователи) (сумма строк 03, 04, 05, 08)')
INSERT #F VALUES (1,3,1,'в том числе: руководитель организации')
INSERT #F VALUES (1,4,1,'заместители руководителя и руководители структурных подразделений и их заместителей')
INSERT #F VALUES (1,5,1,'научные работники')
INSERT #F VALUES (1,6,1,'из них: главные, ведущие и старшие научные сотрудники')
INSERT #F VALUES (1,7,1,'научные, младшие научные сотрудники')
INSERT #F VALUES (1,8,1,'другие научные работники (исследователи)')
INSERT #F VALUES (1,9,1,'техники')
INSERT #F VALUES (1,10,1,'вспомогательный персонал')
INSERT #F VALUES (1,11,1,'врачи')
INSERT #F VALUES (1,12,1,'средний медицинский персонал (персонал,обеспечивающий условия для предоставления медицинских услуг)')
INSERT #F VALUES (1,13,1,'младший медицинский персонал (персонал,обеспечивающий условия для предоставления медицинских услуг)')
INSERT #F VALUES (1,14,1,'прочий персонал')
INSERT #F VALUES (1,15,1,'Из строки 01 фонд начисленной заработной платы работников: за счет средств  федерального бюджета')
INSERT #F VALUES (1,16,1,'конкурсное (программное) финансирование')
INSERT #F VALUES (1,1,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,2,2,'301                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,3,2,'101                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,4,2,'102                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,5,2,'311                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,6,2,'312                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,7,2,'313                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,8,2,'302                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,9,2,'321                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,10,2,'331                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,11,2,'401                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,12,2,'411                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,13,2,'421                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,14,2,'103                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,15,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,16,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,1,3,'01                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,2,3,'02                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,3,3,'03                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,4,3,'04                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,5,3,'05                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,6,3,'06                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,7,3,'07                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,8,3,'08                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,9,3,'09                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,10,3,'10                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,11,3,'11                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,12,3,'12                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,13,3,'13                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,14,3,'14                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,15,3,'15                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,16,3,'16                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,1,4,'НЗП_УСТАНОВКА() + НЗП_ЗНАЧЕНИЕ(''100'',4)')
INSERT #F VALUES (1,2,4,'НЗП_ЗНАЧЕНИЕ(''3014'',4)')
INSERT #F VALUES (1,3,4,'НЗП_ЗНАЧЕНИЕ(''101'',4)')
INSERT #F VALUES (1,4,4,'НЗП_ЗНАЧЕНИЕ(''102'',4)')
INSERT #F VALUES (1,5,4,'НЗП_ЗНАЧЕНИЕ(''3113'',4)')
INSERT #F VALUES (1,6,4,'НЗП_ЗНАЧЕНИЕ(''312'',4)')
INSERT #F VALUES (1,7,4,'НЗП_ЗНАЧЕНИЕ(''313'',4)')
INSERT #F VALUES (1,8,4,'НЗП_ЗНАЧЕНИЕ(''302'',4)')
INSERT #F VALUES (1,9,4,'НЗП_ЗНАЧЕНИЕ(''321'',4)')
INSERT #F VALUES (1,10,4,'НЗП_ЗНАЧЕНИЕ(''331'',4)')
INSERT #F VALUES (1,11,4,'НЗП_ЗНАЧЕНИЕ(''401'',4)')
INSERT #F VALUES (1,12,4,'НЗП_ЗНАЧЕНИЕ(''411'',4)')
INSERT #F VALUES (1,13,4,'НЗП_ЗНАЧЕНИЕ(''421'',4)')
INSERT #F VALUES (1,14,4,'НЗП_ЗНАЧЕНИЕ(''103'',4)')
INSERT #F VALUES (1,15,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,4,'ЗАПРЕТ()')
INSERT #F VALUES (1,2,5,'НЗП_ЗНАЧЕНИЕ(''3014'',5)')
INSERT #F VALUES (1,3,5,'НЗП_ЗНАЧЕНИЕ(''101'',5)')
INSERT #F VALUES (1,4,5,'НЗП_ЗНАЧЕНИЕ(''102'',5)')
INSERT #F VALUES (1,5,5,'НЗП_ЗНАЧЕНИЕ(''3113'',5)')
INSERT #F VALUES (1,6,5,'НЗП_ЗНАЧЕНИЕ(''312'',5)')
INSERT #F VALUES (1,7,5,'НЗП_ЗНАЧЕНИЕ(''313'',5)')
INSERT #F VALUES (1,8,5,'НЗП_ЗНАЧЕНИЕ(''302'',5)')
INSERT #F VALUES (1,9,5,'НЗП_ЗНАЧЕНИЕ(''321'',5)')
INSERT #F VALUES (1,10,5,'НЗП_ЗНАЧЕНИЕ(''331'',5)')
INSERT #F VALUES (1,11,5,'НЗП_ЗНАЧЕНИЕ(''401'',5)')
INSERT #F VALUES (1,12,5,'НЗП_ЗНАЧЕНИЕ(''411'',5)')
INSERT #F VALUES (1,13,5,'НЗП_ЗНАЧЕНИЕ(''421'',5)')
INSERT #F VALUES (1,14,5,'НЗП_ЗНАЧЕНИЕ(''103'',5)')
INSERT #F VALUES (1,15,5,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,5,'ЗАПРЕТ()')
INSERT #F VALUES (1,2,6,'НЗП_ЗНАЧЕНИЕ(''3014'',6)')
INSERT #F VALUES (1,3,6,'НЗП_ЗНАЧЕНИЕ(''101'',6)')
INSERT #F VALUES (1,4,6,'НЗП_ЗНАЧЕНИЕ(''102'',6)')
INSERT #F VALUES (1,5,6,'НЗП_ЗНАЧЕНИЕ(''3113'',6)')
INSERT #F VALUES (1,6,6,'НЗП_ЗНАЧЕНИЕ(''312'',6)')
INSERT #F VALUES (1,7,6,'НЗП_ЗНАЧЕНИЕ(''313'',6)')
INSERT #F VALUES (1,8,6,'НЗП_ЗНАЧЕНИЕ(''302'',6)')
INSERT #F VALUES (1,9,6,'НЗП_ЗНАЧЕНИЕ(''321'',6)')
INSERT #F VALUES (1,10,6,'НЗП_ЗНАЧЕНИЕ(''331'',6)')
INSERT #F VALUES (1,11,6,'НЗП_ЗНАЧЕНИЕ(''401'',6)')
INSERT #F VALUES (1,12,6,'НЗП_ЗНАЧЕНИЕ(''411'',6)')
INSERT #F VALUES (1,13,6,'НЗП_ЗНАЧЕНИЕ(''421'',6)')
INSERT #F VALUES (1,14,6,'НЗП_ЗНАЧЕНИЕ(''103'',6)')
INSERT #F VALUES (1,15,6,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,6,'ЗАПРЕТ()')
INSERT #F VALUES (1,2,7,'НЗП_ЗНАЧЕНИЕ(''3014'',7)')
INSERT #F VALUES (1,3,7,'НЗП_ЗНАЧЕНИЕ(''101'',7)')
INSERT #F VALUES (1,4,7,'НЗП_ЗНАЧЕНИЕ(''102'',7)')
INSERT #F VALUES (1,5,7,'НЗП_ЗНАЧЕНИЕ(''3113'',7)')
INSERT #F VALUES (1,6,7,'НЗП_ЗНАЧЕНИЕ(''312'',7)')
INSERT #F VALUES (1,7,7,'НЗП_ЗНАЧЕНИЕ(''313'',7)')
INSERT #F VALUES (1,8,7,'НЗП_ЗНАЧЕНИЕ(''302'',7)')
INSERT #F VALUES (1,9,7,'НЗП_ЗНАЧЕНИЕ(''321'',7)')
INSERT #F VALUES (1,10,7,'НЗП_ЗНАЧЕНИЕ(''331'',7)')
INSERT #F VALUES (1,11,7,'НЗП_ЗНАЧЕНИЕ(''401'',7)')
INSERT #F VALUES (1,12,7,'НЗП_ЗНАЧЕНИЕ(''411'',7)')
INSERT #F VALUES (1,13,7,'НЗП_ЗНАЧЕНИЕ(''421'',7)')
INSERT #F VALUES (1,14,7,'НЗП_ЗНАЧЕНИЕ(''103'',7)')
INSERT #F VALUES (1,15,7,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,7,'ЗАПРЕТ()')
INSERT #F VALUES (1,2,8,'НЗП_ЗНАЧЕНИЕ(''3014'',8)')
INSERT #F VALUES (1,3,8,'НЗП_ЗНАЧЕНИЕ(''101'',8)')
INSERT #F VALUES (1,4,8,'НЗП_ЗНАЧЕНИЕ(''102'',8)')
INSERT #F VALUES (1,5,8,'НЗП_ЗНАЧЕНИЕ(''3113'',8)')
INSERT #F VALUES (1,6,8,'НЗП_ЗНАЧЕНИЕ(''312'',8)')
INSERT #F VALUES (1,7,8,'НЗП_ЗНАЧЕНИЕ(''313'',8)')
INSERT #F VALUES (1,8,8,'НЗП_ЗНАЧЕНИЕ(''302'',8)')
INSERT #F VALUES (1,9,8,'НЗП_ЗНАЧЕНИЕ(''321'',8)')
INSERT #F VALUES (1,10,8,'НЗП_ЗНАЧЕНИЕ(''331'',8)')
INSERT #F VALUES (1,11,8,'НЗП_ЗНАЧЕНИЕ(''401'',8)')
INSERT #F VALUES (1,12,8,'НЗП_ЗНАЧЕНИЕ(''411'',8)')
INSERT #F VALUES (1,13,8,'НЗП_ЗНАЧЕНИЕ(''421'',8)')
INSERT #F VALUES (1,14,8,'НЗП_ЗНАЧЕНИЕ(''103'',8)')
INSERT #F VALUES (1,15,8,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,8,'ЗАПРЕТ()')
INSERT #F VALUES (1,2,9,'НЗП_ЗНАЧЕНИЕ(''3014'',9)')
INSERT #F VALUES (1,3,9,'НЗП_ЗНАЧЕНИЕ(''101'',9)')
INSERT #F VALUES (1,4,9,'НЗП_ЗНАЧЕНИЕ(''102'',9)')
INSERT #F VALUES (1,5,9,'НЗП_ЗНАЧЕНИЕ(''3113'',9)')
INSERT #F VALUES (1,6,9,'НЗП_ЗНАЧЕНИЕ(''312'',9)')
INSERT #F VALUES (1,7,9,'НЗП_ЗНАЧЕНИЕ(''313'',9)')
INSERT #F VALUES (1,8,9,'НЗП_ЗНАЧЕНИЕ(''302'',9)')
INSERT #F VALUES (1,9,9,'НЗП_ЗНАЧЕНИЕ(''321'',9)')
INSERT #F VALUES (1,10,9,'НЗП_ЗНАЧЕНИЕ(''331'',9)')
INSERT #F VALUES (1,11,9,'НЗП_ЗНАЧЕНИЕ(''401'',9)')
INSERT #F VALUES (1,12,9,'НЗП_ЗНАЧЕНИЕ(''411'',9)')
INSERT #F VALUES (1,13,9,'НЗП_ЗНАЧЕНИЕ(''421'',9)')
INSERT #F VALUES (1,14,9,'НЗП_ЗНАЧЕНИЕ(''103'',9)')
INSERT #F VALUES (1,2,10,'НЗП_ЗНАЧЕНИЕ(''3014'',10)')
INSERT #F VALUES (1,3,10,'НЗП_ЗНАЧЕНИЕ(''101'',10)')
INSERT #F VALUES (1,4,10,'НЗП_ЗНАЧЕНИЕ(''102'',10)')
INSERT #F VALUES (1,5,10,'НЗП_ЗНАЧЕНИЕ(''3113'',10)')
INSERT #F VALUES (1,6,10,'НЗП_ЗНАЧЕНИЕ(''312'',10)')
INSERT #F VALUES (1,7,10,'НЗП_ЗНАЧЕНИЕ(''313'',10)')
INSERT #F VALUES (1,8,10,'НЗП_ЗНАЧЕНИЕ(''302'',10)')
INSERT #F VALUES (1,9,10,'НЗП_ЗНАЧЕНИЕ(''321'',10)')
INSERT #F VALUES (1,10,10,'НЗП_ЗНАЧЕНИЕ(''331'',10)')
INSERT #F VALUES (1,11,10,'НЗП_ЗНАЧЕНИЕ(''401'',10)')
INSERT #F VALUES (1,12,10,'НЗП_ЗНАЧЕНИЕ(''411'',10)')
INSERT #F VALUES (1,13,10,'НЗП_ЗНАЧЕНИЕ(''421'',10)')
INSERT #F VALUES (1,14,10,'НЗП_ЗНАЧЕНИЕ(''103'',10)')
INSERT #F VALUES (1,15,10,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,10,'ЗАПРЕТ()')
INSERT #F VALUES (1,2,11,'НЗП_ЗНАЧЕНИЕ(''3014'',11)')
INSERT #F VALUES (1,3,11,'НЗП_ЗНАЧЕНИЕ(''101'',11)')
INSERT #F VALUES (1,4,11,'НЗП_ЗНАЧЕНИЕ(''102'',11)')
INSERT #F VALUES (1,5,11,'НЗП_ЗНАЧЕНИЕ(''3113'',11)')
INSERT #F VALUES (1,6,11,'НЗП_ЗНАЧЕНИЕ(''312'',11)')
INSERT #F VALUES (1,7,11,'НЗП_ЗНАЧЕНИЕ(''313'',11)')
INSERT #F VALUES (1,8,11,'НЗП_ЗНАЧЕНИЕ(''302'',11)')
INSERT #F VALUES (1,9,11,'НЗП_ЗНАЧЕНИЕ(''321'',11)')
INSERT #F VALUES (1,10,11,'НЗП_ЗНАЧЕНИЕ(''331'',11)')
INSERT #F VALUES (1,11,11,'НЗП_ЗНАЧЕНИЕ(''401'',11)')
INSERT #F VALUES (1,12,11,'НЗП_ЗНАЧЕНИЕ(''411'',11)')
INSERT #F VALUES (1,13,11,'НЗП_ЗНАЧЕНИЕ(''421'',11)')
INSERT #F VALUES (1,14,11,'НЗП_ЗНАЧЕНИЕ(''103'',11)')
INSERT #F VALUES (1,2,12,'НЗП_ЗНАЧЕНИЕ(''3014'',12)')
INSERT #F VALUES (1,3,12,'НЗП_ЗНАЧЕНИЕ(''101'',12)')
INSERT #F VALUES (1,4,12,'НЗП_ЗНАЧЕНИЕ(''102'',12)')
INSERT #F VALUES (1,5,12,'НЗП_ЗНАЧЕНИЕ(''3113'',12)')
INSERT #F VALUES (1,6,12,'НЗП_ЗНАЧЕНИЕ(''312'',12)')
INSERT #F VALUES (1,7,12,'НЗП_ЗНАЧЕНИЕ(''313'',12)')
INSERT #F VALUES (1,8,12,'НЗП_ЗНАЧЕНИЕ(''302'',12)')
INSERT #F VALUES (1,9,12,'НЗП_ЗНАЧЕНИЕ(''321'',12)')
INSERT #F VALUES (1,10,12,'НЗП_ЗНАЧЕНИЕ(''331'',12)')
INSERT #F VALUES (1,11,12,'НЗП_ЗНАЧЕНИЕ(''401'',12)')
INSERT #F VALUES (1,12,12,'НЗП_ЗНАЧЕНИЕ(''411'',12)')
INSERT #F VALUES (1,13,12,'НЗП_ЗНАЧЕНИЕ(''421'',12)')
INSERT #F VALUES (1,14,12,'НЗП_ЗНАЧЕНИЕ(''103'',12)')
INSERT #F VALUES (1,2,13,'НЗП_ЗНАЧЕНИЕ(''3014'',13)')
INSERT #F VALUES (1,3,13,'НЗП_ЗНАЧЕНИЕ(''101'',13)')
INSERT #F VALUES (1,4,13,'НЗП_ЗНАЧЕНИЕ(''102'',13)')
INSERT #F VALUES (1,5,13,'НЗП_ЗНАЧЕНИЕ(''3113'',13)')
INSERT #F VALUES (1,6,13,'НЗП_ЗНАЧЕНИЕ(''312'',13)')
INSERT #F VALUES (1,7,13,'НЗП_ЗНАЧЕНИЕ(''313'',13)')
INSERT #F VALUES (1,8,13,'НЗП_ЗНАЧЕНИЕ(''302'',13)')
INSERT #F VALUES (1,9,13,'НЗП_ЗНАЧЕНИЕ(''321'',13)')
INSERT #F VALUES (1,10,13,'НЗП_ЗНАЧЕНИЕ(''331'',13)')
INSERT #F VALUES (1,11,13,'НЗП_ЗНАЧЕНИЕ(''401'',13)')
INSERT #F VALUES (1,12,13,'НЗП_ЗНАЧЕНИЕ(''411'',13)')
INSERT #F VALUES (1,13,13,'НЗП_ЗНАЧЕНИЕ(''421'',13)')
INSERT #F VALUES (1,14,13,'НЗП_ЗНАЧЕНИЕ(''103'',13)')
INSERT #F VALUES (1,15,13,'ЗАПРЕТ()')
INSERT #F VALUES (1,16,13,'ЗАПРЕТ()')
INSERT #F VALUES (1,2,14,'НЗП_ЗНАЧЕНИЕ(''3014'',14)')
INSERT #F VALUES (1,3,14,'НЗП_ЗНАЧЕНИЕ(''101'',14)')
INSERT #F VALUES (1,4,14,'НЗП_ЗНАЧЕНИЕ(''102'',14)')
INSERT #F VALUES (1,5,14,'НЗП_ЗНАЧЕНИЕ(''3113'',14)')
INSERT #F VALUES (1,6,14,'НЗП_ЗНАЧЕНИЕ(''312'',14)')
INSERT #F VALUES (1,7,14,'НЗП_ЗНАЧЕНИЕ(''313'',14)')
INSERT #F VALUES (1,8,14,'НЗП_ЗНАЧЕНИЕ(''302'',14)')
INSERT #F VALUES (1,9,14,'НЗП_ЗНАЧЕНИЕ(''321'',14)')
INSERT #F VALUES (1,10,14,'НЗП_ЗНАЧЕНИЕ(''331'',14)')
INSERT #F VALUES (1,11,14,'НЗП_ЗНАЧЕНИЕ(''401'',14)')
INSERT #F VALUES (1,12,14,'НЗП_ЗНАЧЕНИЕ(''411'',14)')
INSERT #F VALUES (1,13,14,'НЗП_ЗНАЧЕНИЕ(''421'',14)')
INSERT #F VALUES (1,14,14,'НЗП_ЗНАЧЕНИЕ(''103'',14)')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 206
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-02-07 09:17:22.490',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-02-07 09:17:22.490'
	BEGIN
		SELECT @vcMessage = 'Форма 0606047 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0606047 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-02-07 09:17:22.490. Обновление отклонено.'
	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. (фев  7 2014  9:17:29:147AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0606048 (Сведения о численности и оплате труда работников сферы образования по категориям персонала)
-- Дата ввода : 20130601
-- Дата окончания действия :
-- Версия : 2014-02-07 09:17:29.133
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = '0606048' AND [START_DATE] = '20130601'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-02-07 09:17:29.133',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '0606048',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '0606048'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20130601')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SALARY'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Сведения о численности и оплате труда работников сферы образования по категориям персонала',@vcNEW_FORM_CODE,@dNEW_START_DATE,6,1,1,1,2291,'RA_EXPORT_FORM',0,0,'19000101',NULL,''
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, '','sv_0606049_20130101.bas','','KirRepMakerMultiSheet.xls','sv_0606048_20130101.xlt','',NULL,'RA_EXPORT_FORM',0,NULL,NULL,NULL,'          ','REPORTS_ATR_TYPE_ORG,REPORTS_FILTER_SUBDIV',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Таблица', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Категория персонала',@iLINK_TABLE,0,1,1,0,2000,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код категории персонала',@iLINK_TABLE,1,1,2,0,3,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'№ строки',@iLINK_TABLE,1,1,3,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Средняя численность работников, человек: списочного состава',@iLINK_TABLE,1,0,4,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Средняя численность работников, человек:внешних совместителей',@iLINK_TABLE,1,0,5,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Фонд начисленной ЗП работников за отчетный период списочного состава:всего',@iLINK_TABLE,1,0,6,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Фонд начисленной ЗП работников за отчетный период списочного состава:в том числе по внутреннему совместительству',@iLINK_TABLE,1,0,7,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Фонд начисленной ЗП работников за отчетный период списочного состава: внешних совместителей',@iLINK_TABLE,1,0,8,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Фонд начисленной ЗП работников по источникам финансирования(из гр.3) за счет средств бюджетов всех уровней',@iLINK_TABLE,1,0,9,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Фонд начисленной ЗП работников по источникам финансирования(из гр. 3) ОМС',@iLINK_TABLE,1,0,10,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Фонд начисленной ЗП работников по источникам финансирования(из гр.3) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,11,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) за счет средств бюджетов всех уровней',@iLINK_TABLE,1,0,12,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ОМС',@iLINK_TABLE,1,0,13,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,14,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Таблица', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (1,1,1,1)
INSERT #R VALUES (2,1,4,1)
INSERT #R VALUES (3,1,5,1)
INSERT #R VALUES (4,1,27,1)
INSERT #R VALUES (5,1,6,1)
INSERT #R VALUES (6,1,7,1)
INSERT #R VALUES (7,1,8,1)
INSERT #R VALUES (8,1,9,1)
INSERT #R VALUES (9,1,10,1)
INSERT #R VALUES (10,1,11,1)
INSERT #R VALUES (11,1,28,1)
INSERT #R VALUES (12,1,29,1)
INSERT #R VALUES (13,1,30,1)
INSERT #R VALUES (14,1,12,1)
INSERT #R VALUES (15,1,13,1)
INSERT #R VALUES (16,1,14,1)
INSERT #R VALUES (17,1,14,1)
INSERT #R VALUES (18,1,15,1)
INSERT #R VALUES (19,1,17,1)
INSERT #R VALUES (20,1,18,1)
INSERT #R VALUES (21,1,19,1)
INSERT #R VALUES (22,1,20,1)
INSERT #R VALUES (23,1,21,1)
INSERT #R VALUES (24,1,22,1)
INSERT #R VALUES (25,1,23,1)
INSERT #R VALUES (26,1,24,1)
INSERT #R VALUES (27,1,25,1)
INSERT #R VALUES (28,1,26,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 28
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,1,1,'Всего работников (сумма строк 02 - 05,07,08,11,14,17-19,21,23-28)')
INSERT #F VALUES (1,2,1,'в том числе: руководитель организации')
INSERT #F VALUES (1,3,1,'заместители руководителя и руководители структурных подразделений  и их заместители')
INSERT #F VALUES (1,4,1,'педагогические работники дощкольных общеобразовательных учреждений')
INSERT #F VALUES (1,5,1,'педагогические работники общеобразовательных учреждений')
INSERT #F VALUES (1,6,1,'из них учителя')
INSERT #F VALUES (1,7,1,'педагогические работники образовательных учреждений дополнительного образования детей')
INSERT #F VALUES (1,8,1,'педагогические работники образовательных учреждений НПО')
INSERT #F VALUES (1,9,1,'из них преподаватели')
INSERT #F VALUES (1,10,1,'мастера производственного обучения')
INSERT #F VALUES (1,11,1,'педагогические работники общеобразовательных учреждений СПО')
INSERT #F VALUES (1,12,1,'из них преподаватели')
INSERT #F VALUES (1,13,1,'мастера производственного обучения')
INSERT #F VALUES (1,14,1,'педагогические работники учреждений дополнительного профессионального образования, осуществляющие подготовку (повышение квалификации) специалистов, имеющих среднее профессиональное образование')
INSERT #F VALUES (1,15,1,'из них преподаватели')
INSERT #F VALUES (1,16,1,'мастера производственного обучения')
INSERT #F VALUES (1,17,1,'профессорско-преподавательский состав учреждений ВПО')
INSERT #F VALUES (1,18,1,'профессорско-преподавательский состав учреждений дополнительного профессионального образования, осуществляющие подготовку (повышение квалификации) специалистов, имеющих высшее профессиональное образование')
INSERT #F VALUES (1,19,1,'научные работники учреждений ВПО')
INSERT #F VALUES (1,20,1,'из них научные сотрудники')
INSERT #F VALUES (1,21,1,'научные работники учреждений дополнительного профессионального образования')
INSERT #F VALUES (1,22,1,'из них научные сотрудники')
INSERT #F VALUES (1,23,1,'врачи')
INSERT #F VALUES (1,24,1,'средний медицинский персонал')
INSERT #F VALUES (1,25,1,'младший медицинский персонал')
INSERT #F VALUES (1,26,1,'работники культуры')
INSERT #F VALUES (1,27,1,'социальные работники')
INSERT #F VALUES (1,28,1,'прочий персонал')
INSERT #F VALUES (1,1,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,2,2,'101                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,3,2,'102                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,4,2,'201                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,5,2,'211                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,6,2,'212                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,7,2,'221                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,8,2,'231                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,9,2,'232                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,10,2,'233                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,11,2,'241                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,12,2,'242                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,13,2,'243                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,14,2,'251                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,15,2,'252                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,16,2,'253                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,17,2,'261                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,18,2,'271                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,19,2,'301                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,20,2,'311                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,21,2,'301                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,22,2,'311                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,23,2,'401                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,24,2,'411                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,25,2,'421                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,26,2,'631                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,27,2,'501                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,28,2,'103                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,1,3,'01                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,2,3,'02                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,3,3,'03                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,4,3,'04                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,5,3,'05                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,6,3,'06                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,7,3,'07                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,8,3,'08                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,9,3,'09                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,10,3,'10                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,11,3,'11                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,12,3,'12                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,13,3,'13                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,14,3,'14                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,15,3,'15                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,16,3,'16                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,17,3,'17                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,18,3,'18                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,19,3,'19                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,20,3,'20                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,21,3,'21                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,22,3,'22                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,23,3,'23                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,24,3,'24                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,25,3,'25                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,26,3,'26                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,27,3,'27                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,28,3,'28                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,1,4,'НЗП_УСТАНОВКА() + НЗП_ЗНАЧЕНИЕ(''100'',4)')
INSERT #F VALUES (1,2,4,'НЗП_ЗНАЧЕНИЕ(''101'',4)')
INSERT #F VALUES (1,3,4,'НЗП_ЗНАЧЕНИЕ(''102'',4)')
INSERT #F VALUES (1,4,4,'НЗП_ЗНАЧЕНИЕ(''201'',4)')
INSERT #F VALUES (1,5,4,'НЗП_ЗНАЧЕНИЕ(''211'',4)')
INSERT #F VALUES (1,6,4,'НЗП_ЗНАЧЕНИЕ(''212'',4)')
INSERT #F VALUES (1,7,4,'НЗП_ЗНАЧЕНИЕ(''221'',4)')
INSERT #F VALUES (1,8,4,'НЗП_ЗНАЧЕНИЕ(''231'',4)')
INSERT #F VALUES (1,9,4,'НЗП_ЗНАЧЕНИЕ(''232'',4)')
INSERT #F VALUES (1,10,4,'НЗП_ЗНАЧЕНИЕ(''233'',4)')
INSERT #F VALUES (1,11,4,'НЗП_ЗНАЧЕНИЕ(''241'',4)')
INSERT #F VALUES (1,12,4,'НЗП_ЗНАЧЕНИЕ(''242'',4)')
INSERT #F VALUES (1,13,4,'НЗП_ЗНАЧЕНИЕ(''243'',4)')
INSERT #F VALUES (1,14,4,'НЗП_ЗНАЧЕНИЕ(''251'',4)')
INSERT #F VALUES (1,15,4,'НЗП_ЗНАЧЕНИЕ(''252'',4)')
INSERT #F VALUES (1,16,4,'НЗП_ЗНАЧЕНИЕ(''253'',4)')
INSERT #F VALUES (1,17,4,'НЗП_ЗНАЧЕНИЕ(''261'',4)')
INSERT #F VALUES (1,18,4,'НЗП_ЗНАЧЕНИЕ(''271'',4)')
INSERT #F VALUES (1,19,4,'НЗП_ЗНАЧЕНИЕ(''3011'',4)')
INSERT #F VALUES (1,20,4,'НЗП_ЗНАЧЕНИЕ(''3111'',4)')
INSERT #F VALUES (1,21,4,'НЗП_ЗНАЧЕНИЕ(''3012'',4)')
INSERT #F VALUES (1,22,4,'НЗП_ЗНАЧЕНИЕ(''3112'',4)')
INSERT #F VALUES (1,23,4,'НЗП_ЗНАЧЕНИЕ(''401'',4)')
INSERT #F VALUES (1,24,4,'НЗП_ЗНАЧЕНИЕ(''411'',4)')
INSERT #F VALUES (1,25,4,'НЗП_ЗНАЧЕНИЕ(''421'',4)')
INSERT #F VALUES (1,26,4,'НЗП_ЗНАЧЕНИЕ(''631'',4)')
INSERT #F VALUES (1,27,4,'НЗП_ЗНАЧЕНИЕ(''501'',4)')
INSERT #F VALUES (1,28,4,'НЗП_ЗНАЧЕНИЕ(''103'',4)')
INSERT #F VALUES (1,2,5,'НЗП_ЗНАЧЕНИЕ(''101'',5)')
INSERT #F VALUES (1,3,5,'НЗП_ЗНАЧЕНИЕ(''102'',5)')
INSERT #F VALUES (1,4,5,'НЗП_ЗНАЧЕНИЕ(''201'',5)')
INSERT #F VALUES (1,5,5,'НЗП_ЗНАЧЕНИЕ(''211'',5)')
INSERT #F VALUES (1,6,5,'НЗП_ЗНАЧЕНИЕ(''212'',5)')
INSERT #F VALUES (1,7,5,'НЗП_ЗНАЧЕНИЕ(''221'',5)')
INSERT #F VALUES (1,8,5,'НЗП_ЗНАЧЕНИЕ(''231'',5)')
INSERT #F VALUES (1,9,5,'НЗП_ЗНАЧЕНИЕ(''232'',5)')
INSERT #F VALUES (1,10,5,'НЗП_ЗНАЧЕНИЕ(''233'',5)')
INSERT #F VALUES (1,11,5,'НЗП_ЗНАЧЕНИЕ(''241'',5)')
INSERT #F VALUES (1,12,5,'НЗП_ЗНАЧЕНИЕ(''242'',5)')
INSERT #F VALUES (1,13,5,'НЗП_ЗНАЧЕНИЕ(''243'',5)')
INSERT #F VALUES (1,14,5,'НЗП_ЗНАЧЕНИЕ(''251'',5)')
INSERT #F VALUES (1,15,5,'НЗП_ЗНАЧЕНИЕ(''252'',5)')
INSERT #F VALUES (1,16,5,'НЗП_ЗНАЧЕНИЕ(''253'',5)')
INSERT #F VALUES (1,17,5,'НЗП_ЗНАЧЕНИЕ(''261'',5)')
INSERT #F VALUES (1,18,5,'НЗП_ЗНАЧЕНИЕ(''271'',5)')
INSERT #F VALUES (1,19,5,'НЗП_ЗНАЧЕНИЕ(''3011'',5)')
INSERT #F VALUES (1,20,5,'НЗП_ЗНАЧЕНИЕ(''3111'',5)')
INSERT #F VALUES (1,21,5,'НЗП_ЗНАЧЕНИЕ(''3012'',5)')
INSERT #F VALUES (1,22,5,'НЗП_ЗНАЧЕНИЕ(''3112'',5)')
INSERT #F VALUES (1,23,5,'НЗП_ЗНАЧЕНИЕ(''401'',5)')
INSERT #F VALUES (1,24,5,'НЗП_ЗНАЧЕНИЕ(''411'',5)')
INSERT #F VALUES (1,25,5,'НЗП_ЗНАЧЕНИЕ(''421'',5)')
INSERT #F VALUES (1,26,5,'НЗП_ЗНАЧЕНИЕ(''631'',5)')
INSERT #F VALUES (1,27,5,'НЗП_ЗНАЧЕНИЕ(''501'',5)')
INSERT #F VALUES (1,28,5,'НЗП_ЗНАЧЕНИЕ(''103'',5)')
INSERT #F VALUES (1,2,6,'НЗП_ЗНАЧЕНИЕ(''101'',6)')
INSERT #F VALUES (1,3,6,'НЗП_ЗНАЧЕНИЕ(''102'',6)')
INSERT #F VALUES (1,4,6,'НЗП_ЗНАЧЕНИЕ(''201'',6)')
INSERT #F VALUES (1,5,6,'НЗП_ЗНАЧЕНИЕ(''211'',6)')
INSERT #F VALUES (1,6,6,'НЗП_ЗНАЧЕНИЕ(''212'',6)')
INSERT #F VALUES (1,7,6,'НЗП_ЗНАЧЕНИЕ(''221'',6)')
INSERT #F VALUES (1,8,6,'НЗП_ЗНАЧЕНИЕ(''231'',6)')
INSERT #F VALUES (1,9,6,'НЗП_ЗНАЧЕНИЕ(''232'',6)')
INSERT #F VALUES (1,10,6,'НЗП_ЗНАЧЕНИЕ(''233'',6)')
INSERT #F VALUES (1,11,6,'НЗП_ЗНАЧЕНИЕ(''241'',6)')
INSERT #F VALUES (1,12,6,'НЗП_ЗНАЧЕНИЕ(''242'',6)')
INSERT #F VALUES (1,13,6,'НЗП_ЗНАЧЕНИЕ(''243'',6)')
INSERT #F VALUES (1,14,6,'НЗП_ЗНАЧЕНИЕ(''251'',6)')
INSERT #F VALUES (1,15,6,'НЗП_ЗНАЧЕНИЕ(''252'',6)')
INSERT #F VALUES (1,16,6,'НЗП_ЗНАЧЕНИЕ(''253'',6)')
INSERT #F VALUES (1,17,6,'НЗП_ЗНАЧЕНИЕ(''261'',6)')
INSERT #F VALUES (1,18,6,'НЗП_ЗНАЧЕНИЕ(''271'',6)')
INSERT #F VALUES (1,19,6,'НЗП_ЗНАЧЕНИЕ(''3011'',6)')
INSERT #F VALUES (1,20,6,'НЗП_ЗНАЧЕНИЕ(''3111'',6)')
INSERT #F VALUES (1,21,6,'НЗП_ЗНАЧЕНИЕ(''3012'',6)')
INSERT #F VALUES (1,22,6,'НЗП_ЗНАЧЕНИЕ(''3112'',6)')
INSERT #F VALUES (1,23,6,'НЗП_ЗНАЧЕНИЕ(''401'',6)')
INSERT #F VALUES (1,24,6,'НЗП_ЗНАЧЕНИЕ(''411'',6)')
INSERT #F VALUES (1,25,6,'НЗП_ЗНАЧЕНИЕ(''421'',6)')
INSERT #F VALUES (1,26,6,'НЗП_ЗНАЧЕНИЕ(''631'',6)')
INSERT #F VALUES (1,27,6,'НЗП_ЗНАЧЕНИЕ(''501'',6)')
INSERT #F VALUES (1,28,6,'НЗП_ЗНАЧЕНИЕ(''103'',6)')
INSERT #F VALUES (1,2,7,'НЗП_ЗНАЧЕНИЕ(''101'',7)')
INSERT #F VALUES (1,3,7,'НЗП_ЗНАЧЕНИЕ(''102'',7)')
INSERT #F VALUES (1,4,7,'НЗП_ЗНАЧЕНИЕ(''201'',7)')
INSERT #F VALUES (1,5,7,'НЗП_ЗНАЧЕНИЕ(''211'',7)')
INSERT #F VALUES (1,6,7,'НЗП_ЗНАЧЕНИЕ(''212'',7)')
INSERT #F VALUES (1,7,7,'НЗП_ЗНАЧЕНИЕ(''221'',7)')
INSERT #F VALUES (1,8,7,'НЗП_ЗНАЧЕНИЕ(''231'',7)')
INSERT #F VALUES (1,9,7,'НЗП_ЗНАЧЕНИЕ(''232'',7)')
INSERT #F VALUES (1,10,7,'НЗП_ЗНАЧЕНИЕ(''233'',7)')
INSERT #F VALUES (1,11,7,'НЗП_ЗНАЧЕНИЕ(''241'',7)')
INSERT #F VALUES (1,12,7,'НЗП_ЗНАЧЕНИЕ(''242'',7)')
INSERT #F VALUES (1,13,7,'НЗП_ЗНАЧЕНИЕ(''243'',7)')
INSERT #F VALUES (1,14,7,'НЗП_ЗНАЧЕНИЕ(''251'',7)')
INSERT #F VALUES (1,15,7,'НЗП_ЗНАЧЕНИЕ(''252'',7)')
INSERT #F VALUES (1,16,7,'НЗП_ЗНАЧЕНИЕ(''253'',7)')
INSERT #F VALUES (1,17,7,'НЗП_ЗНАЧЕНИЕ(''261'',7)')
INSERT #F VALUES (1,18,7,'НЗП_ЗНАЧЕНИЕ(''271'',7)')
INSERT #F VALUES (1,19,7,'НЗП_ЗНАЧЕНИЕ(''3011'',7)')
INSERT #F VALUES (1,20,7,'НЗП_ЗНАЧЕНИЕ(''3111'',7)')
INSERT #F VALUES (1,21,7,'НЗП_ЗНАЧЕНИЕ(''3012'',7)')
INSERT #F VALUES (1,22,7,'НЗП_ЗНАЧЕНИЕ(''3112'',7)')
INSERT #F VALUES (1,23,7,'НЗП_ЗНАЧЕНИЕ(''401'',7)')
INSERT #F VALUES (1,24,7,'НЗП_ЗНАЧЕНИЕ(''411'',7)')
INSERT #F VALUES (1,25,7,'НЗП_ЗНАЧЕНИЕ(''421'',7)')
INSERT #F VALUES (1,26,7,'НЗП_ЗНАЧЕНИЕ(''631'',7)')
INSERT #F VALUES (1,27,7,'НЗП_ЗНАЧЕНИЕ(''501'',7)')
INSERT #F VALUES (1,28,7,'НЗП_ЗНАЧЕНИЕ(''103'',7)')
INSERT #F VALUES (1,2,8,'НЗП_ЗНАЧЕНИЕ(''101'',8)')
INSERT #F VALUES (1,3,8,'НЗП_ЗНАЧЕНИЕ(''102'',8)')
INSERT #F VALUES (1,4,8,'НЗП_ЗНАЧЕНИЕ(''201'',8)')
INSERT #F VALUES (1,5,8,'НЗП_ЗНАЧЕНИЕ(''211'',8)')
INSERT #F VALUES (1,6,8,'НЗП_ЗНАЧЕНИЕ(''212'',8)')
INSERT #F VALUES (1,7,8,'НЗП_ЗНАЧЕНИЕ(''221'',8)')
INSERT #F VALUES (1,8,8,'НЗП_ЗНАЧЕНИЕ(''231'',8)')
INSERT #F VALUES (1,9,8,'НЗП_ЗНАЧЕНИЕ(''232'',8)')
INSERT #F VALUES (1,10,8,'НЗП_ЗНАЧЕНИЕ(''233'',8)')
INSERT #F VALUES (1,11,8,'НЗП_ЗНАЧЕНИЕ(''241'',8)')
INSERT #F VALUES (1,12,8,'НЗП_ЗНАЧЕНИЕ(''242'',8)')
INSERT #F VALUES (1,13,8,'НЗП_ЗНАЧЕНИЕ(''243'',8)')
INSERT #F VALUES (1,14,8,'НЗП_ЗНАЧЕНИЕ(''251'',8)')
INSERT #F VALUES (1,15,8,'НЗП_ЗНАЧЕНИЕ(''252'',8)')
INSERT #F VALUES (1,16,8,'НЗП_ЗНАЧЕНИЕ(''253'',8)')
INSERT #F VALUES (1,17,8,'НЗП_ЗНАЧЕНИЕ(''261'',8)')
INSERT #F VALUES (1,18,8,'НЗП_ЗНАЧЕНИЕ(''271'',8)')
INSERT #F VALUES (1,19,8,'НЗП_ЗНАЧЕНИЕ(''3011'',8)')
INSERT #F VALUES (1,20,8,'НЗП_ЗНАЧЕНИЕ(''3111'',8)')
INSERT #F VALUES (1,21,8,'НЗП_ЗНАЧЕНИЕ(''3012'',8)')
INSERT #F VALUES (1,22,8,'НЗП_ЗНАЧЕНИЕ(''3112'',8)')
INSERT #F VALUES (1,23,8,'НЗП_ЗНАЧЕНИЕ(''401'',8)')
INSERT #F VALUES (1,24,8,'НЗП_ЗНАЧЕНИЕ(''411'',8)')
INSERT #F VALUES (1,25,8,'НЗП_ЗНАЧЕНИЕ(''421'',8)')
INSERT #F VALUES (1,26,8,'НЗП_ЗНАЧЕНИЕ(''631'',8)')
INSERT #F VALUES (1,27,8,'НЗП_ЗНАЧЕНИЕ(''501'',8)')
INSERT #F VALUES (1,28,8,'НЗП_ЗНАЧЕНИЕ(''103'',8)')
INSERT #F VALUES (1,2,9,'НЗП_ЗНАЧЕНИЕ(''101'',9)')
INSERT #F VALUES (1,3,9,'НЗП_ЗНАЧЕНИЕ(''102'',9)')
INSERT #F VALUES (1,4,9,'НЗП_ЗНАЧЕНИЕ(''201'',9)')
INSERT #F VALUES (1,5,9,'НЗП_ЗНАЧЕНИЕ(''211'',9)')
INSERT #F VALUES (1,6,9,'НЗП_ЗНАЧЕНИЕ(''212'',9)')
INSERT #F VALUES (1,7,9,'НЗП_ЗНАЧЕНИЕ(''221'',9)')
INSERT #F VALUES (1,8,9,'НЗП_ЗНАЧЕНИЕ(''231'',9)')
INSERT #F VALUES (1,9,9,'НЗП_ЗНАЧЕНИЕ(''232'',9)')
INSERT #F VALUES (1,10,9,'НЗП_ЗНАЧЕНИЕ(''233'',9)')
INSERT #F VALUES (1,11,9,'НЗП_ЗНАЧЕНИЕ(''241'',9)')
INSERT #F VALUES (1,12,9,'НЗП_ЗНАЧЕНИЕ(''242'',9)')
INSERT #F VALUES (1,13,9,'НЗП_ЗНАЧЕНИЕ(''243'',9)')
INSERT #F VALUES (1,14,9,'НЗП_ЗНАЧЕНИЕ(''251'',9)')
INSERT #F VALUES (1,15,9,'НЗП_ЗНАЧЕНИЕ(''252'',9)')
INSERT #F VALUES (1,16,9,'НЗП_ЗНАЧЕНИЕ(''253'',9)')
INSERT #F VALUES (1,17,9,'НЗП_ЗНАЧЕНИЕ(''261'',9)')
INSERT #F VALUES (1,18,9,'НЗП_ЗНАЧЕНИЕ(''271'',9)')
INSERT #F VALUES (1,19,9,'НЗП_ЗНАЧЕНИЕ(''3011'',9)')
INSERT #F VALUES (1,20,9,'НЗП_ЗНАЧЕНИЕ(''3111'',9)')
INSERT #F VALUES (1,21,9,'НЗП_ЗНАЧЕНИЕ(''3012'',9)')
INSERT #F VALUES (1,22,9,'НЗП_ЗНАЧЕНИЕ(''3112'',9)')
INSERT #F VALUES (1,23,9,'НЗП_ЗНАЧЕНИЕ(''401'',9)')
INSERT #F VALUES (1,24,9,'НЗП_ЗНАЧЕНИЕ(''411'',9)')
INSERT #F VALUES (1,25,9,'НЗП_ЗНАЧЕНИЕ(''421'',9)')
INSERT #F VALUES (1,26,9,'НЗП_ЗНАЧЕНИЕ(''631'',9)')
INSERT #F VALUES (1,27,9,'НЗП_ЗНАЧЕНИЕ(''501'',9)')
INSERT #F VALUES (1,28,9,'НЗП_ЗНАЧЕНИЕ(''103'',9)')
INSERT #F VALUES (1,2,10,'НЗП_ЗНАЧЕНИЕ(''101'',10)')
INSERT #F VALUES (1,3,10,'НЗП_ЗНАЧЕНИЕ(''102'',10)')
INSERT #F VALUES (1,4,10,'НЗП_ЗНАЧЕНИЕ(''201'',10)')
INSERT #F VALUES (1,5,10,'НЗП_ЗНАЧЕНИЕ(''211'',10)')
INSERT #F VALUES (1,6,10,'НЗП_ЗНАЧЕНИЕ(''212'',10)')
INSERT #F VALUES (1,7,10,'НЗП_ЗНАЧЕНИЕ(''221'',10)')
INSERT #F VALUES (1,8,10,'НЗП_ЗНАЧЕНИЕ(''231'',10)')
INSERT #F VALUES (1,9,10,'НЗП_ЗНАЧЕНИЕ(''232'',10)')
INSERT #F VALUES (1,10,10,'НЗП_ЗНАЧЕНИЕ(''233'',10)')
INSERT #F VALUES (1,11,10,'НЗП_ЗНАЧЕНИЕ(''241'',10)')
INSERT #F VALUES (1,12,10,'НЗП_ЗНАЧЕНИЕ(''242'',10)')
INSERT #F VALUES (1,13,10,'НЗП_ЗНАЧЕНИЕ(''243'',10)')
INSERT #F VALUES (1,14,10,'НЗП_ЗНАЧЕНИЕ(''251'',10)')
INSERT #F VALUES (1,15,10,'НЗП_ЗНАЧЕНИЕ(''252'',10)')
INSERT #F VALUES (1,16,10,'НЗП_ЗНАЧЕНИЕ(''253'',10)')
INSERT #F VALUES (1,17,10,'НЗП_ЗНАЧЕНИЕ(''261'',10)')
INSERT #F VALUES (1,18,10,'НЗП_ЗНАЧЕНИЕ(''271'',10)')
INSERT #F VALUES (1,19,10,'НЗП_ЗНАЧЕНИЕ(''3011'',10)')
INSERT #F VALUES (1,20,10,'НЗП_ЗНАЧЕНИЕ(''3111'',10)')
INSERT #F VALUES (1,21,10,'НЗП_ЗНАЧЕНИЕ(''3012'',10)')
INSERT #F VALUES (1,22,10,'НЗП_ЗНАЧЕНИЕ(''3112'',10)')
INSERT #F VALUES (1,23,10,'НЗП_ЗНАЧЕНИЕ(''401'',10)')
INSERT #F VALUES (1,24,10,'НЗП_ЗНАЧЕНИЕ(''411'',10)')
INSERT #F VALUES (1,25,10,'НЗП_ЗНАЧЕНИЕ(''421'',10)')
INSERT #F VALUES (1,26,10,'НЗП_ЗНАЧЕНИЕ(''631'',10)')
INSERT #F VALUES (1,27,10,'НЗП_ЗНАЧЕНИЕ(''501'',10)')
INSERT #F VALUES (1,28,10,'НЗП_ЗНАЧЕНИЕ(''103'',10)')
INSERT #F VALUES (1,2,11,'НЗП_ЗНАЧЕНИЕ(''101'',11)')
INSERT #F VALUES (1,3,11,'НЗП_ЗНАЧЕНИЕ(''102'',11)')
INSERT #F VALUES (1,4,11,'НЗП_ЗНАЧЕНИЕ(''201'',11)')
INSERT #F VALUES (1,5,11,'НЗП_ЗНАЧЕНИЕ(''211'',11)')
INSERT #F VALUES (1,6,11,'НЗП_ЗНАЧЕНИЕ(''212'',11)')
INSERT #F VALUES (1,7,11,'НЗП_ЗНАЧЕНИЕ(''221'',11)')
INSERT #F VALUES (1,8,11,'НЗП_ЗНАЧЕНИЕ(''231'',11)')
INSERT #F VALUES (1,9,11,'НЗП_ЗНАЧЕНИЕ(''232'',11)')
INSERT #F VALUES (1,10,11,'НЗП_ЗНАЧЕНИЕ(''233'',11)')
INSERT #F VALUES (1,11,11,'НЗП_ЗНАЧЕНИЕ(''241'',11)')
INSERT #F VALUES (1,12,11,'НЗП_ЗНАЧЕНИЕ(''242'',11)')
INSERT #F VALUES (1,13,11,'НЗП_ЗНАЧЕНИЕ(''243'',11)')
INSERT #F VALUES (1,14,11,'НЗП_ЗНАЧЕНИЕ(''251'',11)')
INSERT #F VALUES (1,15,11,'НЗП_ЗНАЧЕНИЕ(''252'',11)')
INSERT #F VALUES (1,16,11,'НЗП_ЗНАЧЕНИЕ(''253'',11)')
INSERT #F VALUES (1,17,11,'НЗП_ЗНАЧЕНИЕ(''261'',11)')
INSERT #F VALUES (1,18,11,'НЗП_ЗНАЧЕНИЕ(''271'',11)')
INSERT #F VALUES (1,19,11,'НЗП_ЗНАЧЕНИЕ(''3011'',11)')
INSERT #F VALUES (1,20,11,'НЗП_ЗНАЧЕНИЕ(''3111'',11)')
INSERT #F VALUES (1,21,11,'НЗП_ЗНАЧЕНИЕ(''3012'',11)')
INSERT #F VALUES (1,22,11,'НЗП_ЗНАЧЕНИЕ(''3112'',11)')
INSERT #F VALUES (1,23,11,'НЗП_ЗНАЧЕНИЕ(''401'',11)')
INSERT #F VALUES (1,24,11,'НЗП_ЗНАЧЕНИЕ(''411'',11)')
INSERT #F VALUES (1,25,11,'НЗП_ЗНАЧЕНИЕ(''421'',11)')
INSERT #F VALUES (1,26,11,'НЗП_ЗНАЧЕНИЕ(''631'',11)')
INSERT #F VALUES (1,27,11,'НЗП_ЗНАЧЕНИЕ(''501'',11)')
INSERT #F VALUES (1,28,11,'НЗП_ЗНАЧЕНИЕ(''103'',11)')
INSERT #F VALUES (1,2,12,'НЗП_ЗНАЧЕНИЕ(''101'',12)')
INSERT #F VALUES (1,3,12,'НЗП_ЗНАЧЕНИЕ(''102'',12)')
INSERT #F VALUES (1,4,12,'НЗП_ЗНАЧЕНИЕ(''201'',12)')
INSERT #F VALUES (1,5,12,'НЗП_ЗНАЧЕНИЕ(''211'',12)')
INSERT #F VALUES (1,6,12,'НЗП_ЗНАЧЕНИЕ(''212'',12)')
INSERT #F VALUES (1,7,12,'НЗП_ЗНАЧЕНИЕ(''221'',12)')
INSERT #F VALUES (1,8,12,'НЗП_ЗНАЧЕНИЕ(''231'',12)')
INSERT #F VALUES (1,9,12,'НЗП_ЗНАЧЕНИЕ(''232'',12)')
INSERT #F VALUES (1,10,12,'НЗП_ЗНАЧЕНИЕ(''233'',12)')
INSERT #F VALUES (1,11,12,'НЗП_ЗНАЧЕНИЕ(''241'',12)')
INSERT #F VALUES (1,12,12,'НЗП_ЗНАЧЕНИЕ(''242'',12)')
INSERT #F VALUES (1,13,12,'НЗП_ЗНАЧЕНИЕ(''243'',12)')
INSERT #F VALUES (1,14,12,'НЗП_ЗНАЧЕНИЕ(''251'',12)')
INSERT #F VALUES (1,15,12,'НЗП_ЗНАЧЕНИЕ(''252'',12)')
INSERT #F VALUES (1,16,12,'НЗП_ЗНАЧЕНИЕ(''253'',12)')
INSERT #F VALUES (1,17,12,'НЗП_ЗНАЧЕНИЕ(''261'',12)')
INSERT #F VALUES (1,18,12,'НЗП_ЗНАЧЕНИЕ(''271'',12)')
INSERT #F VALUES (1,19,12,'НЗП_ЗНАЧЕНИЕ(''3011'',12)')
INSERT #F VALUES (1,20,12,'НЗП_ЗНАЧЕНИЕ(''3111'',12)')
INSERT #F VALUES (1,21,12,'НЗП_ЗНАЧЕНИЕ(''3012'',12)')
INSERT #F VALUES (1,22,12,'НЗП_ЗНАЧЕНИЕ(''3112,12)')
INSERT #F VALUES (1,23,12,'НЗП_ЗНАЧЕНИЕ(''401'',12)')
INSERT #F VALUES (1,24,12,'НЗП_ЗНАЧЕНИЕ(''411'',12)')
INSERT #F VALUES (1,25,12,'НЗП_ЗНАЧЕНИЕ(''421'',12)')
INSERT #F VALUES (1,26,12,'НЗП_ЗНАЧЕНИЕ(''631'',12)')
INSERT #F VALUES (1,27,12,'НЗП_ЗНАЧЕНИЕ(''501'',12)')
INSERT #F VALUES (1,28,12,'НЗП_ЗНАЧЕНИЕ(''103'',12)')
INSERT #F VALUES (1,2,13,'НЗП_ЗНАЧЕНИЕ(''101'',13)')
INSERT #F VALUES (1,3,13,'НЗП_ЗНАЧЕНИЕ(''102'',13)')
INSERT #F VALUES (1,4,13,'НЗП_ЗНАЧЕНИЕ(''201'',13)')
INSERT #F VALUES (1,5,13,'НЗП_ЗНАЧЕНИЕ(''211'',13)')
INSERT #F VALUES (1,6,13,'НЗП_ЗНАЧЕНИЕ(''212'',13)')
INSERT #F VALUES (1,7,13,'НЗП_ЗНАЧЕНИЕ(''221'',13)')
INSERT #F VALUES (1,8,13,'НЗП_ЗНАЧЕНИЕ(''231'',13)')
INSERT #F VALUES (1,9,13,'НЗП_ЗНАЧЕНИЕ(''232'',13)')
INSERT #F VALUES (1,10,13,'НЗП_ЗНАЧЕНИЕ(''233'',13)')
INSERT #F VALUES (1,11,13,'НЗП_ЗНАЧЕНИЕ(''241'',13)')
INSERT #F VALUES (1,12,13,'НЗП_ЗНАЧЕНИЕ(''242'',13)')
INSERT #F VALUES (1,13,13,'НЗП_ЗНАЧЕНИЕ(''243'',13)')
INSERT #F VALUES (1,14,13,'НЗП_ЗНАЧЕНИЕ(''251'',13)')
INSERT #F VALUES (1,15,13,'НЗП_ЗНАЧЕНИЕ(''252'',13)')
INSERT #F VALUES (1,16,13,'НЗП_ЗНАЧЕНИЕ(''253'',13)')
INSERT #F VALUES (1,17,13,'НЗП_ЗНАЧЕНИЕ(''261'',13)')
INSERT #F VALUES (1,18,13,'НЗП_ЗНАЧЕНИЕ(''271'',13)')
INSERT #F VALUES (1,19,13,'НЗП_ЗНАЧЕНИЕ(''3011'',13)')
INSERT #F VALUES (1,20,13,'НЗП_ЗНАЧЕНИЕ(''3111'',13)')
INSERT #F VALUES (1,21,13,'НЗП_ЗНАЧЕНИЕ(''3012'',13)')
INSERT #F VALUES (1,22,13,'НЗП_ЗНАЧЕНИЕ(''3112'',3)')
INSERT #F VALUES (1,23,13,'НЗП_ЗНАЧЕНИЕ(''401'',13)')
INSERT #F VALUES (1,24,13,'НЗП_ЗНАЧЕНИЕ(''411'',13)')
INSERT #F VALUES (1,25,13,'НЗП_ЗНАЧЕНИЕ(''421'',13)')
INSERT #F VALUES (1,26,13,'НЗП_ЗНАЧЕНИЕ(''631'',13)')
INSERT #F VALUES (1,27,13,'НЗП_ЗНАЧЕНИЕ(''501'',13)')
INSERT #F VALUES (1,28,13,'НЗП_ЗНАЧЕНИЕ(''103'',13)')
INSERT #F VALUES (1,2,14,'НЗП_ЗНАЧЕНИЕ(''101'',14)')
INSERT #F VALUES (1,3,14,'НЗП_ЗНАЧЕНИЕ(''102'',14)')
INSERT #F VALUES (1,4,14,'НЗП_ЗНАЧЕНИЕ(''201'',14)')
INSERT #F VALUES (1,5,14,'НЗП_ЗНАЧЕНИЕ(''211'',14)')
INSERT #F VALUES (1,6,14,'НЗП_ЗНАЧЕНИЕ(''212'',14)')
INSERT #F VALUES (1,7,14,'НЗП_ЗНАЧЕНИЕ(''221'',14)')
INSERT #F VALUES (1,8,14,'НЗП_ЗНАЧЕНИЕ(''231'',14)')
INSERT #F VALUES (1,9,14,'НЗП_ЗНАЧЕНИЕ(''232'',14)')
INSERT #F VALUES (1,10,14,'НЗП_ЗНАЧЕНИЕ(''233'',14)')
INSERT #F VALUES (1,11,14,'НЗП_ЗНАЧЕНИЕ(''241'',14)')
INSERT #F VALUES (1,12,14,'НЗП_ЗНАЧЕНИЕ(''242'',14)')
INSERT #F VALUES (1,13,14,'НЗП_ЗНАЧЕНИЕ(''243'',14)')
INSERT #F VALUES (1,14,14,'НЗП_ЗНАЧЕНИЕ(''251'',14)')
INSERT #F VALUES (1,15,14,'НЗП_ЗНАЧЕНИЕ(''252'',14)')
INSERT #F VALUES (1,16,14,'НЗП_ЗНАЧЕНИЕ(''253'',14)')
INSERT #F VALUES (1,17,14,'НЗП_ЗНАЧЕНИЕ(''261'',14)')
INSERT #F VALUES (1,18,14,'НЗП_ЗНАЧЕНИЕ(''271'',14)')
INSERT #F VALUES (1,19,14,'НЗП_ЗНАЧЕНИЕ(''3011'',14)')
INSERT #F VALUES (1,20,14,'НЗП_ЗНАЧЕНИЕ(''3111'',14)')
INSERT #F VALUES (1,21,14,'НЗП_ЗНАЧЕНИЕ(''3012'',14)')
INSERT #F VALUES (1,22,14,'НЗП_ЗНАЧЕНИЕ(''3112'',14)')
INSERT #F VALUES (1,23,14,'НЗП_ЗНАЧЕНИЕ(''401'',14)')
INSERT #F VALUES (1,24,14,'НЗП_ЗНАЧЕНИЕ(''411'',14)')
INSERT #F VALUES (1,25,14,'НЗП_ЗНАЧЕНИЕ(''421'',14)')
INSERT #F VALUES (1,26,14,'НЗП_ЗНАЧЕНИЕ(''631'',14)')
INSERT #F VALUES (1,27,14,'НЗП_ЗНАЧЕНИЕ(''501'',14)')
INSERT #F VALUES (1,28,14,'НЗП_ЗНАЧЕНИЕ(''103'',14)')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 382
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'т.1стр.01 =  т.1стр.02 +  т.1стр.03 +  т.1стр.05 +  т.1стр.07 +  т.1стр.08 +  т.1стр.11 +  т.1стр.14 +  т.1стр.18 +  т.1стр.19 +  т.1стр.17 +  т.1стр.04 +  т.1стр.21 +  т.1стр.23 +  т.1стр.24 +  т.1стр.25 +  т.1стр.26 +  т.1стр.27 +  т.1стр.28',1,3,1,'20130912','','','','0606048','20130601','','=',2,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 1
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','01','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','02','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','03','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','05','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','07','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','08','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','11','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','14','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,9,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','18','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,10,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','19','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,11,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','17','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,12,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','04','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,13,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','21','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,14,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','23','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,15,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','24','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,16,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','25','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,17,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','26','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,18,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','27','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,19,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','28','1',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 19
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '451       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'451','Республика Коми',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '606       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'606','Заработная плата',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-02-07 09:17:29.133',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-02-07 09:17:29.133'
	BEGIN
		SELECT @vcMessage = 'Форма 0606048 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0606048 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-02-07 09:17:29.133. Обновление отклонено.'
	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. (фев  7 2014  9:17:36:133AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : 0606049 (Сведения о численности и оплате труда работников сферы социального обслуживания по категориям персонала)
-- Дата ввода : 20130601
-- Дата окончания действия :
-- Версия : 2014-02-07 09:17:36.123
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

SET NOCOUNT               ON
SET ANSI_NULLS            ON  -- Правильная обработка NULL.
SET ANSI_WARNINGS         ON  -- При возникновении ошибки транзакция не прерывается.
SET IMPLICIT_TRANSACTIONS OFF -- Режим явного определения транзакций.
SET LOCK_TIMEOUT          -1  -- Бесконечное время ожидания разблокировки ресурсов.

BEGIN TRANSACTION         -- Начало новой транзакции.
SAVE TRANSACTION SaveTran -- Создание точки сохранения.

DECLARE @iERROR INT, @iLINK_FORM INT, @iLINK_TABLE INT, @iFORM_TYPE INT,
        @iLINK_COL INT, @iLINK_CODE_COL INT, @iLINK_ROW INT, @iLINK_TOTAL INT,
        @iOLD_FORM_LINK INT, @vcNEW_FORM_CODE VARCHAR(20), @dNEW_START_DATE DATETIME, @dOLD_UPDATE_DATE DATETIME

IF OBJECT_ID('tempdb..#tabErrorLog') IS NOT NULL
BEGIN
   DROP TABLE #tabErrorLog
END
CREATE TABLE #tabErrorLog([PROC] VARCHAR(250),[ERROR] INT)

IF OBJECT_ID('tempdb..#tabStop') IS NOT NULL
BEGIN
   DROP TABLE #tabStop
END
CREATE TABLE #tabStop([CURRENT_DATE] VARCHAR(100))

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabStop',@iERROR)
END

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL
BEGIN
   DROP TABLE #tabInfo
END
CREATE TABLE #tabInfo([LINK_FORM] INT, [LINK_FORM_NEW] INT)

SET @iERROR = @@ERROR
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #tabInfo',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Определение старой формы текущей версии. Изменение ее кода, чтобы не мешать установке новой формы.
SELECT @iOLD_FORM_LINK = [LINK_FORM], @dOLD_UPDATE_DATE = [UPDATE_DATE]FROM dbo.[REPORT_FORMS] WHERE [CODE] = '0606049' AND [START_DATE] = '20130601'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-02-07 09:17:36.123',121)
BEGIN
   INSERT #tabStop VALUES(CONVERT(VARCHAR(50),@dOLD_UPDATE_DATE,121))
END

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

IF @iOLD_FORM_LINK IS NOT NULL
BEGIN
   SET @vcNEW_FORM_CODE = LEFT('NEW_' + '0606049',20)
   SELECT @dNEW_START_DATE = MAX([START_DATE]) + 1    FROM dbo.[REPORT_FORMS]    WHERE [CODE] = @vcNEW_FORM_CODE
END
ELSE BEGIN
   SET @vcNEW_FORM_CODE = '0606049'
END

SET @dNEW_START_DATE = ISNULL(@dNEW_START_DATE,'20130601')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_FORMS.
SELECT @iFORM_TYPE = [LINK] FROM dbo.[S_OBJECTS] WHERE [CODE] = 'SALARY'
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_FORMS]  @iLINK_FORM OUTPUT,'Сведения о численности и оплате труда работников сферы социального обслуживания по категориям персонала',@vcNEW_FORM_CODE,@dNEW_START_DATE,6,1,1,1,2291,'RA_EXPORT_FORM',0,0,'19000101',NULL,''
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_FORMS',@iERROR)
END

EXEC @iERROR = dbo.[RN_REPORT_SAVE_REPORT_FORMS_PART2]  @iLINK_FORM, '','sv_0606049_20130101.bas','','KirRepMakerMultiSheet.xls','sv_0606049_20130101.xlt','',NULL,'RA_EXPORT_FORM',0,NULL,NULL,NULL,'          ','REPORTS_ATR_TYPE_ORG,REPORTS_FILTER_SUBDIV',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Таблица', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Категория персонала',@iLINK_TABLE,0,1,1,0,2000,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код категории персонала',@iLINK_TABLE,1,1,2,0,3,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'№ строки',@iLINK_TABLE,1,1,3,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Средняя численность работников, человек: списочного состава',@iLINK_TABLE,1,0,4,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Средняя численность работников, человек:внешних совместителей',@iLINK_TABLE,1,0,5,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'Фонд начисленной ЗП работников за отчетный период списочного состава:всего',@iLINK_TABLE,1,0,6,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'Фонд начисленной ЗП работников за отчетный период списочного состава:в том числе по внутреннему совместительству',@iLINK_TABLE,1,0,7,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'Фонд начисленной ЗП работников за отчетный период списочного состава: внешних совместителей',@iLINK_TABLE,1,0,8,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 9,'Фонд начисленной ЗП работников по источникам финансирования(из гр.3) за счет средств бюджетов всех уровней',@iLINK_TABLE,1,0,9,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 10,'Фонд начисленной ЗП работников по источникам финансирования(из гр. 3) ОМС',@iLINK_TABLE,1,0,10,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 11,'Фонд начисленной ЗП работников по источникам финансирования(из гр.3) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,11,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 12,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) за счет средств бюджетов всех уровней',@iLINK_TABLE,1,0,12,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 13,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ОМС',@iLINK_TABLE,1,0,13,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 14,'Фонд начисленной ЗП работников по источникам финансирования(из гр.5) ср-ва от при-носящей доход деятель-ности',@iLINK_TABLE,1,0,14,0,1,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Таблица', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (1,1,1,1)
INSERT #R VALUES (2,1,4,1)
INSERT #R VALUES (3,1,5,1)
INSERT #R VALUES (4,1,6,1)
INSERT #R VALUES (5,1,7,1)
INSERT #R VALUES (6,1,8,1)
INSERT #R VALUES (7,1,9,1)
INSERT #R VALUES (8,1,10,1)
INSERT #R VALUES (9,1,11,1)
INSERT #R VALUES (10,1,12,1)
INSERT #R VALUES (11,1,13,1)
INSERT #R VALUES (12,1,14,1)
INSERT #R VALUES (13,1,14,1)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #R) <> 13
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #R',0)
END

ALTER TABLE dbo.[REPORT_ROWS] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_ROWS] ([ORDERS],
                          [LINK_TABLE],
                          [CALC_ORDERS],
                          [PRINT_NULL])
SELECT [C].[ORDERS],
       [B].[LINK_TABLE],
       [C].[CALC_ORDERS],
       [C].[PRINT_NULL]
FROM #tabInfo            [A]
JOIN dbo.[REPORT_TABLES] [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN #R                  [C] ON [B].[ORDERS] = [C].[LINK_TABLE]

ALTER TABLE dbo.[REPORT_ROWS] ENABLE TRIGGER ALL

DROP TABLE #R

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

-- Выгрузка REPORT_FORMULA.
IF OBJECT_ID('tempdb..#F') IS NOT NULL
BEGIN
   DROP TABLE #F
END

CREATE TABLE #F([ORDER_TABLE] INT,
                [ORDER_ROW]   INT,
                [ORDER_COL]   INT,
                [FORMULA]  VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #F',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
INSERT #F VALUES (1,1,1,'Всего работников (сумма строк 02 - 04, 06 - 08, 10 - 13)')
INSERT #F VALUES (1,2,1,'в том числе: руководитель организации')
INSERT #F VALUES (1,3,1,'заместители руководителя и руководители структурных подразделений (кроме врачей - руководителей структурных подразделений), иные руководители')
INSERT #F VALUES (1,4,1,'педагогические работники')
INSERT #F VALUES (1,5,1,'из них преподаватели')
INSERT #F VALUES (1,6,1,'врачи (кроме зубных), включая врачей - руководителей структурных подразделений')
INSERT #F VALUES (1,7,1,'социальные работники')
INSERT #F VALUES (1,8,1,'научные работники')
INSERT #F VALUES (1,9,1,'из них научные сотрудники')
INSERT #F VALUES (1,10,1,'средний медицинский (фармацевтический) персонал (персонал, обеспечивающий предоставление медицинских услуг)')
INSERT #F VALUES (1,11,1,'младший медицинский (фармацевтический) персонал (персонал, обеспечивающий предоставление медицинских услуг)')
INSERT #F VALUES (1,12,1,'работники, имеющие высшее фармацевтическое или иное высшее образование, предоставляющие медицинские услуги (обеспечивающие предоставление медицинских услуг)')
INSERT #F VALUES (1,13,1,'прочий персонал')
INSERT #F VALUES (1,1,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,2,2,'101                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,3,2,'102                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,4,2,'281                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,5,2,'282                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,6,2,'401                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,7,2,'501                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,8,2,'301                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,9,2,'311                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,10,2,'411                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,11,2,'421                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,12,2,'431                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,13,2,'103                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (1,1,3,'01                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,2,3,'02                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,3,3,'03                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,4,3,'04                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,5,3,'05                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,6,3,'06                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,7,3,'07                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,8,3,'08                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,9,3,'09                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,10,3,'10                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,11,3,'11                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,12,3,'12                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,13,3,'13                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (1,1,4,'НЗП_УСТАНОВКА() + НЗП_ЗНАЧЕНИЕ(''100'',4)')
INSERT #F VALUES (1,2,4,'НЗП_ЗНАЧЕНИЕ(''101'',4)')
INSERT #F VALUES (1,3,4,'НЗП_ЗНАЧЕНИЕ(''102'',4)')
INSERT #F VALUES (1,4,4,'НЗП_ЗНАЧЕНИЕ(''281'',4)')
INSERT #F VALUES (1,5,4,'НЗП_ЗНАЧЕНИЕ(''282'',4)')
INSERT #F VALUES (1,6,4,'НЗП_ЗНАЧЕНИЕ(''401'',4)')
INSERT #F VALUES (1,7,4,'НЗП_ЗНАЧЕНИЕ(''501'',4)')
INSERT #F VALUES (1,8,4,'НЗП_ЗНАЧЕНИЕ(''3013'',4)')
INSERT #F VALUES (1,9,4,'НЗП_ЗНАЧЕНИЕ(''3113'',4)')
INSERT #F VALUES (1,10,4,'НЗП_ЗНАЧЕНИЕ(''411'',4)')
INSERT #F VALUES (1,11,4,'НЗП_ЗНАЧЕНИЕ(''421'',4)')
INSERT #F VALUES (1,12,4,'НЗП_ЗНАЧЕНИЕ(''431'',4)')
INSERT #F VALUES (1,13,4,'НЗП_ЗНАЧЕНИЕ(''103'',4)')
INSERT #F VALUES (1,2,5,'НЗП_ЗНАЧЕНИЕ(''101'',5)')
INSERT #F VALUES (1,3,5,'НЗП_ЗНАЧЕНИЕ(''102'',5)')
INSERT #F VALUES (1,4,5,'НЗП_ЗНАЧЕНИЕ(''281'',5)')
INSERT #F VALUES (1,5,5,'НЗП_ЗНАЧЕНИЕ(''282'',5)')
INSERT #F VALUES (1,6,5,'НЗП_ЗНАЧЕНИЕ(''401'',5)')
INSERT #F VALUES (1,7,5,'НЗП_ЗНАЧЕНИЕ(''501'',5)')
INSERT #F VALUES (1,8,5,'НЗП_ЗНАЧЕНИЕ(''3013'',5)')
INSERT #F VALUES (1,9,5,'НЗП_ЗНАЧЕНИЕ(''3113'',5)')
INSERT #F VALUES (1,10,5,'НЗП_ЗНАЧЕНИЕ(''411'',5)')
INSERT #F VALUES (1,11,5,'НЗП_ЗНАЧЕНИЕ(''421'',5)')
INSERT #F VALUES (1,12,5,'НЗП_ЗНАЧЕНИЕ(''431'',5)')
INSERT #F VALUES (1,13,5,'НЗП_ЗНАЧЕНИЕ(''103'',5)')
INSERT #F VALUES (1,2,6,'НЗП_ЗНАЧЕНИЕ(''101'',6)')
INSERT #F VALUES (1,3,6,'НЗП_ЗНАЧЕНИЕ(''102'',6)')
INSERT #F VALUES (1,4,6,'НЗП_ЗНАЧЕНИЕ(''281'',6)')
INSERT #F VALUES (1,5,6,'НЗП_ЗНАЧЕНИЕ(''282'',6)')
INSERT #F VALUES (1,6,6,'НЗП_ЗНАЧЕНИЕ(''401'',6)')
INSERT #F VALUES (1,7,6,'НЗП_ЗНАЧЕНИЕ(''501'',6)')
INSERT #F VALUES (1,8,6,'НЗП_ЗНАЧЕНИЕ(''3013'',6)')
INSERT #F VALUES (1,9,6,'НЗП_ЗНАЧЕНИЕ(''3113'',6)')
INSERT #F VALUES (1,10,6,'НЗП_ЗНАЧЕНИЕ(''411'',6)')
INSERT #F VALUES (1,11,6,'НЗП_ЗНАЧЕНИЕ(''421'',6)')
INSERT #F VALUES (1,12,6,'НЗП_ЗНАЧЕНИЕ(''431'',6)')
INSERT #F VALUES (1,13,6,'НЗП_ЗНАЧЕНИЕ(''103'',6)')
INSERT #F VALUES (1,2,7,'НЗП_ЗНАЧЕНИЕ(''101'',7)')
INSERT #F VALUES (1,3,7,'НЗП_ЗНАЧЕНИЕ(''102'',7)')
INSERT #F VALUES (1,4,7,'НЗП_ЗНАЧЕНИЕ(''281'',7)')
INSERT #F VALUES (1,5,7,'НЗП_ЗНАЧЕНИЕ(''282'',7)')
INSERT #F VALUES (1,6,7,'НЗП_ЗНАЧЕНИЕ(''401'',7)')
INSERT #F VALUES (1,7,7,'НЗП_ЗНАЧЕНИЕ(''501'',7)')
INSERT #F VALUES (1,8,7,'НЗП_ЗНАЧЕНИЕ(''3013'',7)')
INSERT #F VALUES (1,9,7,'НЗП_ЗНАЧЕНИЕ(''3113'',7)')
INSERT #F VALUES (1,10,7,'НЗП_ЗНАЧЕНИЕ(''411'',7)')
INSERT #F VALUES (1,11,7,'НЗП_ЗНАЧЕНИЕ(''421'',7)')
INSERT #F VALUES (1,12,7,'НЗП_ЗНАЧЕНИЕ(''431'',7)')
INSERT #F VALUES (1,13,7,'НЗП_ЗНАЧЕНИЕ(''103'',7)')
INSERT #F VALUES (1,2,8,'НЗП_ЗНАЧЕНИЕ(''101'',8)')
INSERT #F VALUES (1,3,8,'НЗП_ЗНАЧЕНИЕ(''102'',8)')
INSERT #F VALUES (1,4,8,'НЗП_ЗНАЧЕНИЕ(''281'',8)')
INSERT #F VALUES (1,5,8,'НЗП_ЗНАЧЕНИЕ(''282'',8)')
INSERT #F VALUES (1,6,8,'НЗП_ЗНАЧЕНИЕ(''401'',8)')
INSERT #F VALUES (1,7,8,'НЗП_ЗНАЧЕНИЕ(''501'',8)')
INSERT #F VALUES (1,8,8,'НЗП_ЗНАЧЕНИЕ(''3013'',8)')
INSERT #F VALUES (1,9,8,'НЗП_ЗНАЧЕНИЕ(''3113'',8)')
INSERT #F VALUES (1,10,8,'НЗП_ЗНАЧЕНИЕ(''411'',8)')
INSERT #F VALUES (1,11,8,'НЗП_ЗНАЧЕНИЕ(''421'',8)')
INSERT #F VALUES (1,12,8,'НЗП_ЗНАЧЕНИЕ(''431'',8)')
INSERT #F VALUES (1,13,8,'НЗП_ЗНАЧЕНИЕ(''103'',8)')
INSERT #F VALUES (1,2,9,'НЗП_ЗНАЧЕНИЕ(''101'',9)')
INSERT #F VALUES (1,3,9,'НЗП_ЗНАЧЕНИЕ(''102'',9)')
INSERT #F VALUES (1,4,9,'НЗП_ЗНАЧЕНИЕ(''281'',9)')
INSERT #F VALUES (1,5,9,'НЗП_ЗНАЧЕНИЕ(''282'',9)')
INSERT #F VALUES (1,6,9,'НЗП_ЗНАЧЕНИЕ(''401'',9)')
INSERT #F VALUES (1,7,9,'НЗП_ЗНАЧЕНИЕ(''501'',9)')
INSERT #F VALUES (1,8,9,'НЗП_ЗНАЧЕНИЕ(''3013'',9)')
INSERT #F VALUES (1,9,9,'НЗП_ЗНАЧЕНИЕ(''3113'',9)')
INSERT #F VALUES (1,10,9,'НЗП_ЗНАЧЕНИЕ(''411'',9)')
INSERT #F VALUES (1,11,9,'НЗП_ЗНАЧЕНИЕ(''421'',9)')
INSERT #F VALUES (1,12,9,'НЗП_ЗНАЧЕНИЕ(''431'',9)')
INSERT #F VALUES (1,13,9,'НЗП_ЗНАЧЕНИЕ(''103'',9)')
INSERT #F VALUES (1,2,10,'НЗП_ЗНАЧЕНИЕ(''101'',10)')
INSERT #F VALUES (1,3,10,'НЗП_ЗНАЧЕНИЕ(''102'',10)')
INSERT #F VALUES (1,4,10,'НЗП_ЗНАЧЕНИЕ(''281'',10)')
INSERT #F VALUES (1,5,10,'НЗП_ЗНАЧЕНИЕ(''282'',10)')
INSERT #F VALUES (1,6,10,'НЗП_ЗНАЧЕНИЕ(''401'',10)')
INSERT #F VALUES (1,7,10,'НЗП_ЗНАЧЕНИЕ(''501'',10)')
INSERT #F VALUES (1,8,10,'НЗП_ЗНАЧЕНИЕ(''3013'',10)')
INSERT #F VALUES (1,9,10,'НЗП_ЗНАЧЕНИЕ(''3113'',10)')
INSERT #F VALUES (1,10,10,'НЗП_ЗНАЧЕНИЕ(''411'',10)')
INSERT #F VALUES (1,11,10,'НЗП_ЗНАЧЕНИЕ(''421'',10)')
INSERT #F VALUES (1,12,10,'НЗП_ЗНАЧЕНИЕ(''431'',10)')
INSERT #F VALUES (1,13,10,'НЗП_ЗНАЧЕНИЕ(''103'',10)')
INSERT #F VALUES (1,2,11,'НЗП_ЗНАЧЕНИЕ(''101'',11)')
INSERT #F VALUES (1,3,11,'НЗП_ЗНАЧЕНИЕ(''102'',11)')
INSERT #F VALUES (1,4,11,'НЗП_ЗНАЧЕНИЕ(''281'',11)')
INSERT #F VALUES (1,5,11,'НЗП_ЗНАЧЕНИЕ(''282'',11)')
INSERT #F VALUES (1,6,11,'НЗП_ЗНАЧЕНИЕ(''401'',11)')
INSERT #F VALUES (1,7,11,'НЗП_ЗНАЧЕНИЕ(''501'',11)')
INSERT #F VALUES (1,8,11,'НЗП_ЗНАЧЕНИЕ(''3013'',11)')
INSERT #F VALUES (1,9,11,'НЗП_ЗНАЧЕНИЕ(''3113'',11)')
INSERT #F VALUES (1,10,11,'НЗП_ЗНАЧЕНИЕ(''411'',11)')
INSERT #F VALUES (1,11,11,'НЗП_ЗНАЧЕНИЕ(''421'',11)')
INSERT #F VALUES (1,12,11,'НЗП_ЗНАЧЕНИЕ(''431'',11)')
INSERT #F VALUES (1,13,11,'НЗП_ЗНАЧЕНИЕ(''103'',11)')
INSERT #F VALUES (1,2,12,'НЗП_ЗНАЧЕНИЕ(''101'',12)')
INSERT #F VALUES (1,3,12,'НЗП_ЗНАЧЕНИЕ(''102'',12)')
INSERT #F VALUES (1,4,12,'НЗП_ЗНАЧЕНИЕ(''281'',12)')
INSERT #F VALUES (1,5,12,'НЗП_ЗНАЧЕНИЕ(''282'',12)')
INSERT #F VALUES (1,6,12,'НЗП_ЗНАЧЕНИЕ(''401'',12)')
INSERT #F VALUES (1,7,12,'НЗП_ЗНАЧЕНИЕ(''501'',12)')
INSERT #F VALUES (1,8,12,'НЗП_ЗНАЧЕНИЕ(''3013'',12)')
INSERT #F VALUES (1,9,12,'НЗП_ЗНАЧЕНИЕ(''3113'',12)')
INSERT #F VALUES (1,10,12,'НЗП_ЗНАЧЕНИЕ(''411'',12)')
INSERT #F VALUES (1,11,12,'НЗП_ЗНАЧЕНИЕ(''421'',12)')
INSERT #F VALUES (1,12,12,'НЗП_ЗНАЧЕНИЕ(''431'',12)')
INSERT #F VALUES (1,13,12,'НЗП_ЗНАЧЕНИЕ(''103'',12)')
INSERT #F VALUES (1,2,13,'НЗП_ЗНАЧЕНИЕ(''101'',13)')
INSERT #F VALUES (1,3,13,'НЗП_ЗНАЧЕНИЕ(''102'',13)')
INSERT #F VALUES (1,4,13,'НЗП_ЗНАЧЕНИЕ(''281'',13)')
INSERT #F VALUES (1,5,13,'НЗП_ЗНАЧЕНИЕ(''282'',13)')
INSERT #F VALUES (1,6,13,'НЗП_ЗНАЧЕНИЕ(''401'',13)')
INSERT #F VALUES (1,7,13,'НЗП_ЗНАЧЕНИЕ(''501'',13)')
INSERT #F VALUES (1,8,13,'НЗП_ЗНАЧЕНИЕ(''3013'',13)')
INSERT #F VALUES (1,9,13,'НЗП_ЗНАЧЕНИЕ(''3113'',13)')
INSERT #F VALUES (1,10,13,'НЗП_ЗНАЧЕНИЕ(''411'',13)')
INSERT #F VALUES (1,11,13,'НЗП_ЗНАЧЕНИЕ(''421'',13)')
INSERT #F VALUES (1,12,13,'НЗП_ЗНАЧЕНИЕ(''431'',13)')
INSERT #F VALUES (1,13,13,'НЗП_ЗНАЧЕНИЕ(''103'',13)')
INSERT #F VALUES (1,2,14,'НЗП_ЗНАЧЕНИЕ(''101'',14)')
INSERT #F VALUES (1,3,14,'НЗП_ЗНАЧЕНИЕ(''102'',14)')
INSERT #F VALUES (1,4,14,'НЗП_ЗНАЧЕНИЕ(''281'',14)')
INSERT #F VALUES (1,5,14,'НЗП_ЗНАЧЕНИЕ(''282'',14)')
INSERT #F VALUES (1,6,14,'НЗП_ЗНАЧЕНИЕ(''401'',14)')
INSERT #F VALUES (1,7,14,'НЗП_ЗНАЧЕНИЕ(''501'',14)')
INSERT #F VALUES (1,8,14,'НЗП_ЗНАЧЕНИЕ(''3013'',14)')
INSERT #F VALUES (1,9,14,'НЗП_ЗНАЧЕНИЕ(''3113'',14)')
INSERT #F VALUES (1,10,14,'НЗП_ЗНАЧЕНИЕ(''411'',14)')
INSERT #F VALUES (1,11,14,'НЗП_ЗНАЧЕНИЕ(''421'',14)')
INSERT #F VALUES (1,12,14,'НЗП_ЗНАЧЕНИЕ(''431'',14)')
INSERT #F VALUES (1,13,14,'НЗП_ЗНАЧЕНИЕ(''103'',14)')

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #F) <> 172
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #F',0)
END

ALTER TABLE dbo.[REPORT_FORMULA] DISABLE TRIGGER ALL

INSERT dbo.[REPORT_FORMULA] ([LINK_ROW],
                             [LINK_COL],
                             [FORMULA])
SELECT [D].[LINK_ROW],
       [C].[LINK_COL],
       [E].[FORMULA]
FROM #tabInfo              [A]
JOIN dbo.[REPORT_TABLES]   [B] ON [A].[LINK_FORM_NEW] = [B].[LINK_FORM]
JOIN dbo.[REPORT_COLOUMNS] [C] ON [B].[LINK_TABLE] = [C].[LINK_TABLE]
JOIN dbo.[REPORT_ROWS]     [D] ON [B].[LINK_TABLE] = [D].[LINK_TABLE]
JOIN #F                    [E] ON [E].[ORDER_TABLE] = [B].[ORDERS] AND [E].[ORDER_COL] = [C].[ORDERS] AND [E].[ORDER_ROW] = [D].[ORDERS]

ALTER TABLE dbo.[REPORT_FORMULA] ENABLE TRIGGER ALL

DROP TABLE #F

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN

DECLARE @iERROR INT, @iLINK_FORM_NEW INT, @iLINK_FORM INT

SELECT @iLINK_FORM = [LINK_FORM],
       @iLINK_FORM_NEW = [LINK_FORM_NEW]
FROM #tabInfo

--IF @iLINK_FORM_NEW <> @iLINK_FORM
--BEGIN
  EXEC @iERROR = dbo.[RA_UNION_FORM_STRUCT] @iLINK_FORM, @iLINK_FORM_NEW, 1
--END
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UNION_FORM_STRUCT',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Установка внутридокументных правил КС формы.
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF OBJECT_ID('tempdb..#A') IS NOT NULL
BEGIN
   DROP TABLE #A
END
CREATE TABLE #A ([LINK_RULE]       INT NULL,
                 [LINK_TASK]       INT NULL,
                 [IsOutside]       TINYINT NULL,
                 [LINK_FORM]       INT NULL,
                 [OrderRule]       INT NULL,
                 [PERIOD]          SMALLINT NULL,
                 [PERIOD_NOM]      SMALLINT NULL,
                 [ORG_LEVEL]       SMALLINT NULL,
                 [IsSvod]          SMALLINT NULL,
                 [STR_RULE]        VARCHAR (6000) NULL,
                 [IsDoschet]       TINYINT NULL,
                 [CALC_ORDERS]     INT NULL,
                 [IsSystemsRule]   TINYINT NULL ,
                 [MODIFY_DATE]     DATETIME NULL,
                 [ROWS]            VARCHAR(1000),
                 [COLS]            VARCHAR(250),
                 [ROWS_DESC]       VARCHAR (250),
                 [CODE_FORM]       VARCHAR (250),
                 [START_DATE_FORM] VARCHAR (250),
                 [REGION]				VARCHAR (100),
                 [SIGN_SR]         CHAR(2)      NOT NULL,
                 [ALGORITHM]       TINYINT      NOT NULL,
                 [ATR_CODE_SR]     VARCHAR(254) NOT NULL,
                 [COMMENT]         VARCHAR(8000))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #A',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #A'
INSERT #A VALUES(1,NULL,0,NULL,1,7,0,0,0,'т.1стр.01 =  т.1стр.02 +  т.1стр.03 +  т.1стр.04 +  т.1стр.06 +  т.1стр.07 +  т.1стр.08 +  т.1стр.10 +  т.1стр.11 +  т.1стр.12 +  т.1стр.13',1,3,1,'20130912','','','','0606049','20130601','','=',2,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 1
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','01','1',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','02','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','03','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','04','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','06','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','07','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','08','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','10','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,9,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','11','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,10,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','12','1',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,11,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','','13','1',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 11
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #B',0)
END

CREATE INDEX #IX_tabROWS ON #B([LINK_RULE])
CREATE INDEX #IX_tabRULES ON #A([LINK_RULE])

-- Импорт правил во временные таблицы.
EXEC @iERROR = dbo.[RN_IMPORT_RULES] '#A', '#B', 1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_IMPORT_RULES',@iERROR)
END
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT, @iLINK_FORM INT, @iTABLE_LINK INT, @tTABLE_ORDER TINYINT, @iGF_LINK INT

SELECT @iLINK_FORM = [LINK_FORM]
FROM #tabInfo


-- Обновление связей с группами форм.

DELETE dbo.[REPORT_FORM_GROUPS_REF]
WHERE [LINK_FORM] = @iLINK_FORM

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '451       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'451','Республика Коми',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

SET @iGF_LINK = NULL
SELECT @iGF_LINK = [LINK] FROM dbo.[REPORT_FORM_GROUPS] WHERE [CODE] = '606       '
EXEC @iERROR = dbo.[RV_UPDATE_REPORT_FORM_GROUPS] @iGF_LINK OUTPUT,'606','Заработная плата',0,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RV_UPDATE_REPORT_FORM_GROUPS',@iERROR)
END

EXEC @iERROR = dbo.[RA_UPDATE_FORM_GROUPS_REF] @iLINK_FORM, @iGF_LINK
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RA_UPDATE_FORM_GROUPS_REF',@iERROR)
END

-- Переформирование процедур RI_PROC_T.
DECLARE curTable CURSOR FOR
SELECT [LINK_TABLE],
       [ORDERS]
FROM [REPORT_TABLES]
WHERE [LINK_FORM] = @iLINK_FORM

OPEN curTable

FETCH NEXT
FROM curTable
INTO @iTABLE_LINK,
     @tTABLE_ORDER

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC @iERROR = dbo.[I_REPORT_CREATE_PROC] @iTABLE_LINK
   IF @iERROR <> 0
   BEGIN
      INSERT #tabErrorLog VALUES ('I_REPORT_CREATE_PROC',@iERROR)
   END
   FETCH NEXT
   FROM curTable
   INTO @iTABLE_LINK,
        @tTABLE_ORDER
END
CLOSE curTable
DEALLOCATE curTable

EXEC dbo.[I_CONTROL_RULES_ACTION] 3, @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2014-02-07 09:17:36.123',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-02-07 09:17:36.123'
	BEGIN
		SELECT @vcMessage = 'Форма 0606049 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма 0606049 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-02-07 09:17:36.123. Обновление отклонено.'
	END

	 IF OBJECT_ID('tempdb..#tabUpdateMessages') IS NOT NULL
	 BEGIN
		 INSERT #tabUpdateMessages([TXT]) VALUES (@vcMessage)
	 END
	 SELECT @vcMessage
END
GO

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL DROP TABLE #tabInfo
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog
DROP TABLE #tabStop

COMMIT TRANSACTION -- Фиксация транзакции.
GO


GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (фев  6 2014  4:07:20:780PM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : РСВ-1 (Расчет по начисленным и уплаченным страховым взносам на ОПС и в ФСС (ФЗ от 24 июля 2009 г. № 212-ФЗ))
-- Дата ввода : 20130101
-- Дата окончания действия :
-- Версия : 2014-02-06 16:07:20.733
-- Параметры выгрузки :
-- экспортировать внутридокументные КС          : да
-- выгружать только внутридокументные КС        : нет
-- удалять системные КС старой версии           : да
-- удалять все версии формы кроме текущей       : нет
-- удалять пользовательские КС старой версии    : нет
-- не обновлять форму при совпадении дат версий : нет

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] = '20130101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2014-02-06 16:07:20.733',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,'20130101')

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. 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_2013()','RSV_1_PFR_2013.bas','','KirRepMakerMultiSheet.XLS','RSV-1-PFR_2013.XLT','',NULL,'i_report_export_nalog',0,NULL,NULL,NULL,'          ','',NULL,NULL,'|',1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('RN_REPORT_SAVE_REPORT_FORMS_PART2',@iERROR)
END

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Сохранение в табл. REPORT_TABLES.
SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Титульный лист', @iLINK_FORM,1
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование',@iLINK_TABLE,0,1,1,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код',@iLINK_TABLE,1,1,2,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Количество застрахованных лиц',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Среднесписочная численность',@iLINK_TABLE,1,0,4,1,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Титульный лист', @iLINK_FORM,1, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р1. Расчет по начисленным и уплаченным страховым', @iLINK_FORM,2
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Страховые взносы на ОПС: страховая часть',@iLINK_TABLE,1,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Страховые взносы на ОПС: накопительная часть',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Страховые взносы на ОПС:по доп тарифу - в соответствии с частью 1 статьи 58.3 Федерального закона от 24 июля 2009 г. № 212-ФЗ',@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,'Страховые взносы на ОПС:по доп тарифу - в соответствии с частью 2 статьи 58.3 Федерального закона от 24 июля 2009 г. № 212-ФЗ',@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


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.Расчет доп тарифа страховых взносов (часть 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,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.Расчет доп тарифа страховых взносов (часть 1)', @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, 'Р3.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,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,100,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Дата выдачи справки',@iLINK_TABLE,0,1,3,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'Срок действия',@iLINK_TABLE,1,1,4,0,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В т.ч. сумма за 1 мес отч. квартала',@iLINK_TABLE,1,0,6,6,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 7,'В т.ч. сумма за 2 мес отч. квартала',@iLINK_TABLE,1,0,7,7,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 8,'В т.ч. сумма за 3 мес отч. квартала',@iLINK_TABLE,1,0,8,8,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.1. Сведения, необходимые для применения понижен', @iLINK_FORM,6, @iLINK_CODE_COL,1,'CALC_SMETA=exec dbo.RSA_RSV_1_12_PFR_INV @dateBeginPeriod, @dateEndPeriod, @depLink, 7, 1',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.2. Расчет соотв. условий на право пониж тарифа', @iLINK_FORM,7
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода, 1 месяц',@iLINK_TABLE,1,0,4,0,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода, 2 месяц',@iLINK_TABLE,1,0,5,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода, 3 месяц',@iLINK_TABLE,1,0,6,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.2. Расчет соотв. условий на право пониж тарифа', @iLINK_FORM,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, 'P3.3.Расчет для пониж. тарифа для организаций, уст', @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,0,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'Всего с начала расчетного периода',@iLINK_TABLE,1,0,3,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'В том числе за последние три месяца отчетного периода, 1 месяц',@iLINK_TABLE,1,0,4,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'В том числе за последние три месяца отчетного периода, 2 месяц',@iLINK_TABLE,1,0,5,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'В том числе за последние три месяца отчетного периода, 3 месяц',@iLINK_TABLE,1,0,6,0,2,1,NULL,NULL,NULL,'999 999 999 999 999.99',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'P3.3.Расчет для пониж. тарифа для организаций, уст', @iLINK_FORM,8, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.4. Соответствия условиям п.6 ч.1 ст.58 № 212-ФЗ', @iLINK_FORM,9
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'По итогам 9-ти месяцев года, предшествующего текущему расчетному перио',@iLINK_TABLE,1,0,3,1,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'По итогам текущего отчетного (расчетного) периода',@iLINK_TABLE,1,0,4,2,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Дата записи в реестре  аккредитованных организаций',@iLINK_TABLE,1,1,5,5,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'№ записи в реестре аккредитованных организаций',@iLINK_TABLE,1,1,6,6,50,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.4. Соответствия условиям п.6 ч.1 ст.58 № 212-ФЗ', @iLINK_FORM,9, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

SET @iLINK_TABLE = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE OUTPUT, 'Р3.5. Соответствие условиям п.7 ч.1 ст. 58  № 212-', @iLINK_FORM,10
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'№ п/п',@iLINK_TABLE,1,1,1,0,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.5. Соответствие условиям п.7 ч.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.6. Соответсвие условиям п.8 ч.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,'С начала отчетного (расчетного) периода',@iLINK_TABLE,0,0,3,3,0,1,NULL,NULL,NULL,'999 999 999 999 999',NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.6. Соответсвие условиям п.8 ч.1. ст.58 ФЗ № 212', @iLINK_FORM,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.7.Соответствие сведениям п. 11 ч. 1 ст. 58  № 2', @iLINK_FORM,12
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END


-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_DINAMIC_TOTALS.

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Сохранение в табл. REPORT_COLOUMNS.
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 1,'Наименование показателя',@iLINK_TABLE,1,1,1,0,254,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 2,'Код строки',@iLINK_TABLE,1,1,2,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_CODE_COL = @iLINK_COL
SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 3,'По итогам года, предшествующего текущему расчетному периоду',@iLINK_TABLE,1,0,3,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'По итогам текущего расчетного периода',@iLINK_TABLE,1,0,4,0,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.7.Соответствие сведениям п. 11 ч. 1 ст. 58  № 2', @iLINK_FORM,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.8. Соответствие условиям п. 13 ч. 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,'По итогам 9-ти месяцев года, предшествующего текущему расчетному перио',@iLINK_TABLE,1,0,3,3,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 4,'По итогам текущего отчетного (расчетного) периода',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Дата получения положительного заключения',@iLINK_TABLE,1,1,5,5,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 6,'№',@iLINK_TABLE,1,1,6,6,10,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_TABLES] @iLINK_TABLE, 'Р3.8. Соответствие условиям п. 13 ч. 1 ст. 58 № 21', @iLINK_FORM,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,'Период, за который выявлены и доначислены страховые взносы, год',@iLINK_TABLE,1,1,3,3,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,'Период, за который выявлены и доначислены страховые взносы, месяц',@iLINK_TABLE,1,0,4,4,0,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_COLOUMNS',@iERROR)
END


SET @iLINK_COL = NULL
EXEC @iERROR = dbo.[I_REPORT_SAVE_REPORT_COLOUMNS] @iLINK_COL OUTPUT, 5,'Страховые взносы: страховая часть - Всего',@iLINK_TABLE,1,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,'Страх. взносы на ОПС, по доп тарифу: в соответствии с частью 1 статьи 58.3 Федерального закона от 24 июля 2009 г. № 212-ФЗ',@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,'Страх. взносы на ОПС, по доп тарифу: в соответствии с частью 2 статьи 58.3 Федерального закона от 24 июля 2009 г. № 212-ФЗ',@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, 'Р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 чт', @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 чт', @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 чт', @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 чт', @iLINK_FORM,16, @iLINK_CODE_COL,0,'',NULL,0
IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('I_REPORT_SAVE_REPORT_TABLES',@iERROR)
END

INSERT #tabInfo VALUES (COALESCE(@iOLD_FORM_LINK, @iLINK_FORM), @iLINK_FORM)

DELETE FROM dbo.[REPORT_CONTROL_RULES] WHERE [LINK_FORM] = @iOLD_FORM_LINK AND [IsSystemsRule] = 1
END -- проверка признака остановки в #tabStop

GO

-->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-- Выгрузка для статических таблиц.

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN

DECLARE @iError INT

-- Выгрузка строк статических таблиц.
IF OBJECT_ID('tempdb..#R') IS NOT NULL
BEGIN
   DROP TABLE #R
END

CREATE TABLE #R([ORDERS]      SMALLINT,
                [LINK_TABLE]  INT,
                [CALC_ORDERS] SMALLINT,
                [PRINT_NULL]  TINYINT)

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #R',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop)
BEGIN
INSERT #R VALUES (1,1,1,1)
INSERT #R VALUES (1,2,0,1)
INSERT #R VALUES (2,2,0,1)
INSERT #R VALUES (3,2,0,1)
INSERT #R VALUES (4,2,0,1)
INSERT #R VALUES (5,2,0,1)
INSERT #R VALUES (6,2,1,1)
INSERT #R VALUES (7,2,0,1)
INSERT #R VALUES (8,2,1,1)
INSERT #R VALUES (10,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 (15,2,1,1)
INSERT #R VALUES (16,2,0,1)
INSERT #R VALUES (17,2,0,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,0,1)
INSERT #R VALUES (6,3,0,1)
INSERT #R VALUES (7,3,0,1)
INSERT #R VALUES (8,3,0,1)
INSERT #R VALUES (9,3,0,1)
INSERT #R VALUES (11,3,0,1)
INSERT #R VALUES (12,3,0,1)
INSERT #R VALUES (13,3,0,1)
INSERT #R VALUES (14,3,1,1)
INSERT #R VALUES (15,3,1,1)
INSERT #R VALUES (16,3,0,1)
INSERT #R VALUES (17,3,0,1)
INSERT #R VALUES (18,3,0,1)
INSERT #R VALUES (19,3,0,1)
INSERT #R VALUES (20,3,0,1)
INSERT #R VALUES (22,3,0,1)
INSERT #R VALUES (23,3,0,1)
INSERT #R VALUES (24,3,0,1)
INSERT #R VALUES (25,3,0,1)
INSERT #R VALUES (26,3,2,1)
INSERT #R VALUES (27,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,0,1)
INSERT #R VALUES (6,4,0,1)
INSERT #R VALUES (7,4,0,1)
INSERT #R VALUES (8,4,0,1)
INSERT #R VALUES (9,4,0,1)
INSERT #R VALUES (11,4,0,1)
INSERT #R VALUES (12,4,0,1)
INSERT #R VALUES (13,4,0,1)
INSERT #R VALUES (14,4,1,1)
INSERT #R VALUES (15,4,1,1)
INSERT #R VALUES (16,4,0,1)
INSERT #R VALUES (17,4,0,1)
INSERT #R VALUES (18,4,0,1)
INSERT #R VALUES (19,4,0,1)
INSERT #R VALUES (20,4,0,1)
INSERT #R VALUES (22,4,0,1)
INSERT #R VALUES (23,4,0,1)
INSERT #R VALUES (24,4,0,1)
INSERT #R VALUES (25,4,0,1)
INSERT #R VALUES (26,4,2,1)
INSERT #R VALUES (27,4,0,1)
INSERT #R VALUES (1,5,0,1)
INSERT #R VALUES (2,5,0,1)
INSERT #R VALUES (3,5,0,1)
INSERT #R VALUES (5,5,0,1)
INSERT #R VALUES (6,5,0,1)
INSERT #R VALUES (4,5,1,1)
INSERT #R VALUES (7,5,0,1)
INSERT #R VALUES (8,5,8,1)
INSERT #R VALUES (9,5,9,1)
INSERT #R VALUES (10,5,10,1)
INSERT #R VALUES (11,5,11,1)
INSERT #R VALUES (12,5,12,1)
INSERT #R VALUES (1,7,0,1)
INSERT #R VALUES (2,7,0,1)
INSERT #R VALUES (3,7,1,1)
INSERT #R VALUES (1,8,0,1)
INSERT #R VALUES (2,8,0,1)
INSERT #R VALUES (3,8,1,1)
INSERT #R VALUES (4,8,0,1)
INSERT #R VALUES (5,8,0,1)
INSERT #R VALUES (6,8,1,1)
INSERT #R VALUES (1,9,0,1)
INSERT #R VALUES (2,9,0,1)
INSERT #R VALUES (3,9,1,1)
INSERT #R VALUES (4,9,0,1)
INSERT #R VALUES (5,9,0,1)
INSERT #R VALUES (1,10,0,1)
INSERT #R VALUES (2,10,0,1)
INSERT #R VALUES (3,10,0,1)
INSERT #R VALUES (4,10,0,1)
INSERT #R VALUES (5,10,0,1)
INSERT #R VALUES (6,10,0,1)
INSERT #R VALUES (7,10,0,1)
INSERT #R VALUES (8,10,0,1)
INSERT #R VALUES (9,10,0,1)
INSERT #R VALUES (10,10,0,1)
INSERT #R VALUES (11,10,1,1)
INSERT #R VALUES (12,10,0,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 (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,1,1)
INSERT #R VALUES (1,13,0,1)
INSERT #R VALUES (2,13,0,1)
INSERT #R VALUES (3,13,1,1)
INSERT #R VALUES (4,13,0,1)
INSERT #R VALUES (5,13,0,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) <> 119
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_13_УСТАНОВКА() + РСВ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,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,'в том числе за предыдущие расчетные периоды                                                                                                                                                                                                                   ')
INSERT #F VALUES (2,17,1,'Остаток страховых взносов, подлежащих уплате
на конец отчетного периода (с.130 - с.140) (+) задолженность, (-) переплата                                                                                                                                     ')
INSERT #F VALUES (2,8,1,'В том числе с сумм, превышающих предельную величину базы для начисления страховых взносов                                                                                                                                                                     ')
INSERT #F VALUES (2,1,2,'100                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,2,2,'110                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,3,2,'111                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,4,2,'112                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,5,2,'113                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,6,2,'114                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,7,2,'120                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,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,'145                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,17,2,'150                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,8,2,'121                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (2,1,3,'КТСН("_.303.10","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,11,3,'АДТКТ("_.303.10","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=НАЧ.ГОДА") + АДТКТ("_.303.10","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,12,3,'АДТКТ("_.303.10","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(1)") + АДТКТ("_.303.10","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,13,3,'АДТКТ("_.303.10","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(2)") + АДТКТ("_.303.10","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,14,3,'АДТКТ("_.303.10","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(3)") + АДТКТ("_.303.10","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,1,4,'КТСН("_.303.11","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,11,4,'АДТКТ("_.303.11","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=НАЧ.ГОДА") + АДТКТ("_.303.11","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,12,4,'АДТКТ("_.303.11","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(1)") + АДТКТ("_.303.11","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,13,4,'АДТКТ("_.303.11","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(2)") + АДТКТ("_.303.11","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,14,4,'АДТКТ("_.303.11","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(3)") + АДТКТ("_.303.11","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,8,4,'ЗАПРЕТ()')
INSERT #F VALUES (2,1,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (2,11,5,'АДТКТ("_.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,5,'АДТКТ("_.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,5,'АДТКТ("_.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,5,'АДТКТ("_.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,8,5,'ЗАПРЕТ()')
INSERT #F VALUES (2,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (2,11,6,'АДТКТ("_.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,6,'АДТКТ("_.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,6,'АДТКТ("_.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,6,'АДТКТ("_.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,8,6,'ЗАПРЕТ()')
INSERT #F VALUES (2,1,7,'КТСН("_.303.07","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,11,7,'АДТКТ("_.303.07","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=НАЧ.ГОДА") + АДТКТ("_.303.07","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=НАЧ.ГОДА")')
INSERT #F VALUES (2,12,7,'АДТКТ("_.303.07","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(1)") + АДТКТ("_.303.07","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(1)")')
INSERT #F VALUES (2,13,7,'АДТКТ("_.303.07","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(2)") + АДТКТ("_.303.07","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(2)")')
INSERT #F VALUES (2,14,7,'АДТКТ("_.303.07","_.304.05,СГУ>=''211'',СГУ<''290''","ДЛЯ ДАТА=МЕСЯЦ(3)") + АДТКТ("_.303.07","_.201.11:_.201.21:_.201.27","ДЛЯ ДАТА=МЕСЯЦ(3)")')
INSERT #F VALUES (2,8,7,'ЗАПРЕТ()')
INSERT #F VALUES (3,1,1,'Сумма выплат и иных вознаграждений, начисл-ых в пользу физ. лиц (ст. 7 ФЗ от 24 июля 2009 г. № 212-ФЗ): 1966 г.р. и старше                                                                                                                                    ')
INSERT #F VALUES (3,2,1,'      1967 г.р. и моложе                                                                                                                                                                                                                                      ')
INSERT #F VALUES (3,3,1,'       иностранные граждане или лица без гражданства, временно проживающие/пребывающие на территории РФ                                                                                                                                                       ')
INSERT #F VALUES (3,4,1,'Суммы, не подлежащие обложению страх. взн. (ч. 1, 2 ст. 9): 1966 г.р. и старше                                                                                                                                                                                ')
INSERT #F VALUES (3,5,1,'                            1967 г.р. и моложе                                                                                                                                                                                                                ')
INSERT #F VALUES (3,6,1,'        иностранные граждане или лица без гражданства, временно проживающие/пребывающие на территории РФ                                                                                                                                                      ')
INSERT #F VALUES (3,7,1,'Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ : 1966 г.р. и старше: 1966 г.р. и старше                                                                                                ')
INSERT #F VALUES (3,8,1,'                            1967 г.р. и моложе                                                                                                                                                                                                                ')
INSERT #F VALUES (3,9,1,'        иностранные граждане или лица без гражданства, временно проживающие/пребывающие на территории РФ                                                                                                                                                      ')
INSERT #F VALUES (3,11,1,'Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную ст. 8 Федерального закона
от 24 июля 2009 г. № 212-ФЗ: 1966 г.р. и старше                                                                                        ')
INSERT #F VALUES (3,12,1,'        1967 г.р. и моложе                                                                                                                                                                                                                                    ')
INSERT #F VALUES (3,13,1,'       иностранные граждане или лица без гражданства, временно проживающие/пребывающие на территории РФ                                                                                                                                                       ')
INSERT #F VALUES (3,14,1,'База для начисления страховых взносов на обязательное пенсионное страхование: 1966 г.р. и старше (с. 201+ с. 203 - с. 211 - с. 213 - с. 221 - с. 231 - с. 233)                                                                                                ')
INSERT #F VALUES (3,15,1,'       1967 г.р. и моложе (с. 202 - с. 212 - с. 222 - с. 232)                                                                                                                                                                                                 ')
INSERT #F VALUES (3,16,1,'Начислено страховых взносов на обяза-тельное пенсионное страхование: страховая часть                                                                                                                                                                          ')
INSERT #F VALUES (3,17,1,'       накопительная часть                                                                                                                                                                                                                                    ')
INSERT #F VALUES (3,18,1,'       с сумм, превышающих предельную величину базы                                                                                                                                                                                                           ')
INSERT #F VALUES (3,19,1,'Количество физических лиц, с выплат  которым начислены страховые взносы в соответствии с тарифом (чел.)                                                                                                                                                       ')
INSERT #F VALUES (3,22,1,'Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с межгосударственными соглашениями                                                      ')
INSERT #F VALUES (3,23,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии с частями 1, 2 статьи 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с межгосударственными соглашениями                                                                 ')
INSERT #F VALUES (3,24,1,'Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ                                                                                                                                         ')
INSERT #F VALUES (3,25,1,'Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную статьей 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                         ')
INSERT #F VALUES (3,26,1,'База для начисления страховых взносов на обязательное медицинское страхование (с. 271 - с. 272 - ст. 273 - ст. 274)                                                                                                                                           ')
INSERT #F VALUES (3,27,1,'Начислено страховых взносов на обяза-тельное медицинское страхование                                                                                                                                                                                          ')
INSERT #F VALUES (3,20,1,'Количество физических лиц, по которым величина базы превысила предел, установленный статьей 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ (чел.)                                                                                                          ')
INSERT #F VALUES (3,1,2,'201                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,2,2,'202                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,3,2,'203                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,4,2,'211                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,5,2,'212                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,6,2,'213                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,7,2,'221                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,8,2,'222                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,9,2,'223                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,11,2,'231                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,12,2,'232                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,13,2,'233                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,14,2,'240                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,15,2,'241                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,16,2,'250                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,17,2,'251                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,18,2,'252                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,19,2,'260                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,22,2,'271                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,23,2,'272                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,24,2,'273                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,25,2,'274                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,26,2,'275                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,27,2,'276                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,20,2,'261                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (3,1,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,3,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,4,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,5,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,6,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,7,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,8,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,9,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,12,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,13,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,16,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,17,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,18,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,19,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,22,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,23,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,24,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,25,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,27,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,20,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (3,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,3,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,4,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,5,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,6,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,7,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,8,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,9,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,12,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,13,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,16,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,17,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,18,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,19,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,22,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,23,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,24,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,25,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,27,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,20,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (3,1,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,3,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,4,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,5,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,6,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,7,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,8,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,9,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,12,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,13,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,16,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,17,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,18,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,19,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,22,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,23,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,24,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,25,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,27,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,20,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (3,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,3,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,4,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,5,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,6,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,7,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,8,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,9,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,11,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,12,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,13,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,16,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,17,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,18,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,19,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,22,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,23,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,24,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,25,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,27,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (3,20,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,1,1,'Сумма выплат и иных вознаграждений, начисл-ых в пользу физ. лиц (ст. 7 ФЗ от 24 июля 2009 г. № 212-ФЗ): 1966 г.р. и старше                                                                                                                                    ')
INSERT #F VALUES (4,2,1,'      1967 г.р. и моложе                                                                                                                                                                                                                                      ')
INSERT #F VALUES (4,3,1,'       иностранные граждане или лица без гражданства, временно проживающие/пребывающие на территории РФ                                                                                                                                                       ')
INSERT #F VALUES (4,4,1,'Суммы, не подлежащие обложению страх. взн. (ч. 1, 2 ст. 9): 1966 г.р. и старше                                                                                                                                                                                ')
INSERT #F VALUES (4,5,1,'                            1967 г.р. и моложе                                                                                                                                                                                                                ')
INSERT #F VALUES (4,6,1,'        иностранные граждане или лица без гражданства, временно проживающие/пребывающие на территории РФ                                                                                                                                                      ')
INSERT #F VALUES (4,7,1,'Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ : 1966 г.р. и старше: 1966 г.р. и старше                                                                                                ')
INSERT #F VALUES (4,8,1,'                            1967 г.р. и моложе                                                                                                                                                                                                                ')
INSERT #F VALUES (4,9,1,'        иностранные граждане или лица без гражданства, временно проживающие/пребывающие на территории РФ                                                                                                                                                      ')
INSERT #F VALUES (4,11,1,'Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную ст. 8 Федерального закона
от 24 июля 2009 г. № 212-ФЗ: 1966 г.р. и старше                                                                                        ')
INSERT #F VALUES (4,12,1,'        1967 г.р. и моложе                                                                                                                                                                                                                                    ')
INSERT #F VALUES (4,13,1,'       иностранные граждане или лица без гражданства, временно проживающие/пребывающие на территории РФ                                                                                                                                                       ')
INSERT #F VALUES (4,14,1,'База для начисления страховых взносов на обязательное пенсионное страхование: 1966 г.р. и старше (с. 201+ с. 203 - с. 211 - с. 213 - с. 221 - с. 231 - с. 233)                                                                                                ')
INSERT #F VALUES (4,15,1,'       1967 г.р. и моложе (с. 202 - с. 212 - с. 222 - с. 232)                                                                                                                                                                                                 ')
INSERT #F VALUES (4,16,1,'Начислено страховых взносов на обяза-тельное пенсионное страхование: страховая часть                                                                                                                                                                          ')
INSERT #F VALUES (4,17,1,'       накопительная часть                                                                                                                                                                                                                                    ')
INSERT #F VALUES (4,18,1,'       с сумм, превышающих предельную величину базы                                                                                                                                                                                                           ')
INSERT #F VALUES (4,19,1,'Количество физических лиц, с выплат  которым начислены страховые взносы в соответствии с тарифом (чел.)                                                                                                                                                       ')
INSERT #F VALUES (4,22,1,'Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с межгосударственными соглашениями                                                      ')
INSERT #F VALUES (4,23,1,'Суммы, не подлежащие обложению страховыми взносами в соответствии с частями 1, 2 статьи 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ и в соответствии с межгосударственными соглашениями                                                                 ')
INSERT #F VALUES (4,24,1,'Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ                                                                                                                                         ')
INSERT #F VALUES (4,25,1,'Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную статьей 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                                                                                         ')
INSERT #F VALUES (4,26,1,'База для начисления страховых взносов на обязательное медицинское страхование (с. 271 - с. 272 - ст. 273 - ст. 274)                                                                                                                                           ')
INSERT #F VALUES (4,27,1,'Начислено страховых взносов на обяза-тельное медицинское страхование                                                                                                                                                                                          ')
INSERT #F VALUES (4,20,1,'Количество физических лиц, по которым величина базы превысила предел, установленный статьей 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ (чел.)                                                                                                          ')
INSERT #F VALUES (4,1,2,'2010                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,2,2,'2020                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,3,2,'2030                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,4,2,'2110                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,5,2,'2120                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,6,2,'2130                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,7,2,'2210                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,8,2,'2220                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,9,2,'2230                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,11,2,'2310                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,12,2,'2320                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,13,2,'2330                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,14,2,'2400                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,15,2,'2410                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,16,2,'2500                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,17,2,'2510                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,18,2,'2520                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,19,2,'2600                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,22,2,'2710                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,23,2,'2720                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,24,2,'2730                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,25,2,'2740                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,26,2,'2750                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,27,2,'2760                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (4,20,2,'2610                                                                                                                                                                                                                                                          ')
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,5,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,6,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,7,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,8,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,9,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,12,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,13,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,16,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,17,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,18,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,19,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,22,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,23,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,24,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,25,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,27,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (4,20,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,5,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,6,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,7,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,8,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,9,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,12,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,13,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,16,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,17,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,18,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,19,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,22,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,23,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,24,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,25,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,27,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (4,20,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,5,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,6,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,7,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,8,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,9,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,12,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,13,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,16,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,17,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,18,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,19,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,22,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,23,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,24,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,25,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,27,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (4,20,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,5,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,6,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,7,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,8,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,9,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,11,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,12,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,13,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,16,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,17,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,18,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,19,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,22,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,23,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,24,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,25,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,27,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (4,20,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,'Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ (по доп тарифу 1)                                                                                                                    ')
INSERT #F VALUES (5,5,1,'Начислено страх. взносов по доп.тарифу 1 для отдельных категорий плательщиков страх. взносов                                                                                                                                                                  ')
INSERT #F VALUES (5,6,1,'Количество физических лиц, с выплат которым начислены страх. взносы по доп. тарифу 1 страх. взносов (чел.)                                                                                                                                                    ')
INSERT #F VALUES (5,4,1,'База для начисления взносов по доп. тарифу 1  (с. 280 - с. 281 - с. 282)                                                                                                                                                                                      ')
INSERT #F VALUES (5,7,1,'Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ (по доп тарифу 2)                                                                                        ')
INSERT #F VALUES (5,8,1,'Суммы, не подлежащие обложению страх. взносами в соответствии со статьей 9 Федерального закона от 24 июля 2009 г. № 212-ФЗ (по доп тарифу 2)                                                                                                                  ')
INSERT #F VALUES (5,9,1,'Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 г. № 212-ФЗ (по доп тарифу 2)                                                                                                                    ')
INSERT #F VALUES (5,10,1,'База для начисления взносов по доп. тарифу 2  (с. 290 - с. 291 - с. 292)                                                                                                                                                                                      ')
INSERT #F VALUES (5,11,1,'Начислено страх. взносов по доп. тарифу 2 для отдельных категорий плательщиков страх. взносов                                                                                                                                                                 ')
INSERT #F VALUES (5,12,1,'Количество физических лиц, с выплат которым начислены страх. взносы по доп. тарифу 2 страх. взносов (чел.)                                                                                                                                                    ')
INSERT #F VALUES (5,1,2,'280                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,2,2,'281                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,3,2,'282                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,5,2,'284                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,6,2,'285                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,4,2,'283                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,7,2,'290                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,8,2,'291                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,9,2,'292                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,10,2,'293                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,11,2,'294                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,12,2,'295                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (5,1,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,3,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,8,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,9,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,11,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,12,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (5,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,3,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,8,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,9,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,11,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,12,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (5,1,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,3,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,8,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,9,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,11,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,12,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (5,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,3,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,8,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,9,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,11,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (5,12,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (7,1,1,'Численность членов организации, всего (чел.)                                                                                                                                                                                                                  ')
INSERT #F VALUES (7,2,1,'       из них: численность инвалидов и их законных представителей (чел.)                                                                                                                                                                                      ')
INSERT #F VALUES (7,3,1,'Удельный вес численности инвалидов и их законных представителей в численности членов организации (%)
(с. 322 / с. 321) х 100                                                                                                                                 ')
INSERT #F VALUES (7,1,2,'321                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (7,2,2,'322                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (7,3,2,'323                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (8,1,1,'Среднесписочная численность, всего (чел.)                                                                                                                                                                                                                     ')
INSERT #F VALUES (8,2,1,'          из них: среднесписочная численность инвалидов (чел.)                                                                                                                                                                                                ')
INSERT #F VALUES (8,3,1,'Удельный вес инвалидов в среднесписочной численности (%)                                                                                                                                                                                                      ')
INSERT #F VALUES (8,4,1,'Фонд оплаты труда, всего (в рублях)                                                                                                                                                                                                                           ')
INSERT #F VALUES (8,5,1,'         из них: заработная плата инвалидов (в рублях)                                                                                                                                                                                                        ')
INSERT #F VALUES (8,6,1,'Удельный вес заработной платы инвалидов (%) (с. 335 / с. 334) х 100                                                                                                                                                                                           ')
INSERT #F VALUES (8,1,2,'331                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (8,2,2,'332                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (8,3,2,'333                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (8,4,2,'334                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (8,5,2,'335                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (8,6,2,'336                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (8,1,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (8,2,3,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,3)')
INSERT #F VALUES (8,1,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (8,2,4,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,4)')
INSERT #F VALUES (8,1,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (8,2,5,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,5)')
INSERT #F VALUES (8,1,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (8,2,6,'РСВ1_ЗНАЧЕНИЕ(К.СТР.,6)')
INSERT #F VALUES (9,1,1,'Сумма доходов, определяемая в соответствии со статьей 248 Налогового кодекса Российской Федерации, всего (в рублях)                                                                                                                                           ')
INSERT #F VALUES (9,2,1,'           из них: сумма доходов, определяемая исходя из критериев, указанных в пункте 2 части 2.1 или пункте  2 части 2.2 статьи 57 Федерального закона от 24 июля 2009 г. № 212-ФЗ (в рублях)                                                               ')
INSERT #F VALUES (9,3,1,'Доля доходов, определяемая в целях применения части 5 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%)
(с. 342 / с. 341) х 100                                                                                                                  ')
INSERT #F VALUES (9,4,1,'Средняя численность работников*/
среднесписочная численность работников**(чел.)                                                                                                                                                                              ')
INSERT #F VALUES (9,5,1,'Сведения из реестра аккредитованных организаций, осуществляющих деятельность в области информационных технологий*                                                                                                                                             ')
INSERT #F VALUES (9,1,2,'341                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (9,2,2,'342                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (9,3,2,'343                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (9,4,2,'344                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (9,5,2,'345                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (9,5,3,'ЗАПРЕТ()')
INSERT #F VALUES (9,5,4,'ЗАПРЕТ()')
INSERT #F VALUES (9,1,5,'ЗАПРЕТ()')
INSERT #F VALUES (9,2,5,'ЗАПРЕТ()')
INSERT #F VALUES (9,3,5,'ЗАПРЕТ()')
INSERT #F VALUES (9,4,5,'ЗАПРЕТ()')
INSERT #F VALUES (9,1,6,'ЗАПРЕТ()')
INSERT #F VALUES (9,2,6,'ЗАПРЕТ()')
INSERT #F VALUES (9,3,6,'ЗАПРЕТ()')
INSERT #F VALUES (9,4,6,'ЗАПРЕТ()')
INSERT #F VALUES (10,1,1,'1                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,2,1,'2                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,3,1,'3                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,4,1,'4                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,5,1,'5                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,6,1,'6                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,7,1,'7                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,8,1,'8                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,9,1,'9                                                                                                                                                                                                                                                             ')
INSERT #F VALUES (10,10,1,'10                                                                                                                                                                                                                                                            ')
INSERT #F VALUES (10,12,1,'Сведения из реестра СМИ**                                                                                                                                                                                                                                     ')
INSERT #F VALUES (10,11,3,'Итого по всем видам деятельности')
INSERT #F VALUES (10,1,4,'350a                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (10,2,4,'350b                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (10,3,4,'350c                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (10,4,4,'350d                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (10,5,4,'350e                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (10,6,4,'350f                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (10,7,4,'350g                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (10,8,4,'350h                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (10,9,4,'350j                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (10,10,4,'350k                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (10,11,4,'350l                                                                                                                                                                                                                                                          ')
INSERT #F VALUES (10,12,4,'351                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (10,12,5,'ЗАПРЕТ()')
INSERT #F VALUES (10,11,6,'ЗАПРЕТ()')
INSERT #F VALUES (10,12,6,'ЗАПРЕТ()')
INSERT #F VALUES (10,1,7,'ЗАПРЕТ()')
INSERT #F VALUES (10,2,7,'ЗАПРЕТ()')
INSERT #F VALUES (10,3,7,'ЗАПРЕТ()')
INSERT #F VALUES (10,4,7,'ЗАПРЕТ()')
INSERT #F VALUES (10,5,7,'ЗАПРЕТ()')
INSERT #F VALUES (10,6,7,'ЗАПРЕТ()')
INSERT #F VALUES (10,7,7,'ЗАПРЕТ()')
INSERT #F VALUES (10,8,7,'ЗАПРЕТ()')
INSERT #F VALUES (10,9,7,'ЗАПРЕТ()')
INSERT #F VALUES (10,10,7,'ЗАПРЕТ()')
INSERT #F VALUES (10,11,7,'ЗАПРЕТ()')
INSERT #F VALUES (10,1,8,'ЗАПРЕТ()')
INSERT #F VALUES (10,2,8,'ЗАПРЕТ()')
INSERT #F VALUES (10,3,8,'ЗАПРЕТ()')
INSERT #F VALUES (10,4,8,'ЗАПРЕТ()')
INSERT #F VALUES (10,5,8,'ЗАПРЕТ()')
INSERT #F VALUES (10,6,8,'ЗАПРЕТ()')
INSERT #F VALUES (10,7,8,'ЗАПРЕТ()')
INSERT #F VALUES (10,8,8,'ЗАПРЕТ()')
INSERT #F VALUES (10,9,8,'ЗАПРЕТ()')
INSERT #F VALUES (10,10,8,'ЗАПРЕТ()')
INSERT #F VALUES (10,11,8,'ЗАПРЕТ()')
INSERT #F VALUES (11,1,1,'Сумма доходов, определяемая в соответствии со статьей 346.15 Налогового кодекса Российской Федерации, всего (в рублях)                                                                                                                                        ')
INSERT #F VALUES (11,2,1,'из них: сумма доходов, определяемая  в целях применения части 1.4 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (в рублях)                                                                                                                        ')
INSERT #F VALUES (11,3,1,'Доля доходов, определяемая  в целях применения части 1.4  статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%)
(с. 362 / с. 361) х 100                                                                                                              ')
INSERT #F VALUES (11,1,2,'361                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,2,2,'362                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (11,3,2,'363                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (12,1,1,'Сумма доходов, всего (в рублях)                                                                                                                                                                                                                               ')
INSERT #F VALUES (12,2,1,'из них: сумма доходов в виде целевых поступлений на содержание некоммерческих организаций и ведение ими уставной деятельности, поименованной в пункте 11 части 1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ                                    ')
INSERT #F VALUES (12,3,1,'сумма доходов в виде грантов, получаемых для осуществления деятельности, поименованной в пункте 11 части 1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ, определяемых в соответствии с подпунктом 14 пункта 1 статьи 251                         ')
INSERT #F VALUES (12,4,1,'сумма доходов от осуществления видов экономической деятельности, указанных в подпунктах р - ф, я.4 - я.6 пункта 8 части 1 статьи 58 Федерального закона от 24 июля 2009 г. 
№ 212-ФЗ (в рублях)                                                              ')
INSERT #F VALUES (12,5,1,'Доля доходов, определяемая в целях применения части 5.1 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%)
(с. 372 + с. 373 + с.374) / с. 371 х 100                                                                                               ')
INSERT #F VALUES (12,1,2,'371                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (12,2,2,'372                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (12,3,2,'373                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (12,4,2,'374                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (12,5,2,'375                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,1,1,'Сумма доходов, определяемая в соответствии со статьей 248 Налогового кодекса Российской Федерации, всего (в рублях)                                                                                                                                           ')
INSERT #F VALUES (13,2,1,'из них: сумма доходов от реализации инжиниринговых услуг, определяемая в целях применения пункта 1 части 5.4 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (в рублях)                                                                             ')
INSERT #F VALUES (13,3,1,'Доля доходов, определяемая в целях применения пункта 1 части 5.4 статьи 58 Федерального закона от 24 июля 2009 г. № 212-ФЗ (%)
(с. 382 / с. 381) х 100                                                                                                       ')
INSERT #F VALUES (13,4,1,'Средняя численность работников (чел.)                                                                                                                                                                                                                         ')
INSERT #F VALUES (13,5,1,'Сведения о получении положительного заключения экспертного совета по технико-внедренческим особым экономическим зонам*                                                                                                                                        ')
INSERT #F VALUES (13,1,2,'381                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,2,2,'382                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,3,2,'383                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,4,2,'384                                                                                                                                                                                                                                                           ')
INSERT #F VALUES (13,5,2,'385                                                                                                                                                                                                                                                           ')
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) <> 528
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,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(2,NULL,0,NULL,2,7,0,0,0,'т.2стр.114гр.4 =  т.2стр.111гр.4 +  т.2стр.112гр.4 +  т.2стр.113гр.4',1,11,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(3,NULL,0,NULL,3,7,0,0,0,'т.2стр.114гр.5 =  т.2стр.111гр.5 +  т.2стр.112гр.5 +  т.2стр.113гр.5',1,11,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(4,NULL,0,NULL,4,7,0,0,0,'т.2стр.130гр.3 =  т.2стр.100гр.3 +  т.2стр.110гр.3 +  т.2стр.120гр.3',1,11,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(5,NULL,0,NULL,5,7,0,0,0,'т.2стр.130гр.4 =  т.2стр.100гр.4 +  т.2стр.110гр.4 +  т.2стр.120гр.4',1,11,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(6,NULL,0,NULL,6,7,0,0,0,'т.2стр.130гр.5 =  т.2стр.100гр.5 +  т.2стр.110гр.5 +  т.2стр.120гр.5',1,11,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(7,NULL,0,NULL,7,7,0,0,0,'т.2стр.144гр.3 =  т.2стр.141гр.3 +  т.2стр.142гр.3 +  т.2стр.143гр.3',1,11,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(8,NULL,0,NULL,8,7,0,0,0,'т.2стр.144гр.4 =  т.2стр.141гр.4 +  т.2стр.142гр.4 +  т.2стр.143гр.4',1,11,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(9,NULL,0,NULL,9,7,0,0,0,'т.2стр.144гр.5 =  т.2стр.141гр.5 +  т.2стр.142гр.5 +  т.2стр.143гр.5',1,11,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(10,NULL,0,NULL,10,7,0,0,0,'т.2стр.150гр.3 =  т.2стр.130гр.3 -  т.2стр.140гр.3',1,12,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(11,NULL,0,NULL,11,7,0,0,0,'т.2стр.150гр.4 =  т.2стр.130гр.4 -  т.2стр.140гр.4',1,12,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(12,NULL,0,NULL,12,7,0,0,0,'т.2стр.150гр.5 =  т.2стр.130гр.5 -  т.2стр.140гр.5',1,12,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(13,NULL,0,NULL,13,7,0,0,0,'т.3стр.240гр.3 =  т.3стр.201гр.3 +  т.3стр.203гр.3 -  т.3стр.211гр.3 -  т.3стр.213гр.3 -  т.3стр.221гр.3 -  т.3стр.223гр.3 -  т.3стр.231гр.3 -  т.3стр.233гр.3',1,0,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(14,NULL,0,NULL,14,7,0,0,0,'т.3стр.240гр.4 =  т.3стр.201гр.4 +  т.3стр.203гр.4 -  т.3стр.211гр.4 -  т.3стр.213гр.4 -  т.3стр.221гр.4 -  т.3стр.223гр.4 -  т.3стр.231гр.4 -  т.3стр.233гр.4',1,0,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(15,NULL,0,NULL,15,7,0,0,0,'т.3стр.240гр.5 =  т.3стр.201гр.5 +  т.3стр.203гр.5 -  т.3стр.211гр.5 -  т.3стр.213гр.5 -  т.3стр.221гр.5 -  т.3стр.223гр.5 -  т.3стр.231гр.5 -  т.3стр.233гр.5',1,0,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(16,NULL,0,NULL,16,7,0,0,0,'т.3стр.241гр.3 =  т.3стр.202гр.3 -  т.3стр.212гр.3 -  т.3стр.222гр.3 -  т.3стр.232гр.3',1,0,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(17,NULL,0,NULL,17,7,0,0,0,'т.3стр.241гр.4 =  т.3стр.202гр.4 -  т.3стр.212гр.4 -  т.3стр.222гр.4 -  т.3стр.232гр.4',1,0,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(18,NULL,0,NULL,18,7,0,0,0,'т.3стр.241гр.5 =  т.3стр.202гр.5 -  т.3стр.212гр.5 -  т.3стр.222гр.5 -  т.3стр.232гр.5',1,0,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(19,NULL,0,NULL,19,7,0,0,0,'т.3стр.275гр.3 =  т.3стр.271гр.3 -  т.3стр.272гр.3 -  т.3стр.273гр.3 -  т.3стр.274гр.3',1,1,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(20,NULL,0,NULL,20,7,0,0,0,'т.3стр.275гр.4 =  т.3стр.271гр.4 -  т.3стр.272гр.4 -  т.3стр.273гр.4 -  т.3стр.274гр.4',1,1,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(21,NULL,0,NULL,21,7,0,0,0,'т.3стр.275гр.5 =  т.3стр.271гр.5 -  т.3стр.272гр.5 -  т.3стр.273гр.5 -  т.3стр.274гр.5',1,1,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(22,NULL,0,NULL,25,7,0,0,0,'т.7стр.323гр.3 =  т.7стр.322гр.3 /  т.7стр.321гр.3 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(23,NULL,0,NULL,26,7,0,0,0,'т.7стр.323гр.4 =  т.7стр.322гр.4 /  т.7стр.321гр.4 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(24,NULL,0,NULL,27,7,0,0,0,'т.7стр.323гр.5 =  т.7стр.322гр.5 /  т.7стр.321гр.5 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(25,NULL,0,NULL,28,7,0,0,0,'т.8стр.333гр.3 =  т.8стр.332гр.3 /  т.8стр.331гр.3 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(26,NULL,0,NULL,29,7,0,0,0,'т.8стр.333гр.4 =  т.8стр.332гр.4 /  т.8стр.331гр.4 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(27,NULL,0,NULL,30,7,0,0,0,'т.8стр.333гр.5 =  т.8стр.332гр.5 /  т.8стр.331гр.5 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(28,NULL,0,NULL,31,7,0,0,0,'т.8стр.336гр.3 =  т.8стр.335гр.3 /  т.8стр.334гр.3 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(29,NULL,0,NULL,32,7,0,0,0,'т.8стр.336гр.4 =  т.8стр.335гр.4 /  т.8стр.334гр.4 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(30,NULL,0,NULL,33,7,0,0,0,'т.3стр.240гр.6 =  т.3стр.201гр.6 +  т.3стр.203гр.6 -  т.3стр.211гр.6 -  т.3стр.213гр.6 -  т.3стр.221гр.6 -  т.3стр.223гр.6 -  т.3стр.231гр.6 -  т.3стр.233гр.6',1,0,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(31,NULL,0,NULL,34,7,0,0,0,'т.3стр.241гр.6 =  т.3стр.202гр.6 -  т.3стр.212гр.6 -  т.3стр.222гр.6 -  т.3стр.232гр.6',1,0,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(32,NULL,0,NULL,35,7,0,0,0,'т.3стр.275гр.6 =  т.3стр.271гр.6 -  т.3стр.272гр.6 -  т.3стр.273гр.6 -  т.3стр.274гр.6',1,1,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(33,NULL,0,NULL,37,7,0,0,0,'т.7стр.323гр.6 =  т.7стр.322гр.6 /  т.7стр.321гр.6 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(34,NULL,0,NULL,38,7,0,0,0,'т.8стр.333гр.6 =  т.8стр.332гр.6 /  т.8стр.331гр.6 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(35,NULL,0,NULL,39,7,0,0,0,'т.10стр.350lгр.5 =  т.10стр.350aгр.5 +  т.10стр.350bгр.5 +  т.10стр.350cгр.5 +  т.10стр.350dгр.5 +  т.10стр.350eгр.5 +  т.10стр.350fгр.5 +  т.10стр.350gгр.5 +  т.10стр.350hгр.5 +  т.10стр.350jгр.5 +  т.10стр.350kгр.5',1,1,1,'20130702','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(36,NULL,0,NULL,40,7,0,0,0,'т.11стр.363гр.3 =  т.11стр.362гр.3 /  т.11стр.361гр.3 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(37,NULL,0,NULL,41,7,0,0,0,'т.12стр.375гр.3 =  т.12стр.372гр.3 +  т.12стр.373гр.3 +  т.12стр.374гр.3 /  т.12стр.371гр.3 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(38,NULL,0,NULL,42,7,0,0,0,'т.12стр.375гр.4 =  т.12стр.372гр.4 +  т.12стр.373гр.4 +  т.12стр.374гр.4 /  т.12стр.371гр.4 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(39,NULL,0,NULL,43,7,0,0,0,'т.13стр.383гр.3 =  т.13стр.382гр.3 /  т.13стр.381гр.3 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(40,NULL,0,NULL,44,7,0,0,0,'т.2стр.110гр.3 =  т.3стр.250гр.3 +  т.3стр.252гр.3 +  т.4стр.2500гр.3 +  т.4стр.2520гр.3',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(41,NULL,0,NULL,45,7,0,0,0,'т.2стр.110гр.4 =  т.3стр.251гр.3 +  т.4стр.2510гр.3',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(42,NULL,0,NULL,46,7,0,0,0,'т.2стр.110гр.7 =  т.3стр.276гр.3 +  т.4стр.2760гр.3',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(43,NULL,0,NULL,47,7,0,0,0,'т.2стр.111гр.3 =  т.3стр.250гр.4 +  т.3стр.252гр.4 +  т.4стр.2500гр.4 +  т.4стр.2520гр.4',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(44,NULL,0,NULL,48,7,0,0,0,'т.2стр.111гр.4 =  т.3стр.251гр.4 +  т.4стр.2510гр.4',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(45,NULL,0,NULL,49,7,0,0,0,'т.2стр.111гр.7 =  т.3стр.276гр.4 +  т.4стр.2760гр.4',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(46,NULL,0,NULL,50,7,0,0,0,'т.2стр.112гр.3 =  т.3стр.250гр.5 +  т.3стр.252гр.5 +  т.4стр.2500гр.5 +  т.4стр.2520гр.5',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(47,NULL,0,NULL,51,7,0,0,0,'т.2стр.112гр.4 =  т.3стр.251гр.5 +  т.4стр.2510гр.5',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(48,NULL,0,NULL,52,7,0,0,0,'т.2стр.112гр.7 =  т.3стр.276гр.5 +  т.4стр.2760гр.5',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(49,NULL,0,NULL,53,7,0,0,0,'т.2стр.113гр.3 =  т.3стр.250гр.6 +  т.3стр.252гр.6 +  т.4стр.2500гр.6 +  т.4стр.2520гр.6',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(50,NULL,0,NULL,54,7,0,0,0,'т.2стр.113гр.4 =  т.3стр.251гр.6 +  т.4стр.2510гр.6',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(51,NULL,0,NULL,55,7,0,0,0,'т.2стр.113гр.7 =  т.3стр.276гр.6 +  т.4стр.2760гр.6',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(52,NULL,0,NULL,56,7,0,0,0,'т.4стр.2400гр.3 =  т.4стр.2010гр.3 +  т.4стр.2030гр.3 -  т.4стр.2110гр.3 -  т.4стр.2130гр.3 -  т.4стр.2210гр.3 -  т.4стр.2230гр.3 -  т.4стр.2310гр.3 -  т.4стр.2330гр.3',1,0,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(53,NULL,0,NULL,57,7,0,0,0,'т.4стр.2400гр.4 =  т.4стр.2010гр.4 +  т.4стр.2030гр.4 -  т.4стр.2110гр.4 -  т.4стр.2130гр.4 -  т.4стр.2210гр.4 -  т.4стр.2230гр.4 -  т.4стр.2310гр.4 -  т.4стр.2330гр.4',1,0,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(54,NULL,0,NULL,58,7,0,0,0,'т.4стр.2400гр.5 =  т.4стр.2010гр.5 +  т.4стр.2030гр.5 -  т.4стр.2110гр.5 -  т.4стр.2130гр.5 -  т.4стр.2210гр.5 -  т.4стр.2230гр.5 -  т.4стр.2310гр.5 -  т.4стр.2330гр.5',1,0,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(55,NULL,0,NULL,59,7,0,0,0,'т.4стр.2400гр.6 =  т.4стр.2010гр.6 +  т.4стр.2030гр.6 -  т.4стр.2110гр.6 -  т.4стр.2130гр.6 -  т.4стр.2210гр.6 -  т.4стр.2230гр.6 -  т.4стр.2310гр.6 -  т.4стр.2330гр.6',1,0,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(56,NULL,0,NULL,60,7,0,0,0,'т.4стр.2410гр.3 =  т.4стр.2020гр.3 -  т.4стр.2120гр.3 -  т.4стр.2220гр.3 -  т.4стр.2320гр.3',1,0,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(57,NULL,0,NULL,61,7,0,0,0,'т.4стр.2410гр.4 =  т.4стр.2020гр.4 -  т.4стр.2120гр.4 -  т.4стр.2220гр.4 -  т.4стр.2320гр.4',1,0,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(58,NULL,0,NULL,62,7,0,0,0,'т.4стр.2410гр.5 =  т.4стр.2020гр.5 -  т.4стр.2120гр.5 -  т.4стр.2220гр.5 -  т.4стр.2320гр.5',1,0,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(59,NULL,0,NULL,63,7,0,0,0,'т.4стр.2410гр.6 =  т.4стр.2020гр.6 -  т.4стр.2120гр.6 -  т.4стр.2220гр.6 -  т.4стр.2320гр.6',1,0,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(60,NULL,0,NULL,64,7,0,0,0,'т.4стр.2750гр.3 =  т.4стр.2710гр.3 -  т.4стр.2720гр.3 -  т.4стр.2730гр.3 -  т.4стр.2740гр.3',1,1,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(61,NULL,0,NULL,65,7,0,0,0,'т.4стр.2750гр.4 =  т.4стр.2710гр.4 -  т.4стр.2720гр.4 -  т.4стр.2730гр.4 -  т.4стр.2740гр.4',1,1,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(62,NULL,0,NULL,66,7,0,0,0,'т.4стр.2750гр.5 =  т.4стр.2710гр.5 -  т.4стр.2720гр.5 -  т.4стр.2730гр.5 -  т.4стр.2740гр.5',1,1,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(63,NULL,0,NULL,67,7,0,0,0,'т.4стр.2750гр.6 =  т.4стр.2710гр.6 -  т.4стр.2720гр.6 -  т.4стр.2730гр.6 -  т.4стр.2740гр.6',1,1,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(64,NULL,0,NULL,68,7,0,0,0,'т.2стр.114гр.6 =  т.2стр.111гр.6 +  т.2стр.112гр.6 +  т.2стр.113гр.6',1,11,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(65,NULL,0,NULL,69,7,0,0,0,'т.2стр.114гр.7 =  т.2стр.111гр.7 +  т.2стр.112гр.7 +  т.2стр.113гр.7',1,11,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(66,NULL,0,NULL,70,7,0,0,0,'т.2стр.130гр.6 =  т.2стр.100гр.6 +  т.2стр.110гр.6 +  т.2стр.120гр.6',1,11,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(67,NULL,0,NULL,71,7,0,0,0,'т.2стр.130гр.7 =  т.2стр.100гр.7 +  т.2стр.110гр.7 +  т.2стр.120гр.7',1,11,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(68,NULL,0,NULL,72,7,0,0,0,'т.2стр.144гр.6 =  т.2стр.141гр.6 +  т.2стр.142гр.6 +  т.2стр.143гр.6',1,11,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(69,NULL,0,NULL,73,7,0,0,0,'т.2стр.144гр.7 =  т.2стр.141гр.7 +  т.2стр.142гр.7 +  т.2стр.143гр.7',1,11,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(70,NULL,0,NULL,74,7,0,0,0,'т.2стр.150гр.6 =  т.2стр.130гр.6 -  т.2стр.140гр.6',1,12,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(71,NULL,0,NULL,75,7,0,0,0,'т.2стр.150гр.7 =  т.2стр.130гр.7 -  т.2стр.140гр.7',1,12,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(72,NULL,0,NULL,76,7,0,0,0,'т.5стр.283гр.3 =  т.5стр.280гр.3 -  т.5стр.281гр.3 -  т.5стр.282гр.3',1,1,1,'20130402','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(73,NULL,0,NULL,77,7,0,0,0,'т.5стр.283гр.4 =  т.5стр.280гр.4 -  т.5стр.281гр.4 -  т.5стр.282гр.4',1,2,1,'20130402','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(74,NULL,0,NULL,78,7,0,0,0,'т.5стр.283гр.5 =  т.5стр.280гр.5 -  т.5стр.281гр.5 -  т.5стр.282гр.5',1,3,1,'20130402','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(75,NULL,0,NULL,79,7,0,0,0,'т.5стр.283гр.6 =  т.5стр.280гр.6 -  т.5стр.281гр.6 -  т.5стр.282гр.6',1,4,1,'20130402','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(76,NULL,0,NULL,80,7,0,0,0,'т.5стр.293гр.3 =  т.5стр.290гр.3 -  т.5стр.291гр.3 -  т.5стр.292гр.3',1,5,1,'20130402','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(77,NULL,0,NULL,81,7,0,0,0,'т.5стр.293гр.4 =  т.5стр.290гр.4 -  т.5стр.291гр.4 -  т.5стр.292гр.4',1,6,1,'20130402','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(78,NULL,0,NULL,82,7,0,0,0,'т.5стр.293гр.5 =  т.5стр.290гр.5 -  т.5стр.291гр.5 -  т.5стр.292гр.5',1,7,1,'20130402','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(79,NULL,0,NULL,83,7,0,0,0,'т.5стр.293гр.6 =  т.5стр.290гр.6 -  т.5стр.291гр.6 -  т.5стр.292гр.6',1,9,1,'20130402','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(80,NULL,0,NULL,84,7,0,0,0,'т.2стр.110гр.5 =  т.5стр.284гр.3',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(81,NULL,0,NULL,85,7,0,0,0,'т.2стр.110гр.6 =  т.5стр.294гр.3',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(82,NULL,0,NULL,86,7,0,0,0,'т.2стр.111гр.5 =  т.5стр.284гр.4',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(83,NULL,0,NULL,87,7,0,0,0,'т.2стр.111гр.6 =  т.5стр.294гр.4',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(84,NULL,0,NULL,88,7,0,0,0,'т.2стр.112гр.5 =  т.5стр.284гр.5',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(85,NULL,0,NULL,89,7,0,0,0,'т.2стр.112гр.6 =  т.5стр.294гр.5',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(86,NULL,0,NULL,90,7,0,0,0,'т.2стр.113гр.5 =  т.5стр.284гр.6',1,10,1,'20130118','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(87,NULL,0,NULL,91,7,0,0,0,'т.2стр.113гр.6 =  т.5стр.294гр.6',1,10,1,'20130402','','','','РСВ-1','20130101','','=',1,'','')
INSERT #A VALUES(88,NULL,0,NULL,92,7,0,0,0,'т.8стр.336гр.5 =  т.8стр.335гр.5 /  т.8стр.334гр.5 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(89,NULL,0,NULL,93,7,0,0,0,'т.8стр.336гр.6 =  т.8стр.335гр.6 /  т.8стр.334гр.6 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(90,NULL,0,NULL,94,7,0,0,0,'т.9стр.343гр.3 =  т.9стр.342гр.3 /  т.9стр.341гр.3 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
INSERT #A VALUES(91,NULL,0,NULL,95,7,0,0,0,'т.9стр.343гр.4 =  т.9стр.342гр.4 /  т.9стр.341гр.4 *  100',1,0,1,'20130306','','','','РСВ-1','20130101','','=',0,'','')
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO
IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #A) <> 91
BEGIN
   INSERT #tabErrorLog VALUES ('Не сошлось количество строк в #A',0)
END

IF OBJECT_ID('tempdb..#B') IS NOT NULL
BEGIN
   DROP TABLE #B
END

CREATE TABLE #B ([LINK_RULE]       INT NULL,
                 [OrderRow]        INT NULL,
                 [VAL_TYPE]        TINYINT NULL,
                 [SIGN]            CHAR(2) NULL,
                 [LINK_FORM]       INT NULL,
                 [LINK_TABLE]      INT NULL,
                 [LINK_COL]        INT NULL,
                 [LINK_ROW]        INT NULL,
                 [PERIOD_FORM]     SMALLINT NULL,
                 [FACTOR]          FLOAT NULL,
                 [EXEC_PROC]       VARCHAR(250) NULL,
                 [EXEC_PROC_DESC]  VARCHAR(250) NULL,
                 [CODE_ROW]        VARCHAR(250) NULL,
                 [FILTER]          VARCHAR(1000) NULL,
                 [FILTER_DESC]     VARCHAR(250) NULL,
                 [MASKA]           VARCHAR(250) NULL,
                 [MASKA_DESC]      VARCHAR(250) NULL,
                 [CODE_FORM_ROW]   VARCHAR(25)  NULL,
                 [COL]             VARCHAR(100) NULL,
                 [ROW]             VARCHAR(100) NULL,
                 [TABLE]           VARCHAR(25)  NULL,
                 [START_DATE_FORM] DATETIME     NULL,
                 [PERIOD_YEAR]     SMALLINT     NULL,
                 [ATR_CODE]        VARCHAR(254) NOT NULL,
                 [PART]            TINYINT      NOT NULL,
                 [BEGIN_DATE]      DATETIME     NULL,
                 [PX]              FLOAT(53)    NOT NULL,
                 [PX_COMMENT]              VARCHAR(254)    NULL,
                 [Property]				TINYINT    DEFAULT (0))

SELECT @iERROR = @@ERROR

IF @iERROR <> 0
BEGIN
   INSERT #tabErrorLog VALUES ('CREATE TABLE #B',@iERROR)
END

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
PRINT 'INSERT #B'
INSERT #B VALUES(1,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(1,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(1,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(2,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(2,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(3,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(3,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(4,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(4,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(5,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(5,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(6,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(6,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(7,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(7,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(8,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(8,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(9,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(9,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(10,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(10,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(11,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(11,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(12,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(12,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','240','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(13,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','203','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','213','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,6,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','221','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,7,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','223','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,8,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','231','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(13,9,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','233','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','240','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(14,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','203','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','213','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,6,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','221','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,7,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','223','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,8,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','231','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(14,9,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','233','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','240','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(15,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','203','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','213','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,6,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','221','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,7,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','223','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,8,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','231','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(15,9,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','233','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','241','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(16,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','222','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(16,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','232','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','241','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(17,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','222','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(17,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','232','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','241','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(18,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','222','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(18,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','232','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','275','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(19,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','271','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','272','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','273','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(19,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','274','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','275','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(20,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','271','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','272','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','273','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(20,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','274','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','275','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(21,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','271','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','272','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','273','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(21,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','274','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','323','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(22,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','322','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(22,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','321','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,'','','','','','','','','4','323','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(23,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','322','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(23,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','321','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,'','','','','','','','','5','323','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(24,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','322','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(24,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','321','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,'','','','','','','','','3','333','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(25,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','332','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','331','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(25,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','333','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(26,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','332','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','331','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(26,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','333','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(27,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','332','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','331','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(27,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','336','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(28,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','335','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(28,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','334','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,'','','','','','','','','4','336','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(29,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','335','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','334','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(29,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','240','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(30,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','201','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','203','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','211','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','213','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,6,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','221','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,7,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','223','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,8,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','231','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(30,9,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','233','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','241','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(31,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','202','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','212','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','222','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(31,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','232','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','275','3',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(32,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','271','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','272','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','273','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(32,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','274','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','323','7',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(33,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','322','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','321','7',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(33,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','333','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(34,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','332','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','331','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(34,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350l','10',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(35,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350a','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350b','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350c','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350d','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,6,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350e','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,7,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350f','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,8,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350g','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,9,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350h','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,10,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350j','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(35,11,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','350k','10',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','363','11',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(36,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','362','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','361','11',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(36,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','375','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(37,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','372','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','373','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','374','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,5,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','371','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(37,6,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','375','12',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(38,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','372','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','373','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','374','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,5,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','371','12',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(38,6,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','383','13',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(39,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','382','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','381','13',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(39,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(40,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','250','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','252','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2500','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(40,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2520','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(41,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','251','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(41,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2510','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(42,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','276','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(42,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2760','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(43,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','250','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','252','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2500','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(43,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2520','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(44,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','251','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(44,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2510','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(45,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','276','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(45,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2760','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(46,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','250','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','252','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2500','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(46,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2520','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(47,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','251','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(47,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2510','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(48,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','276','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(48,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2760','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(49,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','250','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','252','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2500','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(49,5,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2520','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(50,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','251','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(50,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2510','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(51,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','276','3',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(51,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2760','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2400','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(52,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2010','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2030','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2110','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(52,6,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2210','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,7,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2230','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,8,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2310','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(52,9,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2330','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2400','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(53,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2010','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2030','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2110','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(53,6,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2210','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,7,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2230','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,8,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2310','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(53,9,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2330','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2400','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(54,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2010','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2030','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2110','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(54,6,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2210','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,7,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2230','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,8,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2310','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(54,9,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2330','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2400','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(55,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2010','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2030','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2110','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(55,6,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2210','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,7,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2230','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,8,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2310','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(55,9,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2330','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2410','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(56,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2020','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2120','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2220','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(56,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2320','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2410','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(57,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2020','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2120','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2220','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(57,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2320','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2410','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(58,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2020','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2120','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2220','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(58,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2320','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2410','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(59,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2020','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2120','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2220','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(59,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2320','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2750','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(60,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2710','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2720','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2730','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(60,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','2740','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2750','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(61,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2710','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2720','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2730','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(61,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','2740','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2750','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(62,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2710','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2720','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2730','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(62,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','2740','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2750','4',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(63,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2710','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2720','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2730','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(63,5,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','2740','4',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(64,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(64,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','114','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(65,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','111','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','112','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(65,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','113','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(66,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(66,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','130','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(67,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','100','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','110','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(67,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','120','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(68,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(68,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(68,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(68,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(69,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','144','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(69,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','141','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(69,3,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','142','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(69,4,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','143','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(70,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(70,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','150','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(71,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','130','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(71,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','7','140','2',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','283','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(72,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','280','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','281','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(72,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','282','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','283','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(73,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','280','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','281','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(73,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','282','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','283','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(74,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','280','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','281','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(74,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','282','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','283','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(75,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','280','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','281','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(75,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','282','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','293','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(76,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','290','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','291','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(76,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','292','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','293','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(77,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','290','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','291','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(77,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','292','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','293','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(78,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','290','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','291','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(78,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','292','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','293','5',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(79,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','290','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,3,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','291','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(79,4,0,'-',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','292','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(80,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(80,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','284','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(81,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','110','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(81,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','294','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(82,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(82,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','284','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(83,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','111','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(83,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','294','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(84,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(84,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','284','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(85,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','112','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(85,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','294','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(86,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(86,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','284','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(87,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','113','2',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(87,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','294','5',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','336','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(88,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','335','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','5','334','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(88,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','336','8',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(89,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','335','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','6','334','8',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(89,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','343','9',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(90,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','342','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','3','341','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(90,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,1,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','343','9',NULL,NULL,'',0,NULL,1,'',0)
INSERT #B VALUES(91,2,0,'+',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','342','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,3,0,'/',NULL,NULL,NULL,NULL,0,0,'','','','','','','','','4','341','9',NULL,NULL,'',1,NULL,1,'',0)
INSERT #B VALUES(91,4,1,'*',NULL,NULL,NULL,NULL,0,100,'','','','','','','','','','','',NULL,NULL,'',1,NULL,1,'',0)
END -- IF NOT EXISTS(SELECT * FROM #tabStop)
GO

IF NOT EXISTS(SELECT * FROM #tabStop) BEGIN
DECLARE @iERROR INT

IF (SELECT COUNT(*) FROM #B) <> 406
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-02-06 16:07:20.733',121) WHERE [LINK_FORM]=@iLINK_FORM

END -- IF NOT EXISTS(SELECT * FROM #tabStop)
ELSE BEGIN
	DECLARE @vcMessage VARCHAR(8000)
	SELECT @vcMessage = [CURRENT_DATE] FROM #tabStop
	IF @vcMessage = '2014-02-06 16:07:20.733'
	BEGIN
		SELECT @vcMessage = 'Форма РСВ-1 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма РСВ-1 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2014-02-06 16:07:20.733. Обновление отклонено.'
	END

	 IF OBJECT_ID('tempdb..#tabUpdateMessages') IS NOT NULL
	 BEGIN
		 INSERT #tabUpdateMessages([TXT]) VALUES (@vcMessage)
	 END
	 SELECT @vcMessage
END
GO

IF OBJECT_ID('tempdb..#tabInfo') IS NOT NULL DROP TABLE #tabInfo
SELECT * FROM #tabErrorLog

IF EXISTS(SELECT * FROM #tabErrorLog)
BEGIN
   ROLLBACK TRANSACTION SaveTran -- Восстановление точки сохранения.
END

DROP TABLE #tabErrorLog
DROP TABLE #tabStop

COMMIT TRANSACTION -- Фиксация транзакции.
GO


GO
/*Скрытые объекта Сведения  о трудовом стаже застрахованного лица (СЗВ-К)*/

if exists(select * from s_navigator  where code = 'SZV_K_REP_GATOR' and visible = 3)
begin
	UPDATE SN 
		set visible = 0 
	from s_navigator sn  where code = 'SZV_K_REP_GATOR' and visible = 3 
end




GO
-- Закрытие старой формы (AV_IMU) -- 
UPDATE RF
SET END_DATE = '20131231'
FROM dbo.REPORT_FORMS RF
WHERE RF.CODE = 'AV_IMU'
	AND RF.[START_DATE] = '20120101'
GO


GO
-- Закрытие старой формы --
UPDATE RF
SET END_DATE = '20121231'
FROM dbo.REPORT_FORMS RF
WHERE RF.CODE = 'ND_IMU'
	AND RF.[START_DATE] = '20111231'
GO


GO
-- Закрытие старой формы (ND_NP) -- 
UPDATE RF
SET END_DATE = '20131130'
FROM dbo.REPORT_FORMS RF
WHERE RF.CODE = 'ND_NP'
	AND RF.[START_DATE] = '20120801'
GO



GO
-- Закрытие старой формы (ND_TN) -- 
UPDATE RF
SET END_DATE = '20121231'
FROM dbo.REPORT_FORMS RF
WHERE RF.CODE = 'ND_TN'
	AND RF.[START_DATE] = '20120101'
GO


GO
if exists (select * from S_NAVIGATOR where NAME = 'Приказы о предоставлении отпуска' and [OBJECT] is null)
begin 
	update sn 
		set [OBJECT] = (SELECT  link  from S_OBJECTS where CODE = 'VACATION') 
	from S_NAVIGATOR sn where sn.NAME = 'Приказы о предоставлении отпуска'
end 

GO
EXECUTE dbo.X_FORM_VIEW_OPTIONS 'BV_DOC_AO_OPTIONS'
GO


GO
-- Таблица РКО для АО --
EXEC dbo.BK_FORM_VIEW_DOCUMENT_TABLE 'DOC_AO_RKO_TABLE'
EXEC dbo.BK_FORM_SAVE_DOCUMENT_TABLE 'DOC_AO_RKO_TABLE'
GO


GO
